Php 创建图像的缩略图,然后将其保存到数据库中
我正在创建一个图像的缩略图,然后将其保存到数据库中,但我不知道怎么做。这是我的密码Php 创建图像的缩略图,然后将其保存到数据库中,php,mysql,Php,Mysql,我正在创建一个图像的缩略图,然后将其保存到数据库中,但我不知道怎么做。这是我的密码 function createThumbs( $pathToImages, $pathToThumbs, $thumbWidth ) { $pathToImages = "../uploads/images/"; // open the directory $dir = opendir( $pathToImages ); // loop th
function createThumbs( $pathToImages, $pathToThumbs, $thumbWidth )
{
$pathToImages = "../uploads/images/";
// open the directory
$dir = opendir( $pathToImages );
// loop through it, looking for any/all JPG files:
while (false !== ($fname = readdir( $dir ))) {
// parse path for the extension
$info = pathinfo($pathToImages . $fname);
// continue only if this is a JPEG image
if ( strtolower($info['extension']) == 'jpg' )
{
$pathToThumbs = "../uploads/images/thumbs/";
//echo "Creating thumbnail for {$fname} <br />";
// load image and get image size
$img = imagecreatefromjpeg( "{$pathToImages}{$fname}" );
$width = imagesx( $img );
$height = imagesy( $img );
// calculate thumbnail size
$new_width = $thumbWidth;
$new_height = floor( $height * ( $thumbWidth / $width ) );
// create a new temporary image
$tmp_img = imagecreatetruecolor( $new_width, $new_height );
// copy and resize old image into new image
imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width,$new_height, $width, $height );
// save thumbnail into a file
imagejpeg( $tmp_img, "{$pathToThumbs}{$fname}" );
$thumbimage = $fname;
}
}
// close the directory
closedir( $dir );
}
createThumbs("/uploads/documents","/uploads/images/thumbs/",100);
函数createThumbs($pathToImages、$pathToThumbs、$thumbWidth)
{
$pathToImages=“../uploads/images/”;
//打开目录
$dir=opendir($pathToImages);
//循环浏览,查找任何/所有JPG文件:
while(false!=($fname=readdir($dir))){
//解析扩展的路径
$info=pathinfo($pathToImages.$fname);
//仅当这是JPEG图像时才继续
如果(strtolower($info['extension'])=='jpg')
{
$pathToThumbs=“../uploads/images/thumbs/”;
//echo“为{$fname}
创建缩略图”;
//加载图像并获取图像大小
$img=imagecreatefromjpeg(“{$pathToImages}{$fname}”);
$width=imagesx($img);
$height=imagesy($img);
//计算缩略图大小
$new_width=$thumbWidth;
$new_height=地板($height*($thumbWidth/$width));
//创建新的临时映像
$tmp\u img=ImageCreateTureColor($new\u width,$new\u height);
//将旧图像复制并调整大小为新图像
imagecopyresized($tmp\u img,$img,0,0,0,$new\u width,$new\u height,$width,$height);
//将缩略图保存到文件中
图像jpeg($tmp_img,“{$pathToThumbs}{$fname}”);
$thumbimage=$fname;
}
}
//关闭目录
closedir($dir);
}
createThumbs(“/uploads/documents”,“/uploads/images/thumbs/”,100);
创建缩略图很好,但现在我不知道如何将其保存在db中(缺乏技能)为什么不将结果保存在文件中 我想您必须在数据库字段中选择文本类型,然后将图像内容保存在那里 并读取具有“Content-type:image/jpg”标题的不同php文件中的数据 例如:
$query = "SELECT image FROM youtablename WHERE id = 10";
$result = mysql_query($query) or die('Error, query failed');
$content=mysql_result($result,0,"image");
header("Content-type: image/jpg");
echo $content;
您可以使用Dropbox API自动生成缩略图。我认为在数据库中保存二进制文件是我们可能犯的最严重的错误。特别是对于性能和文件管理来说,这变得非常困难。我建议您将图像保存在文件中,并在数据库中只保留url。如果您需要保护您的图像不被公开,可以使用.htaccess来实现