我想用透明背景调整两种类型的图像(png,gif)...
但是在png中,它在原始图像的大尺寸下效果很好。 例如。原始文件尺寸为150x150
更改为200x200或超过原始尺寸,效果很好。但在100x100中显示
然后最后一个GIF不起作用。
这是我的png代码
$new_img = imagecreatetruecolor($max_w, $max_h); imagealphablending($new_img, false); imagesavealpha($new_img, true); $transparentindex = imagecolorallocatealpha($new_img, 255, 255, 255, 127); imagefill($new_img, 0, 0, $transparentindex); imagepng($new_img, $dir); Here my code for gif imagegif($new_img, $dir);
答案 0 :(得分:2)
我不知道PHP,但这似乎可以解决问题:
#!/usr/local/bin/php -f
<?php
$neww=100;
$newh=100;
// Load original image and get its dimensions
$img = imagecreatefrompng("badge.png");
$w=imagesx($img);
$h=imagesy($img);
// Create output image, and fill with lots of transparency
$out = imagecreatetruecolor($neww,$newh);
imagealphablending($out,false);
$transparentindex = imagecolorallocatealpha($out,0,0,0,127);
imagefill($out,0,0,$transparentindex);
imagesavealpha($out, true);
// Copy original image, reized on top
imagecopyresized($out,$img,0,0,0,0,$neww,$newh,$w,$h);
imagepng($out,"out.png");
?>
答案 1 :(得分:2)
这是一个小黑客:) 没有任何其他想法。
它涉及第二张图片(1x1 trasparent gif)
imagecolortransparent()
获取rgb索引imagecopymerge()
张图片
$dir = 'http://i.stack.imgur.com/DbhrJ.png';
$max_w = 50;
$max_h = 50;
// get image size
list($src_w, $src_h) = getimagesize($dir);
if ($src_w > $max_w) {
$ratio = $max_w / $src_w;
$max_w = $src_w * $ratio;
}
else if ($src_h > $max_h) {
$ratio = $max_h / $src_h;
$max_h = $src_h * $ratio;
}
// resize image to $max_w and $max_h, and also save alpha
$src = imagecreatefromstring(file_get_contents($dir));
$new_img = imagecreatetruecolor($max_w, $max_h);
imagealphablending($new_img, false);
imagesavealpha($new_img, true);
imagecopyresampled($new_img, $src, 0, 0, 0, 0, $max_w, $max_h, $src_w, $src_h);
// create a new image with $max_w and $max_h
$maxsize = imagecreatetruecolor($max_w, $max_h);
// add 1x1 gif and resize, then copy over $maxsize
$background = imagecreatefromgif("http://i.imgur.com/atRjCdk.gif"); // transparent 1x1 gif
imagecopyresampled($maxsize, $background, 0, 0, 0, 0, $max_w, $max_h, 1, 1);
// allocate transparency
$transparent = imagecolortransparent($maxsize);
$transparent_index = imagecolorallocate($maxsize, $transparent['red'], $transparent['green'], $transparent['blue']);
imagecolortransparent($maxsize, $transparent_index);
// image copy
imagecopymerge($maxsize, $new_img, 0, 0, 0, 0, $max_w, $max_h, 100);
// save or output
imagegif($maxsize, $path_to_save);
// destroy images
imagedestroy($maxsize);
imagedestroy($new_img);
imagedestroy($background);
imagedestroy($src);