Categories : PHP

You can use this function to resize and change quality of image for jpg, png, gif, bmp formats.

  • php image resize function for all image formats
  • parameters: image_path (required), new_width (optional), new_height (optional), quality (optional)
  • image_path: path to the image file
  • new_image_path: path to the resized image file
  • resize_x: resize by width
  • resize_y: resize by height
  • quality: JPEG quality (0-100)
  • returns boolean
# php image resize function for all image formats

function resize_image($image_path,$new_image_path,$resize_x,$resize_y,$quality) {
 
    // jpeg, png, gif or bmp?
    $ext = strtolower(pathinfo($image_path, PATHINFO_EXTENSION));
    
    // image create function
    switch ($ext) {
        case 'jpg':
        case 'jpeg':
            $image = imagecreatefromjpeg($image_path);
            break;
        case 'png':
            $image = imagecreatefrompng($image_path);
            break;
        case 'gif':
            $image = imagecreatefromgif($image_path);
            break;
        case 'bmp':
            $image = imagecreatefrombmp($image_path);
            break;
        default:
            return false;
    }
    
    // resize
    $resized = imagecreatetruecolor($resize_x, $resize_y);
    imagecopyresampled($resized, $image, 0, 0, 0, 0, $resize_x, $resize_y, imagesx($image), imagesy($image));
    
    // output
    switch ($ext) {
        case 'jpg':
        case 'jpeg':
            imagejpeg($resized, $new_image_path, $quality);
            break;
        case 'png':
            imagepng($resized, $new_image_path);
            break;
        case 'gif':
            imagegif($resized, $new_image_path);
            break;
        case 'bmp':
            imagewbmp($resized, $new_image_path);
            break;
    }
    
    // clear resources
    imagedestroy($image);
    imagedestroy($resized);
    
    return true;
}

How to resize an image in php

Leave a Reply

Your email address will not be published.