我正在尝试使用 PHP 中的 GD 库使图像透明,但运行以下代码,只有一部分是透明的

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

我正在尝试使用 PHP 中的 GD 库使图像透明,但运行以下代码,只有一部分是透明的。

$image = imagecreatefrompng("$second");  
imagealphablending($image, false);
$col_transparent = imagecolorallocatealpha($image, 0, 0, 0, 127);
imagefill($image, 0, 0, $col_transparent);  // set the transparent colour as the background.
imagecolortransparent ($image, $col_transparent); // actually make it transparent
imagesavealpha($image, TRUE);
header( 'Content-Type: image/png' );
imagepng($image);

这里有原始图像:https://postimg.org/image/y68nw57z1/
这是生成的图像:https://postimg.org/image/o4n3t6ic7/

如您所见,结果图像中存在保持白色的部分。
我该如何解决这个问题?

php image gd transparent
2个回答
1
投票

您正在用洪水填充替换图像的白色像素,但这不适用于完全被非白色像素包围的像素(如在任何绘画程序中)。相反,您可以修改白色的定义以使其透明:

$image = imagecreatefrompng($second);
imagetruecolortopalette($image, false, 255);
$index = imagecolorclosest($image, 255, 255, 255); // find index of white.
imagecolorset($image, $index, 0, 0, 0, 127); // replace white with transparent black.
header('Content-Type: image/png');
imagepng($image);

0
投票

您的解决方案效果很好。这是一些代码来证明这一点。我正在使用 Google API 创建一个白色背景的二维码。然后使用您的代码将白色更改为透明,我以红色背景显示二维码。

<?php
// Use Google api to create qr code with white background
//$qrContentText = 'This is a Test';
$qrContentText = 'https://google.com';
$encodedQrContentText = urlencode($qrContentText);
$src = 'https://chart.apis.google.com/chart?cht=qr&chs=540x540&chld=H&choe=UTF-8&chl='.$encodedQrContentText;
$ch = curl_init();
$timeout = 0;
curl_setopt ($ch, CURLOPT_URL, $src);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
// Getting binary data
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);
$sourceQRImage = imagecreatefromstring($response);
// Make white background transparent instead
imagetruecolortopalette($sourceQRImage, false, 255);
$index = imagecolorclosest($sourceQRImage, 255, 255, 255); // find index of white.
imagecolorset($sourceQRImage, $index, 0, 0, 0, 127); // replace white with transparent black.
// Get height & width of image
$sourceQRWidth = intval( imagesx( $sourceQRImage ) );
$sourceQRHeight = intval( imagesy( $sourceQRImage ) );
// Display image in the browser
ob_start();
imagepng($sourceQRImage);
$ImageData=ob_get_contents();
ob_end_clean();
echo '<div style="background-color: red; width: ' . $sourceQRWidth . 'px; height: ' . $sourceQRHeight . 'px"><img src="data:image/png;base64,'.base64_encode($ImageData).'"></div>';
imagedestroy($sourceQRImage);
?>
© www.soinside.com 2019 - 2024. All rights reserved.