我想将上传的图像转换为原始格式(jpg、jpeg-rpng等),但我需要将这些图像的大小重新调整为150px宽和210px高。是否可以在复制时更改大小,或者必须进行转换?
这是不成功的:
$uploaddir1 = "/home/myweb/public_html/temp/sfds454.png";
$uploaddir2 = "/home/myweb/public_html/images/sfds454.png";
$cmd = "/usr/bin/ffmpeg -i $uploaddir1 -vframes 1 -s 150x210 -r 1 -f mjpeg $uploaddir2";
@exec($cmd);
您可以使用gd而不是ffmpeg。要转换图像或调整图像大小,请参见以下示例:http://ryanfait.com/resources/php-image-resize/resize.txt
gd的Php-lib:
http://php.net/manual/en/function.imagecopyresampled.php
该页面中还有一些调整脚本大小的示例。
我最近不得不解决这个问题,并实现了这个简单的缓存解决方案:
<?php
function send($name, $ext) {
$fp = fopen($name, 'rb');
// send the right headers
header("Content-Type: image/$ext");
header("Content-Length: " . filesize($name));
// dump the picture and stop the script
fpassthru($fp);
exit;
}
error_reporting(E_ALL);
ini_set('display_errors', 'On');
if (isset($_REQUEST['fp'])) {
$ext = pathinfo($_REQUEST['fp'], PATHINFO_EXTENSION);
$allowedExt = array('png', 'jpg', 'jpeg');
if (!in_array($ext, $allowedExt)) {
echo 'fail';
}
if (!isset($_REQUEST['w']) && !isset($_REQUEST['h'])) {
send($_REQUEST['fp']);
}
else {
$w = $_REQUEST['w'];
$h = $_REQUEST['h'];
//use height, width, modification time and path to generate a hash
//that will become the file name
$filePath = realpath($_REQUEST['fp']);
$cachePath = md5($filePath.filemtime($filePath).$h.$w);
if (!file_exists("tmp/$cachePath")) {
exec("gm convert -quality 80% -colorspace RGB -resize " .$w .'x' . $h . " $filePath tmp/$cachePath");
}
send("tmp/$cachePath", $ext);
}
}
?>
我注意到的一些事情:
- Graphicsmagick的转换速度比imagemagik快得多,尽管我没有用cuda处理测试转换
- 对于最终的产品,我使用ASP语言的原生图形库重新实现了这段代码。这又快了很多,但如果出现内存不足错误,就会中断(在我的工作站上运行良好,但在4GB RAM服务器上不起作用)