我正在尝试构建一个执行许多照片操作的类,一个方法将从用户上传图像,但我还需要构建一个从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
答案 0 :(得分:1)
以下两个调用将告诉php使用png图像中存在的alpha混合:
ImageAlphaBlending($photo, false);
ImageSaveAlpha($photo, true);
编辑: 我看到你也把图像输出为JPEG。 JPEG不支持透明度,因此无论您做什么,最终都会得到不正确的背景颜色。另请参阅此相关问题:PHP/GD ImageSaveAlpha and ImageAlphaBlending
答案 1 :(得分:0)
您需要为图像类型添加更好的支持,并扩展其透明度。
由于图片是透明的,我们可以知道它是GIF还是PNG但你在使用imagejpeg()
时发送GIF标题 - jpegs不支持任何类型的透明度。但如果它是一个png,你可能还需要考虑它的alpha trans或index透明度。