将JPEG和PNG与透明背景合并到一个图像PHP

时间:2017-05-17 05:16:25

标签: php image

我有以下脚本用于将JPEG和PNG复制到名为base.png的现有PNG。在函数" transparent_background"我用透明度替换白色背景。这个功能就是问题所在。 Standlone功能正在浏览器中直接输出。请看评论" // imagepng($ img);"。但是,如果我将$ img从函数中返回,我认为它仍然是一个jpeg,这就是为什么它不透明。第二个功能仅用于调整大小。

<?php

function transparent_background($img) 
{
    $img = imagecreatefromjpeg($img); //or whatever loading function you need
    $colors= array("255","255","255");
    $remove = imagecolorallocate($img, $colors[0], $colors[1], $colors[2]);
    imagecolortransparent($img, $remove);
    //imagepng($img);
    return $img;
    imagedestroy($img);
}
function resize($img, $w){
    $img = imagecreatefromjpeg($img);
    $ratio = imagesx($img)/imagesy($img); 
    if( $ratio > 1) {
        $width = $w;
        $height = $w/$ratio;
    }
    else {
        $width = $w*$ratio;
        $height = $w;
    }
    $dst = imagecreatetruecolor($width,$height);
    imagecopyresampled($dst,$img,0,0,0,0,$width,$height,imagesx($img),imagesy($img));
    return $dst;
    imagedestroy($dst);
    imagedestroy($img);
}

$h="https://images-eu.ssl-images-amazon.com/images/I/415zYwg2-TL.jpg";
$base = imagecreatefrompng("base.png");
$logo = imagecreatefrompng("fs_logo_line.png");

$pos1=resize($h,"730");
$pos1=transparent_background($h);
imagecopy($base,$pos1,0, 5, 0, 0, imagesx($pos1),imagesy($pos1));
imagecopy($base,$logo,0, 1136, 0,0,imagesx($logo),imagesy($logo));

imagepng($base);

?>

我认为问题是,我从transparent_background函数返回jpeg,这就是为什么$ pos1中的图像不透明。我有什么想法可以解决这个问题?我试过ob_start&amp; ob_get_contents但这也没有用。

1 个答案:

答案 0 :(得分:0)

您可以使用PHP GD2库将两个图像合并在一起。

示例:

<?php
 # If you don't know the type of image you are using as your originals.
 $image = imagecreatefromstring(file_get_contents($your_original_image));
 $frame = imagecreatefromstring(file_get_contents($your_frame_image));

 # If you know your originals are of type PNG.
 $image = imagecreatefrompng($your_original_image);
 $frame = imagecreatefrompng($your_frame_image);

 imagecopymerge($image, $frame, 0, 0, 0, 0, 50, 50, 100);

 # Save the image to a file
 imagepng($image, '/path/to/save/image.png');

 # Output straight to the browser.
 imagepng($image);
?>

如果您希望在图片上保留PNG框架透明度,请在imagealphablending($frame,true);之前添加imagecopymerge()