我正在尝试使用 PHP 的 GD 库创建照片的缩略图。
以下是我正在采取的步骤。
- 创建GD图像资源。
- 获取图像的高度和宽度
- 创建一个空白的 gd 图像资源,高度为 100 像素,宽度适当
- 将资源图像复制到空白 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']}");
}
图像正在保存,但复制不起作用,缩略图中有空白的黑色区域。
This is the original Image:
This is the image saved again with gd:
This is the thumbnail:
我喜欢四重检查 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 )
有人有什么想法吗?