使用PHP创建一个透明的png文件
目前,我想创建一个最低质量的透明png 守则:使用PHP创建一个透明的png文件,php,image,png,imagecreatefrompng,Php,Image,Png,Imagecreatefrompng,目前,我想创建一个最低质量的透明png 守则: <?php function createImg ($src, $dst, $width, $height, $quality) { $newImage = imagecreatetruecolor($width,$height); $source = imagecreatefrompng($src); //imagecreatefrompng() returns an image identifier representin
<?php
function createImg ($src, $dst, $width, $height, $quality) {
$newImage = imagecreatetruecolor($width,$height);
$source = imagecreatefrompng($src); //imagecreatefrompng() returns an image identifier representing the image obtained from the given filename.
imagecopyresampled($newImage,$source,0,0,0,0,$width,$height,$width,$height);
imagepng($newImage,$dst,$quality); //imagepng() creates a PNG file from the given image.
return $dst;
}
createImg ('test.png','test.png','1920','1080','1');
?>
但是,也存在一些问题:
imagecreatefrompng('test.png')
尝试打开文件test.png
,然后可以使用GD函数编辑该文件
至(2)
启用alpha通道imagesavealpha($img,true)的保存代码>被使用。
下面的代码通过启用alpha保存并用透明度填充来创建200x200px大小的透明图像
<?php
$img = imagecreatetruecolor(200, 200);
imagesavealpha($img, true);
$color = imagecolorallocatealpha($img, 0, 0, 0, 127);
imagefill($img, 0, 0, $color);
imagepng($img, 'test.png');
看看:
示例函数用于复制透明PNG文件:
<?php
function copyTransparent($src, $output)
{
$dimensions = getimagesize($src);
$x = $dimensions[0];
$y = $dimensions[1];
$im = imagecreatetruecolor($x,$y);
$src_ = imagecreatefrompng($src);
// Prepare alpha channel for transparent background
$alpha_channel = imagecolorallocatealpha($im, 0, 0, 0, 127);
imagecolortransparent($im, $alpha_channel);
// Fill image
imagefill($im, 0, 0, $alpha_channel);
// Copy from other
imagecopy($im,$src_, 0, 0, 0, 0, $x, $y);
// Save transparency
imagesavealpha($im,true);
// Save PNG
imagepng($im,$output,9);
imagedestroy($im);
}
$png = 'test.png';
copyTransparent($png,"png.png");
?>
1)您可以创建一个新的png文件,而无需任何现有文件。
2) 因为使用了imagecreatetruecolor(),所以得到的是黑色图像代码>。它创建了一个具有黑色背景的高质量图像。由于需要最低质量的图像,请使用imagecreate()代码>
您可以在本文中阅读更多内容:谢谢您的帮助!你介意教我如何最小化png文件的大小吗?在imagepng函数中设置“9”质量级别是我唯一能做的事情吗?感谢imagepng
s默认的“质量”设置(应命名为压缩,因为png
s压缩是无损的)是9(好吧,我测试时没有设置质量(234Bytes
),质量为0(几百KB
),设置为9(234字节))。所以我想这是GD能做的最好的了。这让我的黑线消失了
<?php
$tt_image = imagecreate( 100, 50 ); /* width, height */
$background = imagecolorallocatealpha( $tt_image, 0, 0, 255, 127 ); /* In RGB colors- (Red, Green, Blue, Transparency ) */
header( "Content-type: image/png" );
imagepng( $tt_image );
imagecolordeallocate( $background );
imagedestroy( $tt_image );
?>