I need a way (using built-in PHP libs) to pull down an image from URL and save it to local disk with resized/scaled WIDTH to 150px. I have been trying this:
Creating a thumbnail from an uploaded image
function makeThumbnails($updir, $img, $id)
{
$thumbnail_width = 134;
$thumbnail_height = 189;
$thumb_beforeword = "thumb";
$arr_image_details = getimagesize("$updir" . $id . '_' . "$img"); // pass id to thumb name
$original_width = $arr_image_details[0];
$original_height = $arr_image_details[1];
if ($original_width > $original_height) {
$new_width = $thumbnail_width;
$new_height = intval($original_height * $new_width / $original_width);
} else {
$new_height = $thumbnail_height;
$new_width = intval($original_width * $new_height / $original_height);
}
$dest_x = intval(($thumbnail_width - $new_width) / 2);
$dest_y = intval(($thumbnail_height - $new_height) / 2);
if ($arr_image_details[2] == 1) {
$imgt = "ImageGIF";
$imgcreatefrom = "ImageCreateFromGIF";
}
if ($arr_image_details[2] == 2) {
$imgt = "ImageJPEG";
$imgcreatefrom = "ImageCreateFromJPEG";
}
if ($arr_image_details[2] == 3) {
$imgt = "ImagePNG";
$imgcreatefrom = "ImageCreateFromPNG";
}
if ($imgt) {
$old_image = $imgcreatefrom("$updir" . $id . '_' . "$img");
$new_image = imagecreatetruecolor($thumbnail_width, $thumbnail_height);
imagecopyresized($new_image, $old_image, $dest_x, $dest_y, 0, 0, $new_width, $new_height, $original_width, $original_height);
$imgt($new_image, "$updir" . $id . '_' . "$thumb_beforeword" . "$img");
}
}
That looks very promising but I can't figure out how to use it, and then whether it will do what I want. Concerns/needs:
($updir, $img, $id)
-- Is $updir
the location of the file? Or the location where I want it saved? Is $img
a file handle or the name of the file? Or the new name of the file? What is $id
for? The author didn't give any sample usage.data:image/jpeg;base64,/9j/4AAQ....
What's the best way to accomplish this?
Just do this:
function Thumbnail($url, $filename, $width = 150, $height = true) {
// download and create gd image
$image = ImageCreateFromString(file_get_contents($url));
// calculate resized ratio
// Note: if $height is set to TRUE then we automatically calculate the height based on the ratio
$height = $height === true ? (ImageSY($image) * $width / ImageSX($image)) : $height;
// create image
$output = ImageCreateTrueColor($width, $height);
ImageCopyResampled($output, $image, 0, 0, 0, 0, $width, $height, ImageSX($image), ImageSY($image));
// save image
ImageJPEG($output, $filename, 95);
// return resized image
return $output; // if you need to use it
}
Use it like this:
Thumbnail("http://cdn.cutestpaw.com/wp-content/uploads/2013/01/l-Cute-Kitten.jpg", "kitten.jpg");
The trick here is to use PHP's internal automatic file detection for the incoming stream which is very good handled by ImageCreateFromString
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments