Image resizing in PHP

I want to write some PHP code that automatically resizes any image uploaded through the form to 147x147px, but I don’t know how to do this (I'm relative PHP beginner).

So far, I have successfully downloaded images, recognized file types and names, but I would like to add resizing functionality to the code. For example, I have a test image with a size of 2.3 MB and 1331x1331 in dimension, and I would like its size to decrease, which, I believe, significantly compresses the size of the image file.

So far I have the following:

if ($_FILES) { //Put file properties into variables $file_name = $_FILES['profile-image']['name']; $file_size = $_FILES['profile-image']['size']; $file_tmp_name = $_FILES['profile-image']['tmp_name']; //Determine filetype switch ($_FILES['profile-image']['type']) { case 'image/jpeg': $ext = "jpg"; break; case 'image/png': $ext = "png"; break; default: $ext = ''; break; } if ($ext) { //Check filesize if ($file_size < 500000) { //Process file - clean up filename and move to safe location $n = "$file_name"; $n = ereg_replace("[^A-Za-z0-9.]", "", $n); $n = strtolower($n); $n = "avatars/$n"; move_uploaded_file($file_tmp_name, $n); } else { $bad_message = "Please ensure your chosen file is less than 5MB."; } } else { $bad_message = "Please ensure your image is of filetype .jpg or.png."; } } $query = "INSERT INTO users (image) VALUES ('$n')"; mysql_query($query) or die("Insert failed. " . mysql_error() . "<br />" . $query); 
+71
php image-processing image-resizing image-upload
Feb 01 '13 at 15:31
source share
12 answers

To work with images, you need to use either PHP ImageMagick or GD .

With GD, for example, it is 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 can call this function, for example ...

 $img = resize_image('/path/to/some/image.jpg', 200, 200); 

From personal experience, resampling a GD image also significantly reduces file size, especially when resampling the original images of a digital camera.

+121
Feb 01 '13 at 15:33
source share
— -

There is one very simple function of re-scaling images for all types of images that are transparent and very easy to use.

verify:

http://www.nimrodstech.com/php-image-resize/

https://github.com/Nimrod007/PHP_image_resize

hope this helps

+28
Jan 07 '14 at 10:00
source share

This resource also deserves attention - some very neat code that uses GD. However, I modified their final code snippet to create this function that meets OP requirements ...

 function store_uploaded_image($html_element_name, $new_img_width, $new_img_height) { $target_dir = "your-uploaded-images-folder/"; $target_file = $target_dir . basename($_FILES[$html_element_name]["name"]); $image = new SimpleImage(); $image->load($_FILES[$html_element_name]['tmp_name']); $image->resize($new_img_width, $new_img_height); $image->save($target_file); return $target_file; //return name of saved file in case you want to store it in you database or show confirmation message to user } 

You will also need to include this PHP file ...

 <?php /* * File: SimpleImage.php * Author: Simon Jarvis * Copyright: 2006 Simon Jarvis * Date: 08/11/06 * Link: http://www.white-hat-web-design.co.uk/blog/resizing-images-with-php/ * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details: * http://www.gnu.org/licenses/gpl.html * */ class SimpleImage { var $image; var $image_type; function load($filename) { $image_info = getimagesize($filename); $this->image_type = $image_info[2]; if( $this->image_type == IMAGETYPE_JPEG ) { $this->image = imagecreatefromjpeg($filename); } elseif( $this->image_type == IMAGETYPE_GIF ) { $this->image = imagecreatefromgif($filename); } elseif( $this->image_type == IMAGETYPE_PNG ) { $this->image = imagecreatefrompng($filename); } } function save($filename, $image_type=IMAGETYPE_JPEG, $compression=75, $permissions=null) { if( $image_type == IMAGETYPE_JPEG ) { imagejpeg($this->image,$filename,$compression); } elseif( $image_type == IMAGETYPE_GIF ) { imagegif($this->image,$filename); } elseif( $image_type == IMAGETYPE_PNG ) { imagepng($this->image,$filename); } if( $permissions != null) { chmod($filename,$permissions); } } function output($image_type=IMAGETYPE_JPEG) { if( $image_type == IMAGETYPE_JPEG ) { imagejpeg($this->image); } elseif( $image_type == IMAGETYPE_GIF ) { imagegif($this->image); } elseif( $image_type == IMAGETYPE_PNG ) { imagepng($this->image); } } function getWidth() { return imagesx($this->image); } function getHeight() { return imagesy($this->image); } function resizeToHeight($height) { $ratio = $height / $this->getHeight(); $width = $this->getWidth() * $ratio; $this->resize($width,$height); } function resizeToWidth($width) { $ratio = $width / $this->getWidth(); $height = $this->getheight() * $ratio; $this->resize($width,$height); } function scale($scale) { $width = $this->getWidth() * $scale/100; $height = $this->getheight() * $scale/100; $this->resize($width,$height); } function resize($width,$height) { $new_image = imagecreatetruecolor($width, $height); imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight()); $this->image = $new_image; } } ?> 
+18
Mar 31 '15 at 7:13
source share

If you don’t care about the aspect of the diet (i.e. you want the image to fit to a specific size), 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 download part. At the first stage, upload the file to the desired directory. Then, one of the above functions is called based on the file type (jpg, png or gif) and passes the absolute path of your downloaded file, as shown below:

  // jpg change the dimension 750, 450 to your desired values $img = resize_imagejpg('path/image.jpg', 750, 450); 

Return value $img - resource object. We can save the new location or redefine the original, as shown below:

  // again for jpg imagejpeg($img, 'path/newimage.jpg'); 

Hope this helps someone. Check out these links for more detailed resizing of Imagick :: resizeImage and imagejpeg ()

+11
Aug 22 '16 at 15:45
source share

I hope this works 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); } 
+6
Oct. 23 '13 at 5:37
source share

