Ivar
Ivar

Reputation: 796

download image from remote source and resize then save

Do any of you know of a good php class I can use to download an image from a remote source, re-size it to 120x120 and save it with a file name of my choosing?

So basically I would have an image at "http://www.site.com/image.jpg" save to my web server "/images/myChosenName.jpg" as a 120x120 pixels.

Thanks

Upvotes: 13

Views: 14292

Answers (3)

LatentDenis
LatentDenis

Reputation: 2991

If you're looking to have the ability to do this for both jpg and png file formats, here's what helped me:

$imgUrl = 'http://www.example.com/image.jpg';
// or $imgUrl = 'http://www.example.com/image.png';
$fileInfo = pathinfo($imgUrl);
$img = file_get_contents($imgUrl);
$im = imagecreatefromstring($img);
$originalWidth = imagesx($im);
$originalHeight = imagesy($im);
$resizePercentage = 0.5;
$newWidth = $originalWidth * $resizePercentage;
$newHeight = $originalHeight * $resizePercentage;
$tmp = imagecreatetruecolor($newWidth, $newHeight);
if ($fileInfo['extension'] == 'jpg') {
    imagecopyresized($tmp, $im, 0, 0, 0, 0, $newWidth, $newHeight, $originalWidth, $originalHeight);
    imagejpeg($tmp, '/img/myChosenName.jpg', -1);
}
else if ($fileInfo['extension'] == 'png') {
    $background = imagecolorallocate($tmp , 0, 0, 0);
    imagecolortransparent($tmp, $background);
    imagealphablending($tmp, false);
    imagesavealpha($tmp, true);
    imagecopyresized($tmp, $im, 0, 0, 0, 0, $newWidth, $newHeight, $originalWidth, $originalHeight);
    imagepng($tmp, '/img/myChosenName.png');
}
else {
    // This image is neither a jpg or png
}
imagedestroy($tmp);
imagedestroy($im);

The extra code on the png side of things ensures that the saved image contains any and all transparent sections.

Upvotes: 0

Manos Manoss
Manos Manoss

Reputation: 19

You can resize keeping the ratio of image

$im = imagecreatefromstring($img);

$width_orig = imagesx($im);

$height_orig = imagesy($im);

$width = '800';

$height = '800';

$ratio_orig = $width_orig/$height_orig;

if ($width/$height > $ratio_orig) {
   $width = $height*$ratio_orig;
} else {
   $height = $width/$ratio_orig;
}

Upvotes: 1

Zul
Zul

Reputation: 3608

You can try this:

<?php    
$img = file_get_contents('http://www.site.com/image.jpg');

$im = imagecreatefromstring($img);

$width = imagesx($im);

$height = imagesy($im);

$newwidth = '120';

$newheight = '120';

$thumb = imagecreatetruecolor($newwidth, $newheight);

imagecopyresized($thumb, $im, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

imagejpeg($thumb,'/images/myChosenName.jpg'); //save image as jpg

imagedestroy($thumb); 

imagedestroy($im);
?>


More information about PHP image function : http://www.php.net/manual/en/ref.image.php

Upvotes: 21

Related Questions