Download images and resize
I have built a system which downloads images from a bunch of URLs, depending on the user, and fetch's them asynchronously - if they're wider than the device's screen we resize. Trouble is some of these images can be huge 1MB + and many of them and downloading large files and processing them is causing the older devices to struggle.
So I thought I'd introduce a server side level which can handle the downloading and resizing...but my PHP is not great. I'm guessing this is possible but I cant find any solutions after a few days research. There are an abundance of PHP resize scripts, but none from a URL, they are all from a database or inside HTML . I need it to be sent a URL of an image, download it, if its too big resize, then send back to the device.
Updated with cURL
<?php
$imgurl = $_GET["url"];
function curl_do开发者_开发技巧wnload($Url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $Url);
curl_setopt($ch, CURLOPT_USERAGENT, "MozillaXYZ/1.0");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$output = curl_exec($ch);
$im = imagecreatefromstring($output);
if ($im !== false)
{
header('Content-Type: image/jpeg');
list($width, $height) = getimagesize($im);
$new_width = 320;
$new_height = 320;
// Resample
$image_p = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefromjpeg($im);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
imagejpeg($image_p, null, 100);
}
else
{
echo 'An error occurred.';
}
curl_close($ch);
return $image_p;
}
?>
You can fetch the image with cURL with CURLOPT_RETURN_TRANSFER
passed to curl_setopt
to get the image data. Then the following steps should do for generating the resized image:
imagecreatefromstring
will allow you to construct an image objectimagecreate
to create a new image of the appropriate sizeimagecopyresampled
for the resizeimagejpeg
on the resized image to send it to the browser
As @Paul notes, you'll want to set the content type to image/jpeg
.
you can use cURL or socket to download the html page and images in it, then use GD2 to resize the images, and return to browser with
header("Content-type:image/jpeg");
after that, your application on iphone load this php created image from your php server. i think this is the solution for manipulating all the images from other servers the way you want.
精彩评论