/ 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
Copy this code and paste it in your HTML
<?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 { //Copy image from path into new image ($image_new) with new sizes } else if($type == IMAGETYPE_GIF)//If image is gif { } else if($type == IMAGETYPE_PNG)//If image is png { //Setting black color as transparent because image is png } else { //Image type is not jpeg, gif or png. } } //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); ?>
Comments
