我正在尝试使用cropThumbnailImage
调整图像大小。我使用cropThumbnailImage
,因为它调整到原始图像的较短长度,并在两侧相等地裁剪较长一侧的图像,以便图像的中心部分保持未裁剪。这适用于jpg图像,但对于png图像,调整大小的png会得到黑色背景。
以下是我使用的代码。
$image = new 'Imagick($src);
// resize & crop
$image->cropThumbnailImage($width, $height);
// save new resized file
$image->writeImage($dest);
对以下png图像运行此代码。
http://tuxpaint.org/stamps/stamps/animals/birds/cartoon/tux.pnghttp://www.cs.csubak.edu/~mcabrera/CS211/transparent.pnghttp://www.tcarms.com/media/assets/productPhotos/006_G2%20Contender/png/Pistol_12in_Ribbed_Blued_2720.png
根据需要调整输出图像的大小,但png图像的背景为黑色。
尝试从此处添加以下行,但未成功。
imagealphablending( $image, false );
imagesavealpha( $image, true );
网络上还有其他解决方案可以实现png图像的大小调整,但我没有找到像cropThumbnailImage
那样调整图像大小的解决方案。
使用以下片段保留透明度:
$im = new Imagick($imgPath);
$im->setImageFormat('png');
$im->writeImage('/files/thumbnails/new_title.png');
-
你的JPG没有透明度。。。JPG不是一个透明的图像。。。PNG和GIF在这里是必要的。
-
如果你参考的是PNG,有一个PHP代码可以帮助你透明地调整PNG的大小:
$x=";坐标-X表示作物";;
$y=";坐标-y表示作物";;
$w=";宽度";;
$h=";高度";;
$img=imagecreatefrompng($img_path);
imagealphabiling($img,true);
$img_cutted=imagecreatetruecolor($w,$h);
imagesavealpha($img_cutted,true);
imagealphablending($img_cutted,false);
$transparent=imagecolorallocatelpha($img_cutted,0,0,127);
imagefill($img_cutted,0,0,$transparent);
imagecopy重采样($img_cutted,$img,0,0,$x,$y,$w,$h,$w和$h);//你也可以在这里使用imagecopy()
imagepng($img_cutted,"your_image_cropped.png",2);
imagedestroy($img);
imagedestroy($img_cutted);
编辑:试试这个:
$image=imagecreatefrompng($filename);
$new_image=imagecreatetruecolor($width,$height);//新的宽度和高度
imagealphabiling($new_image,false);
imagesavealpha($new_image,true);
imagecopy-resampled($new_image,$image,0,0,0,0,$width,$height,imagesx($image),imagesy($image));
$image=$new_image;
//保存
imagealphabiling($image,false);
imagesavealpha($image,true);
imagepng($image,$filename);
不要忘记定义$filename、$width、$height