以下是一个使用GD库生成缩略图的示例代码,同时从MySQL数据库中获取图像数据:
<?php
// 连接数据库
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// 从数据库获取图像数据
$sql = "SELECT image FROM images WHERE id = 1"; // 假设图像数据存储在名为images的表中
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
$imageData = $row['image'];
// 创建图像资源
$image = imagecreatefromstring($imageData);
// 创建缩略图
$thumbnailWidth = 200; // 缩略图宽度
$thumbnailHeight = 200; // 缩略图高度
$thumbnail = imagecreatetruecolor($thumbnailWidth, $thumbnailHeight);
imagecopyresampled($thumbnail, $image, 0, 0, 0, 0, $thumbnailWidth, $thumbnailHeight, imagesx($image), imagesy($image));
// 输出缩略图
header('Content-Type: image/jpeg');
imagejpeg($thumbnail);
// 释放资源
imagedestroy($image);
imagedestroy($thumbnail);
} else {
echo "No image found.";
}
$conn->close();
?>
请注意,此示例假设图像数据存储在名为images
的表中,其中包含一个名为image
的列。您需要根据自己的数据库结构进行相应的更改。
此示例还假设图像数据是以二进制格式存储在数据库中。如果您的图像数据以文件路径的形式存储在数据库中,您需要使用file_get_contents()
函数将其读取为二进制数据。
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站