[英]How to watermark GIF image with 24-bit PNG with transparency in PHP?
[英]PNG and GIF transparency lost
我在使用圖像和PHP時遇到問題。
我正在使用一個函數,該函數將根據我的限制調整圖像的大小,然后創建一個新圖像。
問題是當我要調整png或gif文件的大小時,透明度會丟失,生成黑色背景的圖像。
這是函數:
// Resize image - preserve ratio of width and height.
function resizeImage($sourceImage, $targetImage, $maxWidth, $maxHeight, $quality = 70)
{
// Obtain image from given source file.
$info = getimagesize($sourceImage);
$imgtype = image_type_to_mime_type($info[2]);
switch ($imgtype) {
case 'image/jpeg':
$image = imagecreatefromjpeg($sourceImage);
break;
case 'image/png':
$image = imagecreatefrompng($sourceImage);
break;
default:
die('Invalid image type.');
}
// Get dimensions of source image.
list($origWidth, $origHeight) = getimagesize($sourceImage);
if ($maxWidth == 0)
{
$maxWidth = $origWidth;
}
if ($maxHeight == 0)
{
$maxHeight = $origHeight;
}
// Calculate ratio of desired maximum sizes and original sizes.
$widthRatio = $maxWidth / $origWidth;
$heightRatio = $maxHeight / $origHeight;
// Ratio used for calculating new image dimensions.
$ratio = min($widthRatio, $heightRatio);
// Calculate new image dimensions.
$newWidth = (int)$origWidth * $ratio;
$newHeight = (int)$origHeight * $ratio;
// Create final image with new dimensions.
$newImage = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($newImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $origWidth, $origHeight);
imagejpeg($newImage, $targetImage, $quality);
// Free up the memory.
imagedestroy($image);
imagedestroy($newImage);
return true;
}
無論得到什么擴展名,您始終使用imagejpeg
,還有imagepng
和imagegif
。 如果您使用的是.gif或.png,則應使用它們
我說的是這一行:
imagejpeg($newImage, $targetImage, $quality);
您應該根據文件類型調用imagejpeg
, imagepng
或imagegif
。
除了以支持透明性的格式保存圖像外,還需要指示GD復制源中的透明性信息。 對於PNG-8和GIF,您必須手動將透明顏色(請參閱imagecolortransparent )從源復制並設置到目標,對於PNG-24,您必須保存alpha通道(請參見imagesavealpha )。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.