/ Published in: PHP
A function that resizes an image to desired width and height, but does not distort the image proportions. Works for JPEG, GIF and PNG.
Expand |
Embed | Plain Text
<?php /** * This function resizes an image to $fitInWidth and $fitInHeight, but doesn't distort the image proportions * * $path: The full path to the image. Ex.: "/images/my_image.jpg" * * $newName: If you don't want to override the original image, you can specify a new name. * * $fitInWidth:The height in pixels that you want to fit the image in * * $fitInHeight: The height in pixels that you want to fit the image in * * $jpegQuality: If the image is a jpeg, the function will save * the resized jpeg with the specified quality from 1 to 100 */ function resize_image($path, $fitInWidth, $fitInHeight, $newName = '', $jpegQuality = 100) { $scaleW = $fitInWidth/$width; $scaleH = $fitInHeight/$height; if($scaleH > $scaleW) { $new_width = $fitInWidth; } else { $new_height = $fitInHeight; } if($type == IMAGETYPE_JPEG)//If image is jpeg { $image_now = imagecreatefromjpeg($path);//Get image from path $image_new = imagecreatetruecolor($new_width, $new_height);//Create new image from scratch //Copy image from path into new image ($image_new) with new sizes imagecopyresampled($image_new, $image_now, 0, 0, 0, 0, $new_width, $new_height, $width, $height); imagejpeg($image_new, $new_path, $jpegQuality); } else if($type == IMAGETYPE_GIF)//If image is gif { $image_now = imagecreatefromgif($path); $image_new = imagecreatetruecolor($new_width, $new_height); imagecopyresampled($image_new, $image_now, 0, 0, 0, 0, $new_width, $new_height, $width, $height); imagegif($image_new, $new_path); } else if($type == IMAGETYPE_PNG)//If image is png { $image_now = imagecreatefrompng($path); $image_new = imagecreatetruecolor($new_width, $new_height); //Setting black color as transparent because image is png imagecolortransparent($image_new, imagecolorallocate($image_new, 0, 0, 0)); imagecopyresampled($image_new, $image_now, 0, 0, 0, 0, $new_width, $new_height, $width, $height); imagepng($image_new, $new_path); } else { //Image type is not jpeg, gif or png. } imagedestroy($image_now); imagedestroy($image_new); } //How to use $img_path = 'images/my_image.jpg';//The path to the image you want to resize //Here i'm giving a new name to the resized image so that it doesn't override the original image. If you want to override the original image change: $new_name = ''; $new_name = 'resized_image.jpg'; resize_image($img_path, 200, 200, $new_name); ?>
You need to login to post a comment.
