【问题标题】:Saving a transparent image from a URL in PHP从 PHP 中的 URL 保存透明图像
【发布时间】:2019-05-31 03:06:22
【问题描述】:

我正在尝试构建一个执行许多照片操作的类,一个方法将上传来自用户的图像,但我还需要构建一个方法来从 URL 中获取照片并在其上运行其他方法,就像它一样正在通过用户的 POST 表单上传。

下面是我从 URL 获取图像的功能的开始,它可以工作,但仍然需要工作。在代码下方,您可以看到运行此函数的结果的图像。也是原始图像,看看它应该是什么样子。可以看到,这个函数使图像在这个透明图像上具有黑色背景。我怎样才能让它看起来更好看?

$url = 'http://a0.twimg.com/a/1262802780/images/twitter_logo_header.png';

//run our function
savePhotofromURL($url, 'no');



// photo function should grab an photo from a URL
function savePhotofromURL($photo_url, $saveimage = 'yes'){
    if(isset($photo_url) && $photo_url != '') {

        //get info about photo
        $photo_info = getimagesize($photo_url);
        $source_width = $photo_info['0'];
        $source_height = $photo_info['1'];
        $source_type = $photo_info['mime'];

        //grab the Photo from URL
        $photo = imagecreatefromstring(file_get_contents($photo_url));

        if (is_resource($photo) === true){
            if($saveimage === 'yes'){
                // TO DO: resize image and make the thumbs code would go here if we are saving image:
                // TO DO: resize source image if it is wider then 800 pixels
                // TO DO: make 1 thumbnail that is 150 pixels wide
            }else{
                // We are not saving the image show it in the user's browser
                // TO DO: we will add in correct photo type soon
                header('Content-Type: image/gif');
                imagejpeg($photo, null, 100);
                imagedestroy($photo); 
            }
        }else{
            // not a valid resource, show error
            echo 'error getting URL photo from ' .$photo_url;
        }
    }else{
        // url of image was empty
        echo 'The URL was not passed into our function';
    }
}

结果如下所示
alt text http://img2.pict.com/52/05/1f/2429493/0/screenshot2b181.png

而不是这样

【问题讨论】:

    标签: php gd


    【解决方案1】:

    以下两个调用将告诉 php 使用 png 图像中存在的 alpha 混合:

            ImageAlphaBlending($photo, false);
            ImageSaveAlpha($photo, true);
    

    编辑: 我看到您也将图像输出为 JPEG。 JPEG 不支持透明度,因此无论您做什么,最终都会得到不正确的背景颜色。另请参阅此相关问题:PHP/GD ImageSaveAlpha and ImageAlphaBlending

    【讨论】:

    • jpg 输出只是我玩的,我会根据图像类型让它做不同的事情,对于 png 图像我将输出或保存为 png 图像。我试过 ImageAlphaBlending($photo, false);和 ImageSaveAlpha($photo, true);但即使输出为 PNG,它似乎也没有任何改变
    【解决方案2】:

    您需要为图像类型添加更好的支持并扩展它们的透明度。

    由于图像是透明的,我们可以知道它是 GIF 还是 PNG,但您在使用 imagejpeg() 时发送 GIF 标头 - jpeg 不支持任何类型的透明度。但如果它是 png,您可能还必须考虑其 alpha trans 或 index 透明度。

    【讨论】:

    • 是的,我打算添加它,我只是在发布之前添加了获取图像类型的功能,所以我还没有添加代码来使用该数据
    猜你喜欢
    • 2010-10-17
    • 1970-01-01
    • 2014-04-14
    • 1970-01-01
    • 2012-05-31
    • 1970-01-01
    • 1970-01-01
    • 2014-10-05
    相关资源
    最近更新 更多