【发布时间】:2010-01-07 02:24:19
【问题描述】:
我正在尝试在 PHP 中创建一个函数,它允许我输入基本上任何 URL,然后在其上运行一些函数,就像用户在我的服务器上上传一样。因此,我将调整大小并制作一些缩略图,但我需要帮助才能使图像处于可以在其上运行其他代码的状态。该站点上的另一位用户帮助我开始使用 ImageCreateFromString() 和 file_get_contents()
请注意,这段代码缺少很多我知道的东西,我只是想让基本功能正常工作,然后我会添加所有安全措施
我使用这样的 URL 尝试了下面的代码,并将照片 URL 添加到我的脚本 URL:
http://example.com/friendproject2/testing/photos/fromurl/?url=http://a0.twimg.com/a/1262802780/images/twitter_logo_header.png
但它什么也没显示,甚至没有错误
function getphotoURL($url){
if(isset($url) && $url != 'bad') {
$image = ImageCreateFromString(file_get_contents($url));
if (is_resource($image) === true){
echo 'The URL of the image we fetch is :' .$url. '<BR><BR>';
//show image
header('Content-Type: image/jpeg');
imagejpeg($image, null, 100);
imagedestroy($image);
imagedestroy($image);
// image is valid, do your magic here
}else{
// not a valid image, show error
echo 'error getting URL photo from ' .$url;
}
}else{
//url was empty
echo 'The URL was not passed into our function';
}
}
?>
###### 更新#####
这似乎是我的一个简单错误,就像检查 POST 请求而不是 GET 请求一样简单,下面是我的新代码。
我有几个问题,
1) 我正在使用 imagejpeg($image, null, 100);我想知道,我应该使用其他东西吗?它是否要求源图像是 jpg 或它可以与任何图像一起使用?我需要允许主要类型(jpg、jpeg、gif、png)
2) 与上述问题相同,但在屏幕上显示图像时,我将标题设置为:header('Content-Type: image/jpeg');其他类型的图片不应该是jpg吗?
3) 有没有一种方法可以确保传入的源 URL 是实际图像,如果不是图像,我可以做任何我想做的事情,比如显示我自己的错误或做我自己的代码一旦检测到 URL 不是有效的图像 url
<?PHP
// run our function
if(isset($_GET['url']) && $_GET['url'] != "") {
getphotoURL($_GET['url'],'no');
}
function getphotoURL($url, $saveimage = 'yes'){
if(isset($url) && $url != '') {
$image = imagecreatefromstring(file_get_contents($url));
if (is_resource($image) === true){
if($saveimage === 'yes'){
// resize image and make the thumbs code would go here if we are saving image:
// resize source image if it is wider then 800 pixels
// make 1 thumbnail that is 150 pixels wide
}else{
// We are not saving the image show it in the user's browser
header('Content-Type: image/png');
imagejpeg($image, null, 100);
imagedestroy($image);
}
}else{
// not a valid resource, show error
echo 'error getting URL photo from ' .$url;
}
}else{
// url of image was empty
echo 'The URL was not passed into our function';
}
}
?>
【问题讨论】:
-
您确定没有禁用错误报告吗?这应该至少输出一些东西(假设函数实际上正在被调用)。
-
Content-type 之前的回声将会把事情搞砸。
-
您好,我只是确保 eeror 报告已打开,但屏幕上仍然没有显示任何内容 = error_reporting(E_ALL); //全部显示
标签: php image-processing