【问题标题】:Merge JPEG and PNG with transparent Background to one Image PHP将具有透明背景的 JPEG 和 PNG 合并到一个图像 PHP
【发布时间】:2017-10-16 09:39:48
【问题描述】:

我有以下脚本用于将 JPEG 和 PNG 处理为名为 base.png 的现有 PNG。在函数“transparent_background”中,我用透明度替换了白色背景。这个功能是有问题的。独立的函数直接在浏览器中处理输出。请看注释掉“//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 和 ob_get_contents 但这也没有用。

【问题讨论】:

    标签: php image


    【解决方案1】:

    您可以使用 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 帧透明度,请在 imagecopymerge() 之前添加 imagealphablending($frame,true);

    【讨论】:

    • 谢谢,@Vishwas Soni。我会试试的。但我认为问题出在函数 transparent_background 内。我将 jpeg 推送到执行透明度操作的函数,并且不使用 imagepng 将文件输出到浏览器/文件。所以我认为问题在于我从函数返回了一个 jpeg。那么有没有办法将jpeg转换为png而不输出到浏览器或文件。就在一个变量内。
    • @swapfile 这个答案可能会对您有所帮助。 stackoverflow.com/questions/21105802/…
    • 感谢您的链接。但这也是我不想要的浏览器的输出。我想在返回变量中有 png。并返回 imagepng($image);不起作用。
    猜你喜欢
    • 2017-02-16
    • 2011-04-23
    • 2012-12-19
    • 1970-01-01
    • 2013-05-30
    • 1970-01-01
    • 2012-04-08
    • 2012-05-31
    • 2011-06-02
    相关资源
    最近更新 更多