添加图像缩略图以保存在mysql数据库中

时间:2019-04-20 18:44:34

标签: php mysql image

这是添加缩略图的代码。它可以很好地读取图像,即使将缩略图保存在文件夹中也可以。我只是无法将其保存在数据库中。 $ 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);

1 个答案:

答案 0 :(得分:0)

您必须将数据库列设置为Binary Large OBject(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';
 }
}
?>