使用cURL输出外部图像,但是如何更改图像的宽度? [英] Output external image with cURL, but how do you change the width of the image?

查看:127
本文介绍了使用cURL输出外部图像,但是如何更改图像的宽度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  header('Content-type:image / jpeg'); 

$ url = $ _GET ['url'];

$ ch = curl_init();

curl_setopt($ ch,CURLOPT_URL,$ url);
curl_setopt($ ch,CURLOPT_CONNECTTIMEOUT,0);
curl_setopt($ ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ ch,CURLOPT_BINARYTRANSFER,1);

$ file = curl_exec($ ch);

curl_close($ ch);

echo $ file;任何人都可以告诉我如何改变 $ file 的宽度。 / code>到300px?

解决方案

如果图片是在 < img> 标记,那么您可以通过更改 width 属性来获取浏览器的缩放比例。



否则,您需要在输出之前抓取该文件并重新缩放它的PHP代码。



您可以使用 imagecopyresampled()来计算高度。然后输出结果。



例如,从上面的代码中获取 $ file 中的图像。

  $ img = @imagecreatefromstring($ file); 

if($ img === false){
echo $ file;
exit;
}

$ width = imagesx($ img);
$ height = imagesy($ img);

$ newWidth = 300;

$ ratio = $ newWidth / $ width;
$ newHeight = $ ratio * $ height;


$ resized = @imagecreatetruecolor($ newWidth,$ newHeight);

if($ resized === false){
echo $ file;
exit;
}

$ quality = 90;

if(@imagecopyresampled($ resized,$ img,0,0,0,0,$ newWidth,$ newHeight,$ width,$ height)){
@imagejpeg ,NULL,$ quality);
} else {
echo $ file;
}


header('Content-type: image/jpeg');

$url = $_GET['url']; 

$ch = curl_init(); 

curl_setopt($ch, CURLOPT_URL, $url); 
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1); 

$file = curl_exec($ch); 

curl_close($ch);

echo $file;

Can anyone please tell me how I can change the width of $file to 300px?

解决方案

If the image is heading for a browser inside an <img> tag, then you can get the browser to rescale it by changing the width attribute.

Otherwise you need to grab the file and rescale it in your PHP code before outputting it.

You can use imagecopyresampled() to do that, calculating the height. Then outputting the result.

Example, following on from obtaining the image in to $file from the code above.

$img = @imagecreatefromstring($file);

if ($img === false) {
    echo $file;
    exit;
}

$width = imagesx($img);
$height = imagesy($img);

$newWidth = 300;

$ratio = $newWidth / $width;
$newHeight = $ratio * $height;


$resized = @imagecreatetruecolor($newWidth, $newHeight);

if ($resized === false) {
    echo $file;
    exit;
}

$quality = 90;

if (@imagecopyresampled($resized, $img, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height)) {
    @imagejpeg($resized, NULL, $quality);
} else {
    echo $file;
}

这篇关于使用cURL输出外部图像,但是如何更改图像的宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