Just use the PHP function: given as

 // Read the image $img = imagecreatefromjpeg("source_of_img.jpg"); // Now resize the image width = 200 and height = 200 $imgresize = imagescale($img, 200, 200); 
+6
May 15 '18 at 13:31
source share

UPDATED: now done for resizing webp and bmp, and retains a transparent background! (IMPORTANT: this time it is not suitable for resizing the animation (webp or gif), just resize the first frame and create an un-animated image from it! I will update this answer in the coming weeks (when I have time), and the End Result there will be a simple class with one public and several private functions, but also without any third-party library or framework-specific dependency.)

I created this for my php 7.2 project about https://www.techfry.com/php-tutorial , with GD2 (so nothing is a third-party library) and is very similar to Niko Bistolfi's answer, but works with all five basic image mimetype (png , jpeg, webp, bmp and gif), creating a new file with a resized file, without changing the source file, and all things in one (and safe) function and ready to use (copy and paste into your project). (The new file will be png, I use png in most cases, because the quality, but you can easily change this part, with comments or build your own logic from them about type $):

 function createResizedImage( string $imagePath = '', string $newPath = '', int $newWidth = 0, int $newHeight = 0 ) : bool { if ( $newPath === '' or file_exists($imagePath) === false ) { return false; } if ( in_array( ( $type = exif_imagetype($imagePath) ), [ IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_GIF, IMAGETYPE_BMP, IMAGETYPE_WEBP ] ) === false ) { return false; } if ( !(list($width, $height, $type) = getimagesize($imagePath)) ) return false; if ( !( $image = $type === IMAGETYPE_JPEG ? imagecreatefromjpeg($imagePath) : ( $type === IMAGETYPE_PNG ? imagecreatefrompng($imagePath) : ( $type === IMAGETYPE_BMP ? imagecreatefrombmp($imagePath) : ( $type === IMAGETYPE_WEBP ? imagecreatefromwebp($imagePath) : ( $type === IMAGETYPE_GIF ? imagecreatefromgif($imagePath) : false ) ) ) ) ) ) { return false; } $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); imagepng($newImage, $newPath); #imagejpeg($newImage, $newPath); #imagegif($newImage, $newPath); return true; } 
+3
May 8 '19 at 11:20
source share

I created an easy-to-use library for resizing images. It can be found here on Github .

Example library usage:

 // 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 functions if you need them:

  • Quick and easy resizing - resizing to landscape, portrait or auto
  • Easy harvest
  • Add text
  • Quality adjustment
  • Water marks
  • Shadows and reflections
  • Transparency support
  • Read EXIF ​​Metadata
  • Borders, Rounded Corners, Rotation
  • Filters and Effects
  • Image sharpness
  • Image Type Conversion
  • BMP support
+2
Feb 16 '18 at 19:01
source share

