在我的网站上,用户可以上传任意比例的3张图片,我想创建一个包含3个缩略图的动画GIF。 因为比率可能不同,动画GIF必须具有:
所以我用透明背景创建了3个max_width x max_height缩略图,然后将缩小后的图像放在里面。
我担心的是深黑色变得透明:
这段代码的灵感来自Mihai Iorga的回答:
foreach ($jpg_files as $key => $photo) {
// Identification de largeur et hauteur max des vignettes, pour centrage ultérieur
$thumb_w = $w_array[$key];
$thumb_h = $h_array[$key];
list($w_orig, $h_orig) = getimagesize($photo);
if($thumb_w> $thumb_h) {
$off_y=ceil(($max_thumb_h-$thumb_h)/2);
$off_x=0;
} elseif($thumb_h> $thumb_w) {
$off_x=ceil(($max_thumb_w-$thumb_w)/2);
$off_y=0;
}
else {
$off_x=$off_y=0;
}
// Création des vignettes GIF centrées sur fond transparent
$src = "";
$src = imagecreatefromjpeg($photo);
$new_img = imagecreatetruecolor($max_thumb_w, $max_thumb_h);
imagealphablending($new_img, false);
imagesavealpha($new_img, true);
imagecopyresampled($new_img, $src, $off_x, $off_y, 0, 0, $thumb_w, $thumb_h, $w_orig, $h_orig);
// create a new image with max size
$maxsize = imagecreatetruecolor($max_thumb_w, $max_thumb_h);
// add 1x1 gif and resize, then copy over $maxsize
$background = imagecreatefromgif('images/1pix_transparent.gif'); // transparent 1x1 gif
imagecopyresampled($maxsize, $background, 0, 0, 0, 0, $max_thumb_w, $max_thumb_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_thumb_w, $max_thumb_h, 100);
imagecopy($maxsize, $new_img, 0, 0, 0, 0, $max_thumb_w, $max_thumb_h);
// save
imagegif($maxsize, $uploadDir.'/thumb_'.$NewFileNameNoExt.$key.'.gif');
// destroy temp images
imagedestroy($maxsize);
imagedestroy($new_img);
imagedestroy($background);
imagedestroy($src);
array_push($gif_array, $uploadDir.'/thumb_'.$NewFileNameNoExt.$key.'.gif');
$framed[$key] = 150;
}
$thumbName = $uploadDir.'/thumb_'.$NewFileNameLeft.'.gif';
include "includes/GIFEncoder.class.php";
$gif = new GIFEncoder($gif_array, $framed, 0, 2, 0, 0, 0, "url");
fwrite(fopen($thumbName, "wb"),$gif->GetAnimation());