PHP GD库调整大小照片 [英] PHP GD library resize photo
问题描述
我正在尝试使用PHP的GD库创建照片的缩略图.
I am attempting to create thumbnails of photos using PHP's GD library.
这是我正在采取的步骤.
Here are the steps I am taking.
- 创建GD映像资源.
- 获取图像的高度和宽度
- 创建一个100像素高,适当宽度的空白gd图像资源
- 将资源图像复制到空白的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']}");
}
正在保存图像,但是无法使用副本,缩略图中没有空白.
The images are saving, but the copy is not working, there is empty black space in the thumbnail picture.
这是原始图像:
这是用gd再次保存的图像:
This is the image saved again with gd:
这是缩略图:
我喜欢四倍检查imagecopyresize,据我了解,代码中的所有值都应该正确.
I've like quadruple checked imagecopyresize and from what I understand of it all the values in the code should be correct.
这是php.net提供的值:
Here is what php.net has for the values:
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 )
有人有什么主意吗?
推荐答案
Working with PHP/GD can be tedious, so I wrote a library to make things much easier: SimpleImage
使用SimpleImage,您可以在两行中创建一个缩略图:
With SimpleImage, you can create a thumbnail in two simple lines:
// 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
?
If you're still bent on doing it manually, check your imagecopyresized
parameters. Why is the width being multiplied by $ratio
?
这篇关于PHP GD库调整大小照片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!