Output external image with cURL, but how do you change the width of the image?

↘锁芯ラ 提交于 2020-01-05 08:21:16

问题


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?


回答1:


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;
}


来源:https://stackoverflow.com/questions/5069286/output-external-image-with-curl-but-how-do-you-change-the-width-of-the-image

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!