Posted By

kumar_sekhar on 04/14/11


Tagged

resize image


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

Some0ne
mikael12
StarkCreations


Image Resize


 / Published in: PHP
 

Purpose: This script can be used to resize one or more images. It will save the file to a directory and output the path to that directory which you can display or write to a databse.

TO USE,  SET: 
    $filename = image to be resized
    $newfilename = added to filename to for each use to keep from overwriting images created example thumbnail_$filename is how it will be saved.
    $path = where the image should be stored and accessed. 
    $newwidth = resized width could be larger or smaller
    $newheight = resized height could be larger or smaller

SAMPLE OF FUNCTION: makeimage('image.jpg', 'fullimage_', 'imgs/', 250, 250)

Include the file containing the function in your document and simply call the function with the correct parameters and your image will be resized.
  1. //IMAGE RESIZE FUNCTION FOLLOW ABOVE DIRECTIONS
  2. function makeimage($filename, $newfilename, $path, $newwidth, $newheight) {
  3.  
  4. //SEARCHES IMAGE NAME STRING TO SELECT EXTENSION (EVERYTHING AFTER . )
  5. $image_type = strstr($filename, '.');
  6.  
  7. //SWITCHES THE IMAGE CREATE FUNCTION BASED ON FILE EXTENSION
  8. switch($image_type) {
  9. case '.jpg':
  10. $source = imagecreatefromjpeg($filename);
  11. break;
  12. case '.png':
  13. $source = imagecreatefrompng($filename);
  14. break;
  15. case '.gif':
  16. $source = imagecreatefromgif($filename);
  17. break;
  18. default:
  19. echo("Error Invalid Image Type");
  20. die;
  21. break;
  22. }
  23.  
  24. //CREATES THE NAME OF THE SAVED FILE
  25. $file = $newfilename . $filename;
  26.  
  27. //CREATES THE PATH TO THE SAVED FILE
  28. $fullpath = $path . $file;
  29.  
  30. //FINDS SIZE OF THE OLD FILE
  31. list($width, $height) = getimagesize($filename);
  32.  
  33. //CREATES IMAGE WITH NEW SIZES
  34. $thumb = imagecreatetruecolor($newwidth, $newheight);
  35.  
  36. //RESIZES OLD IMAGE TO NEW SIZES
  37. imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
  38.  
  39. //SAVES IMAGE AND SETS QUALITY || NUMERICAL VALUE = QUALITY ON SCALE OF 1-100
  40. imagejpeg($thumb, $fullpath, 60);
  41.  
  42. //CREATING FILENAME TO WRITE TO DATABSE
  43. $filepath = $fullpath;
  44.  
  45. //RETURNS FULL FILEPATH OF IMAGE ENDS FUNCTION
  46. return $filepath;
  47.  
  48. }

Report this snippet  

You need to login to post a comment.