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:
- What do these params mean:
($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. - The function seems to require me to specify WIDTH and HEIGHT. I only want to specify WIDTH and let the height be proportional.
- I need to pull images over 2 different types of URL: (1) The basic http://foo..., and (2) the data syntax:
data:image/jpeg;base64,/9j/4AAQ....
- Ideally I'd like to convert these images in all cases down to a compressed jpeg thumbnail (150px width, any height), even if the original image was not in jpg format.
What's the best way to accomplish this?