我想让用户上传化身类型的图像在各种格式(的GIF,JPEG,和PNG至少),但将它们保存为PNG数据库斑点。如果图像过大,像素,我想在DB插入之前调整它们的大小。
使用GD进行大小调整和PNG转换的最佳方式是什么?
编辑:遗憾的是,在我需要使用的服务器上只有GD可用,没有ImageMagick。
发布于 2008-08-22 13:49:01
<?php
/*
Resizes an image and converts it to PNG returning the PNG data as a string
*/
function imageToPng($srcFile, $maxSize = 100) {
list($width_orig, $height_orig, $type) = getimagesize($srcFile);
// Get the aspect ratio
$ratio_orig = $width_orig / $height_orig;
$width = $maxSize;
$height = $maxSize;
// resize to height (orig is portrait)
if ($ratio_orig < 1) {
$width = $height * $ratio_orig;
}
// resize to width (orig is landscape)
else {
$height = $width / $ratio_orig;
}
// Temporarily increase the memory limit to allow for larger images
ini_set('memory_limit', '32M');
switch ($type)
{
case IMAGETYPE_GIF:
$image = imagecreatefromgif($srcFile);
break;
case IMAGETYPE_JPEG:
$image = imagecreatefromjpeg($srcFile);
break;
case IMAGETYPE_PNG:
$image = imagecreatefrompng($srcFile);
break;
default:
throw new Exception('Unrecognized image type ' . $type);
}
// create a new blank image
$newImage = imagecreatetruecolor($width, $height);
// Copy the old image to the new image
imagecopyresampled($newImage, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
// Output to a temp file
$destFile = tempnam();
imagepng($newImage, $destFile);
// Free memory
imagedestroy($newImage);
if ( is_file($destFile) ) {
$f = fopen($destFile, 'rb');
$data = fread($f);
fclose($f);
// Remove the tempfile
unlink($destFile);
return $data;
}
throw new Exception('Image conversion failed.');
}
发布于 2008-08-22 13:07:29
如果您想使用gdlib,请使用gdlib 2或更高版本。它有一个名为imagecopyresampled()的函数,该函数将在调整大小的同时对像素进行插值,并且看起来更好。
另外,我经常听到网上有人说,在数据库中存储图像是不好的形式:
<>H19>设置正确的缓存/超时/E-tag标头,以便客户端可以正确缓存镜像。如果不正确执行此操作,影像服务脚本将在每次请求时被命中,从而增加服务器甚至more.
上的负载
我能看到的唯一好处是,您不需要保持数据库和映像文件的同步。尽管如此,我还是建议你不要这么做。
发布于 2008-08-22 13:23:33
您确定服务器上没有ImageMagick吗?
我邀请您使用PHP (问题用PHP标记)。我使用的托管公司没有根据phpinfo()打开ImageMagick扩展。
但是当我问他们关于ImageMagick的问题时,他们说这是PHP代码中可用的PHP程序的列表。很简单-- PHP中没有IM接口,但我可以直接从PHP调用IM程序。
我希望你也有同样的选择。
我非常同意--将图像存储在数据库中不是一个好主意。
https://stackoverflow.com/questions/22259
复制相似问题