[英]PHP GD library resize photo
我正在尝试使用PHP的GD库创建照片的缩略图。
这是我正在采取的步骤。
这是我的代码:
private function getExtension($filename) {
$position=strrpos($filename, '.');
$extension = strtolower(substr($filename, $position+1));
if ($extension == "jpg") {
$extension = "jpeg";
}
return $extension;
}
public function saveImage($parameters) {
$extension=$this->getExtension($parameters['filename']);
$createImageFunc="imagecreatefrom".$extension;
$imgResource=$createImageFunc(SITE_PATH."tmp/{$parameters['filename']}");
$width=imagesx($imgResource);
$height=imagesy($imgResource);
$ratio=$height/$width;
$thumbnail=imagecreatetruecolor(100, 100*$ratio);
imagecopyresized($thumbnail, $imgResource, 0, 0, 0, 0, 100*$ratio, 100, $width, $height);
$imgResult=imagejpeg($imgResource, SITE_PATH."images/{$parameters['galleryName']}/{$parameters['filename']}");
$thumbResult=imagejpeg($thumbnail, SITE_PATH."images/{$parameters['galleryName']}/thumbnails/{$parameters['filename']}");
}
图像正在保存,但是副本无法使用,缩略图中没有空白。
这是原始图像:
这是用gd再次保存的图像:
这是缩略图:
我喜欢四重检查imagecopyresize,据我了解,代码中的所有值都应该正确。
这是php.net的值:
bool imagecopyresized ( resource $dst_image , resource $src_image , int $dst_x , int $dst_y , int $src_x , int $src_y , int $dst_w , int $dst_h , int $src_w , int $src_h )
任何人有任何想法吗?
看看这个: PHP / GD Imagestyle
您可以轻松创建缩略图或所需的所有内容
// create a thumbnail
$thumb = imagestyle($image,'autosize:100 100');
// resize the image # resize:200 0; means width=200 height=auto
$resized = imagestyle($image,'resize:200 0;');
// crop it # left=0, top=50, width=200, height=200
$cropped = imagestyle($image,'crop:0 50 200 200;');
// and more
使用PHP / GD可能很乏味,所以我写了一个库来简化事情: SimpleImage
使用SimpleImage,您可以在两行中创建一个缩略图:
// Load image from image.jpg
$image = new \claviska\SimpleImage('image.jpg');
// Create a 100x100 thumbnail, convert to PNG, and save to thumb.png
$image->thumbnail(100, 100)->toFile('thumb.png', 'image/png');
如果您仍然想手动执行此操作,请检查imagecopyresized
参数。 为什么将宽度乘以$ratio
?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.