I\'m wanting to write some PHP code which automatically resizes any image uploaded via a form to 147x147px, but I have no idea how to go about it (I\'m a relative PHP novice
You need to use either PHP's ImageMagick or GD functions to work with images.
With GD, for example, it's as simple as...
function resize_image($file, $w, $h, $crop=FALSE) {
list($width, $height) = getimagesize($file);
$r = $width / $height;
if ($crop) {
if ($width > $height) {
$width = ceil($width-($width*abs($r-$w/$h)));
} else {
$height = ceil($height-($height*abs($r-$w/$h)));
}
$newwidth = $w;
$newheight = $h;
} else {
if ($w/$h > $r) {
$newwidth = $h*$r;
$newheight = $h;
} else {
$newheight = $w/$r;
$newwidth = $w;
}
}
$src = imagecreatefromjpeg($file);
$dst = imagecreatetruecolor($newwidth, $newheight);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
return $dst;
}
And you could call this function, like so...
$img = resize_image(‘/path/to/some/image.jpg’, 200, 200);
From personal experience, GD's image resampling does dramatically reduce file size too, especially when resampling raw digital camera images.
I created an easy-to-use library for image resizing. It can be found here on Github.
An example of how to use the library:
// Include PHP Image Magician library
require_once('php_image_magician.php');
// Open JPG image
$magicianObj = new imageLib('racecar.jpg');
// Resize to best fit then crop (check out the other options)
$magicianObj -> resizeImage(100, 200, 'crop');
// Save resized image as a PNG (or jpg, bmp, etc)
$magicianObj -> saveImage('racecar_small.png');
Other features, should you need them, are:
I hope is will work for you.
/**
* Image re-size
* @param int $width
* @param int $height
*/
function ImageResize($width, $height, $img_name)
{
/* Get original file size */
list($w, $h) = getimagesize($_FILES['logo_image']['tmp_name']);
/*$ratio = $w / $h;
$size = $width;
$width = $height = min($size, max($w, $h));
if ($ratio < 1) {
$width = $height * $ratio;
} else {
$height = $width / $ratio;
}*/
/* Calculate new image size */
$ratio = max($width/$w, $height/$h);
$h = ceil($height / $ratio);
$x = ($w - $width / $ratio) / 2;
$w = ceil($width / $ratio);
/* set new file name */
$path = $img_name;
/* Save image */
if($_FILES['logo_image']['type']=='image/jpeg')
{
/* Get binary data from image */
$imgString = file_get_contents($_FILES['logo_image']['tmp_name']);
/* create image from string */
$image = imagecreatefromstring($imgString);
$tmp = imagecreatetruecolor($width, $height);
imagecopyresampled($tmp, $image, 0, 0, $x, 0, $width, $height, $w, $h);
imagejpeg($tmp, $path, 100);
}
else if($_FILES['logo_image']['type']=='image/png')
{
$image = imagecreatefrompng($_FILES['logo_image']['tmp_name']);
$tmp = imagecreatetruecolor($width,$height);
imagealphablending($tmp, false);
imagesavealpha($tmp, true);
imagecopyresampled($tmp, $image,0,0,$x,0,$width,$height,$w, $h);
imagepng($tmp, $path, 0);
}
else if($_FILES['logo_image']['type']=='image/gif')
{
$image = imagecreatefromgif($_FILES['logo_image']['tmp_name']);
$tmp = imagecreatetruecolor($width,$height);
$transparent = imagecolorallocatealpha($tmp, 0, 0, 0, 127);
imagefill($tmp, 0, 0, $transparent);
imagealphablending($tmp, true);
imagecopyresampled($tmp, $image,0,0,0,0,$width,$height,$w, $h);
imagegif($tmp, $path);
}
else
{
return false;
}
return true;
imagedestroy($image);
imagedestroy($tmp);
}
(IMPORTANT: In the case of animation (animated webp or gif) resizing, the result will be a not animated, but resized image from the first frame! (The original animation remains intact...)
I created this to my php 7.2 project (example imagebmp sure (PHP 7 >= 7.2.0) :php/manual/function.imagebmp) about techfry.com/php-tutorial, with GD2, (so nothing 3rd party library) and very similar to the answer of Nico Bistolfi, but works with the all five basic image mimetype (png, jpeg, webp, bmp and gif), creating a new resized file, without modifying the original one, and the all stuff in one function and ready to use (copy and paste to your project). (You can set the extension of the new file with the fifth parameter, or just leave it, if you want keep the orignal):
function createResizedImage(
string $imagePath = '',
string $newPath = '',
int $newWidth = 0,
int $newHeight = 0,
string $outExt = 'DEFAULT'
) : ?string
{
if (!$newPath or !file_exists ($imagePath)) {
return null;
}
$types = [IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_GIF, IMAGETYPE_BMP, IMAGETYPE_WEBP];
$type = exif_imagetype ($imagePath);
if (!in_array ($type, $types)) {
return null;
}
list ($width, $height) = getimagesize ($imagePath);
$outBool = in_array ($outExt, ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp']);
switch ($type) {
case IMAGETYPE_JPEG:
$image = imagecreatefromjpeg ($imagePath);
if (!$outBool) $outExt = 'jpg';
break;
case IMAGETYPE_PNG:
$image = imagecreatefrompng ($imagePath);
if (!$outBool) $outExt = 'png';
break;
case IMAGETYPE_GIF:
$image = imagecreatefromgif ($imagePath);
if (!$outBool) $outExt = 'gif';
break;
case IMAGETYPE_BMP:
$image = imagecreatefrombmp ($imagePath);
if (!$outBool) $outExt = 'bmp';
break;
case IMAGETYPE_WEBP:
$image = imagecreatefromwebp ($imagePath);
if (!$outBool) $outExt = 'webp';
}
$newImage = imagecreatetruecolor ($newWidth, $newHeight);
//TRANSPARENT BACKGROUND
$color = imagecolorallocatealpha ($newImage, 0, 0, 0, 127); //fill transparent back
imagefill ($newImage, 0, 0, $color);
imagesavealpha ($newImage, true);
//ROUTINE
imagecopyresampled ($newImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
// Rotate image on iOS
if(function_exists('exif_read_data') && $exif = exif_read_data($imagePath, 'IFD0'))
{
if(isset($exif['Orientation']) && isset($exif['Make']) && !empty($exif['Orientation']) && preg_match('/(apple|ios|iphone)/i', $exif['Make'])) {
switch($exif['Orientation']) {
case 8:
if ($width > $height) $newImage = imagerotate($newImage,90,0);
break;
case 3:
$newImage = imagerotate($newImage,180,0);
break;
case 6:
$newImage = imagerotate($newImage,-90,0);
break;
}
}
}
switch (true) {
case in_array ($outExt, ['jpg', 'jpeg']): $success = imagejpeg ($newImage, $newPath);
break;
case $outExt === 'png': $success = imagepng ($newImage, $newPath);
break;
case $outExt === 'gif': $success = imagegif ($newImage, $newPath);
break;
case $outExt === 'bmp': $success = imagebmp ($newImage, $newPath);
break;
case $outExt === 'webp': $success = imagewebp ($newImage, $newPath);
}
if (!$success) {
return null;
}
return $newPath;
}
If you dont care about the aspect ration (i.e you want to force the image to a particular dimension), here is a simplified answer
// for jpg
function resize_imagejpg($file, $w, $h) {
list($width, $height) = getimagesize($file);
$src = imagecreatefromjpeg($file);
$dst = imagecreatetruecolor($w, $h);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $w, $h, $width, $height);
return $dst;
}
// for png
function resize_imagepng($file, $w, $h) {
list($width, $height) = getimagesize($file);
$src = imagecreatefrompng($file);
$dst = imagecreatetruecolor($w, $h);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $w, $h, $width, $height);
return $dst;
}
// for gif
function resize_imagegif($file, $w, $h) {
list($width, $height) = getimagesize($file);
$src = imagecreatefromgif($file);
$dst = imagecreatetruecolor($w, $h);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $w, $h, $width, $height);
return $dst;
}
Now let's handle the upload part. First step, upload the file to your desired directory. Then called one of the above functions based on file type (jpg, png or gif) and pass the absolute path of your uploaded file as below:
// jpg change the dimension 750, 450 to your desired values
$img = resize_imagejpg('path/image.jpg', 750, 450);
The return value $img
is a resource object. We can save to a new location or override the original as below:
// again for jpg
imagejpeg($img, 'path/newimage.jpg');
Hope this helps someone. Check these links for more on resizing Imagick::resizeImage and imagejpeg()
I found a mathematical way to get this job done
Github repo - https://github.com/gayanSandamal/easy-php-image-resizer
Live example - https://plugins.nayague.com/easy-php-image-resizer/
<?php
//path for the image
$source_url = '2018-04-01-1522613288.PNG';
//separate the file name and the extention
$source_url_parts = pathinfo($source_url);
$filename = $source_url_parts['filename'];
$extension = $source_url_parts['extension'];
//define the quality from 1 to 100
$quality = 10;
//detect the width and the height of original image
list($width, $height) = getimagesize($source_url);
$width;
$height;
//define any width that you want as the output. mine is 200px.
$after_width = 200;
//resize only when the original image is larger than expected with.
//this helps you to avoid from unwanted resizing.
if ($width > $after_width) {
//get the reduced width
$reduced_width = ($width - $after_width);
//now convert the reduced width to a percentage and round it to 2 decimal places
$reduced_radio = round(($reduced_width / $width) * 100, 2);
//ALL GOOD! let's reduce the same percentage from the height and round it to 2 decimal places
$reduced_height = round(($height / 100) * $reduced_radio, 2);
//reduce the calculated height from the original height
$after_height = $height - $reduced_height;
//Now detect the file extension
//if the file extension is 'jpg', 'jpeg', 'JPG' or 'JPEG'
if ($extension == 'jpg' || $extension == 'jpeg' || $extension == 'JPG' || $extension == 'JPEG') {
//then return the image as a jpeg image for the next step
$img = imagecreatefromjpeg($source_url);
} elseif ($extension == 'png' || $extension == 'PNG') {
//then return the image as a png image for the next step
$img = imagecreatefrompng($source_url);
} else {
//show an error message if the file extension is not available
echo 'image extension is not supporting';
}
//HERE YOU GO :)
//Let's do the resize thing
//imagescale([returned image], [width of the resized image], [height of the resized image], [quality of the resized image]);
$imgResized = imagescale($img, $after_width, $after_height, $quality);
//now save the resized image with a suffix called "-resized" and with its extension.
imagejpeg($imgResized, $filename . '-resized.'.$extension);
//Finally frees any memory associated with image
//**NOTE THAT THIS WONT DELETE THE IMAGE
imagedestroy($img);
imagedestroy($imgResized);
}
?>