使用cURL获取远程图像,然后重新采样 [英] Get remote image using cURL then resample

查看:150
本文介绍了使用cURL获取远程图像,然后重新采样的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够从网络服务器检索远程图像,重新对其进行抽样,然后将其提供给浏览器,并将其保存到文件中。这是我到目前为止:

I want to be able to retrieve a remote image from a webserver, resample it, and then serve it up to the browser AND save it to a file. Here is what I have so far:

$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "$rURL");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_HEADER, 0);

// grab URL and pass it to the browser
$out = curl_exec($ch);

// close cURL resource, and free up system resources
curl_close($ch);

$imgRes = imagecreatefromstring($out);
imagejpeg($imgRes, $filename, 70);

header("Content-Type: image/jpg");
imagejpeg($imgRes, NULL, 70);
exit();

更新

更新以根据以下讨论反映正确答案

Updated to reflect correct answer based on discussion below

推荐答案

您可以使用 imagecreatefromstring() : / p>

You can fetch the file into a GD resource using imagecreatefromstring():


imagecreatefromstring()返回表示从给定数据获取的图像的图像标识符。如果您的构建的PHP支持这些类型将自动检测:JPEG,PNG,GIF,WBMP和GD2。

imagecreatefromstring() returns an image identifier representing the image obtained from the given data. These types will be automatically detected if your build of PHP supports them: JPEG, PNG, GIF, WBMP, and GD2.

,使用 imagecopyresampled()

使用输出

Output it using imagejpeg() or whichever output format suits you best.

使用文件名输出一个文件:

Make one output with a file name:

imagejpeg($image_resource, "/path/to/image.jpg");

然后向浏览器发送相同的资源:

then send the same resource to the browser:

header("Content-type: image/jpeg");
imagejpeg($image_resource);

取决于图片的格式,您可能希望使用imagepng()或imagegif 。

depending on the image's format, you may want to use the imagepng() or imagegif() functions instead.

您可能需要根据输入文件类型使用不同的输出格式。您可以使用 getimagesize()获取输入文件类型。

You may want to work with different output formats depending on the input file type. You can fetch the input file type using getimagesize().

请记住,您可以使用 $ quality 参数调整生成的JPEG图像的质量。默认值为75%,可能看起来很糟糕。

Remember that you can adjust the resulting JPEG image's quality using the $quality parameter. Default is 75% which can look pretty crappy.

这篇关于使用cURL获取远程图像,然后重新采样的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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