为什么图像裁剪会去除透明度?

问题描述 投票:0回答:1

当我加载具有白色背景的图像时,我可以将白色更改为透明,从而产生具有透明背景的图像。在第一步之后,我想要裁剪透明图像,但之后它将失去透明度。

之后,我尝试先剪裁图像并使裁剪后的图像像我之前使用原始图像一样透明。使用原始图像它工作正常,但相同的方法不适用于裁剪图像。

header('Content-Type: image/png');

// Image resource
$image = imagecreatefrompng("/var/www/html".$_GET["image"]);

// STEP 1 Make background transparant
$white = imagecolorexact($image, 255, 255, 255); 
imagecolortransparent($image, $white);  

// STEP 2 Crop the image
$image = imagecrop($image, ['x' => 15, 'y' => 49, 'width' => 382, 'height' => 382]);

// Serve the image
imagepng($image);
imagedestroy($image);

在裁剪之前,图像是透明但未裁剪的,裁剪后图像调整大小但透明度丢失。切换第一步和第二步没有任何意义。

我也尝试使用imagecopyresampled而不是imagecrop来获得相同的结果。也没有任何结果切换步骤。

header('Content-Type: image/png');

// Image resources
$image = imagecreatefrompng("/var/www/html".$_GET["image"]);  
$new = imagecreatetruecolor(382, 382);

// STEP 1 Make background transparant
$white = imagecolorexact($image, 255, 255, 255); 
imagecolortransparent($image, $white);  

// STEP 2 Crop the image
imagecolortransparent($new, imagecolorallocatealpha($new, 255, 255, 255, 127));
imagealphablending($new, false);
imagesavealpha($new, true);
imagecopyresampled($new, $image, 0, 0, 15, 49, 382, 382, 382, 382);

// Serve the image
imagepng($new);
imagedestroy($new);

为什么这不符合我的预期?

php gd
1个回答
0
投票

现在有了它的工作..我认为问题是混合调色板和真正的彩色图像像04FS说。

function setTransparency($new_image,$image_source) {
  $transparencyIndex = imagecolortransparent($image_source); 
  $transparencyColor = array('red' => 255, 'green' => 255, 'blue' => 255); 

  if ($transparencyIndex >= 0) { 
    $transparencyColor = imagecolorsforindex($image_source, $transparencyIndex);    
  } 

  $transparencyIndex = imagecolorallocate($new_image, $transparencyColor['red'], $transparencyColor['green'], $transparencyColor['blue']); 
  imagefill($new_image, 0, 0, $transparencyIndex); 
  imagecolortransparent($new_image, $transparencyIndex);
}

// Image resource
$image = imagecreatefrompng("/var/www/html".$_GET["image"]); 
$imageNew = imagecreatetruecolor(382, 382);

setTransparency($imageNew, $image);

imagecopyresampled($imageNew, $image, 0, 0, 15, 49, 382, 382, 382, 382);

// Serve the image
header('Content-Type: image/png');
imagepng($imageNew);
imagedestroy($imageNew);
© www.soinside.com 2019 - 2024. All rights reserved.