首页 > 解决方案 > 添加图像的缩略图以保存在 mysql 数据库中

问题描述

这是添加拇指图像的代码。它可以很好地读取图像,即使我将缩略图保存在文件夹中,它也可以。我只是无法将其保存在数据库中。$x 是循环中的计数器。

如果我读取图像并将其保存在数据库中而不更改大小,它可以工作,但在我更改大小后就不行了。

// Create the thumbnail

$picture = "images/" . str_replace(" ", '%20', $images[$x]);
$image = file_get_contents("$picture");
$source = imagecreatefromstring($image);

$width = imagesx($source);
$height = imagesy($source);

$thumb = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($thumb, $source, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);

echo "image created";

// End thumbnail creation


$thumb = mysql_real_escape_string($thumb);
$query = "UPDATE tablename SET thumb = '$thumb' WHERE id = $x";

$result = mysql_query($query);

标签: phpmysqlimage

解决方案


您必须将数据库列设置为二进制大对象 (BLOB)。由于您无法将图像上传到数据库,因此您必须将图像转换为二进制格式然后上传。假设您从一个表单中获取它,即您的 PHP 代码。

<?php
if(isset($_FILES['image']['name'])){
// *** Add your validation code here *** //
// Include Connection
     include_once('conn.php');

 // Get Image
 $name = $_FILES['image']['name'];
 $type = $_FILES['image']['type'];
 $get_content = file_get_contents($_FILES['image']['tmp_name']);
 $escape = mysql_real_escape_string($get_content);
 $sql = "INSERT INTO `img`.`dbimg` (`ID`, `name`, `src`, `type`) VALUES (NULL, '$name', '$escape', '$type');";
 if(mysql_query($sql)){
 echo 'Image inserted to database';
 }else{
 echo 'Error data inserting';
 }
}
?>

推荐阅读