【问题标题】:Resize image before download and presentation using readfile() in PHP使用 PHP 中的 readfile() 在下载和演示之前调整图像大小
【发布时间】:2015-02-28 02:37:31
【问题描述】:
我想在下载和呈现给用户之前使用 PHP 在服务器端调整图像大小。这在上传期间无法完成,因为图像不断变化并使用 FTP 上传。我正在使用以下代码来呈现图像
header('Content-Type: image/jpeg');
readfile($img . $filename . "." . $ext);
这是否可以通过 PHP 来完成,因为我想减少图像的下载大小;理想情况下不写入磁盘(因为用户不断访问该文件)。
感谢您的帮助。
【问题讨论】:
标签:
php
image
image-processing
optimization
web
【解决方案1】:
如果您安装了GD 库,则无需将其写入磁盘即可执行所需操作。
<?php
$filename = 'images/picture.jpg';
//the resize will be a percent of the original size
$percent = 0.5; // 50%
// Content type
header('Content-Type: image/jpeg');
// Get new sizes
list($width, $height) = getimagesize($filename);
$newwidth = $width * $percent;
$newheight = $height * $percent;
// Load
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg($filename);
// Resize
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
imagejpeg($thumb); // this will output image data
// if you need much lower size of image try experimenting with quality param
// imagejpeg($thumb,$saveToFile=null, $quality=70);
imagedestroy($thumb); //free some memory