从PHP中保存URL的透明图像
我想构建一个类,它可以执行很多照片操作,一种方法会从用户上传图像,但我也需要构建一种方法来从URL中获取照片,然后在其上运行其他方法,就像使用用户的POST表单上传它一样。从PHP中保存URL的透明图像
下面是我从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
而不是像这样 alt text http://a0.twimg.com/a/1262802780/images/twitter_logo_header.png
下面的两个调用将告诉PHP使用Alpha PNG图像在目前的混合:
ImageAlphaBlending($photo, false);
ImageSaveAlpha($photo, true);
编辑: 我看到你'也将图像输出为JPEG格式。 JPEG不支持透明度,所以不管你做什么,你最终都会得到不正确的背景颜色。另请参阅此相关问题:PHP/GD ImageSaveAlpha and ImageAlphaBlending
您需要为图像类型添加更好的支持,并通过扩展它们的透明度。
由于图像是透明的,我们可以知道它是GIF或PNG,但您使用imagejpeg()
发送GIF标头 - jpegs不支持任何类型的透明度。但如果它是一个PNG,你可能还需要考虑它的alpha trans或index透明度。
是的我打算加入,我只是增加了在我之前获得图像类型的能力张贴这个,所以我没有添加代码来使用这些数据呢 – JasonDavis 2010-01-08 02:48:10
JPG输出只是我玩耍,我会让它根据图像类型做不同的东西,对于一个PNG图像,我会输出或保存为PNG图像。我试过ImageAlphaBlending($ photo,false);和ImageSaveAlpha($ photo,true);但它似乎没有改变任何东西,即使输出是PNG – JasonDavis 2010-01-08 02:53:37
现在工作,不得不改变更多的东西,谢谢 – JasonDavis 2010-01-08 02:59:06