ZF cake:

 <?php class FkuController extends Zend_Controller_Action { var $image; var $image_type; public function store_uploaded_image($html_element_name, $new_img_width, $new_img_height) { $target_dir = APPLICATION_PATH . "/../public/1/"; $target_file = $target_dir . basename($_FILES[$html_element_name]["name"]); //$image = new SimpleImage(); $this->load($_FILES[$html_element_name]['tmp_name']); $this->resize($new_img_width, $new_img_height); $this->save($target_file); return $target_file; //return name of saved file in case you want to store it in you database or show confirmation message to user public function load($filename) { $image_info = getimagesize($filename); $this->image_type = $image_info[2]; if( $this->image_type == IMAGETYPE_JPEG ) { $this->image = imagecreatefromjpeg($filename); } elseif( $this->image_type == IMAGETYPE_GIF ) { $this->image = imagecreatefromgif($filename); } elseif( $this->image_type == IMAGETYPE_PNG ) { $this->image = imagecreatefrompng($filename); } } public function save($filename, $image_type=IMAGETYPE_JPEG, $compression=75, $permissions=null) { if( $image_type == IMAGETYPE_JPEG ) { imagejpeg($this->image,$filename,$compression); } elseif( $image_type == IMAGETYPE_GIF ) { imagegif($this->image,$filename); } elseif( $image_type == IMAGETYPE_PNG ) { imagepng($this->image,$filename); } if( $permissions != null) { chmod($filename,$permissions); } } public function output($image_type=IMAGETYPE_JPEG) { if( $image_type == IMAGETYPE_JPEG ) { imagejpeg($this->image); } elseif( $image_type == IMAGETYPE_GIF ) { imagegif($this->image); } elseif( $image_type == IMAGETYPE_PNG ) { imagepng($this->image); } } public function getWidth() { return imagesx($this->image); } public function getHeight() { return imagesy($this->image); } public function resizeToHeight($height) { $ratio = $height / $this->getHeight(); $width = $this->getWidth() * $ratio; $this->resize($width,$height); } public function resizeToWidth($width) { $ratio = $width / $this->getWidth(); $height = $this->getheight() * $ratio; $this->resize($width,$height); } public function scale($scale) { $width = $this->getWidth() * $scale/100; $height = $this->getheight() * $scale/100; $this->resize($width,$height); } public function resize($width,$height) { $new_image = imagecreatetruecolor($width, $height); imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight()); $this->image = $new_image; } public function savepicAction() { ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL); $this->_helper->layout()->disableLayout(); $this->_helper->viewRenderer->setNoRender(); $this->_response->setHeader('Access-Control-Allow-Origin', '*'); $this->db = Application_Model_Db::db_load(); $ouser = $_POST['ousername']; $fdata = 'empty'; if (isset($_FILES['picture']) && $_FILES['picture']['size'] > 0) { $file_size = $_FILES['picture']['size']; $tmpName = $_FILES['picture']['tmp_name']; //Determine filetype switch ($_FILES['picture']['type']) { case 'image/jpeg': $ext = "jpg"; break; case 'image/png': $ext = "png"; break; case 'image/jpg': $ext = "jpg"; break; case 'image/bmp': $ext = "bmp"; break; case 'image/gif': $ext = "gif"; break; default: $ext = ''; break; } if($ext) { //if($file_size<400000) { $img = $this->store_uploaded_image('picture', 90,82); //$fp = fopen($tmpName, 'r'); $fp = fopen($img, 'r'); $fdata = fread($fp, filesize($tmpName)); $fdata = base64_encode($fdata); fclose($fp); //} } } if($fdata=='empty'){ } else { $this->db->update('users', array( 'picture' => $fdata, ), array('username=?' => $ouser )); } } 
+1
Oct 31 '16 at 15:47
source share

You can try using the TinyPNG PHP library. Using this library, your image is automatically optimized during the resizing process. All you need to install the library and get the API key from https://tinypng.com/developers . To install the library, run the command below.

 composer require tinify/tinify 

After that, your code is as follows.

 require_once("vendor/autoload.php"); \Tinify\setKey("YOUR_API_KEY"); $source = \Tinify\fromFile("large.jpg"); //image to be resize $resized = $source->resize(array( "method" => "fit", "width" => 150, "height" => 100 )); $resized->toFile("thumbnail.jpg"); //resized image 

I have a blog written on the same topic http://artisansweb.net/resize-image-php-using-tinypng

+1
Jul 07 '17 at 13:19
source share

I would recommend you use piio.co. Once you have uploaded the images to your repository, you simply use the source image URL in <img/> and the library will automatically resize for you.

Your image tag will look like this:

<img data-piio="/image/gallery/p/image1.jpg"/>

Then, as soon as you initialize the Piio script, it will automatically resize the image and send it from the CDN.

Here is a link to the documents

If you want to do this manually , I recommend using the built-in php functions, the GD library will be used for this. For example, if you want to resize a JPEG, you can start with:

 list($width, $height) = getimagesize($filepath); $original = imagecreatefromjpeg($filepath); $thumb = imagecreatetruecolor($new_width, $new_height); imagecopyresized($thumb, $original, 0, 0, 0, 0, $new_width, $new_height, $width, $height); 

To directly display an image:

imagejpeg($thumb);

To save the image to a file:

imagejpeg($thumb, 'filepath/image.jpg');

+1
Apr 21 '18 at 18:47
source share

I found a math way to make this work

Github repository - 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 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 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); } ?> 
+1
May 13 '18 at 9:45
source share



All Articles