Che*_*oft 9 php database png gd image
我想允许用户上传各种格式的头像类型图像(至少GIF,JPEG和PNG),但要将它们全部保存为PNG数据库BLOB.如果图像是超大的,按像素,我想在DB插入之前调整它们的大小.
使用GD进行大小调整和PNG转换的最佳方法是什么?
编辑:可悲的是,只有GD才能在我需要使用的服务器上使用,没有 ImageMagick.
小智 24
<?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.');
}
Run Code Online (Sandbox Code Playgroud)
您的流程步骤应如下所示:
ImageMagick更快,生成更好的图像,更易于配置,最终(IMO)更容易编码.
@ceejayoz只是等待新的GD - 这是像MySQLi的OOP,它实际上并不坏:)
| 归档时间: |
|
| 查看次数: |
16195 次 |
| 最近记录: |