php - 添加图像的缩略图以保存在 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);
解决方案
您必须将数据库列设置为二进制大对象 (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';
}
}
?>
推荐阅读
- java - GridWorld 中的 NullPointerException
- python - 尝试查找不再在列表中的事物的索引而导致的错误
- vuex - 如何将参数从 Nuxt 组件传递给 Vuex 操作
- angular - Angular - 仅打印 ag-Grid 数据
- omnet++ - 使用 VeinsInetMobility 和 TraCIMobility
- tags - 创建标签的 strpos 问题
- android - 过期后如何在 Flutter 应用程序中更新 Firebase 令牌并存储它?
- java - 为什么我的图形邻接列表不起作用?
- javascript - why neither document or window is defined
- python - Python - 按最小值排序列表