PHP

Efficient Image Resizing and Compression! Techniques for Using PHP’s convert -resize

The need to change the size and capacity of images is always present among people who operate websites. Especially to increase the loading speed of web pages, it is very important to reduce the size of images. In this article, we will introduce how to easily resize and compress images using PHP’s convert -resize command.

HTML Code to Call the Image

To display an image on a web page, write the HTML as follows. The resize.php file is responsible for resizing the image.

<img src="resize.php?imgp=image_file_path_and_name" alt="original image">

 
Here, the parameter imgp specifies the file path and file name of the image to be resized.

Resizing Images Using PHP’s convert -resize (resize.php)

Next, let’s take a closer look at the code of the resize.php file, which performs the actual resizing process.

<?php 
if (!empty($_GET['imgp'])) {
    $image_file = $_GET['imgp'];
}
 
$img = new mimage($image_file); 
 
$newWidth = 100; //Specify the resize width (px)
$newHeight = ($img->height / ($img->width / $newWidth));
 
header('Content-type: image/jpeg'); 
echo $img->resizeimage($newWidth, $newHeight); 
 
 
class mimage { 
    var $img_path; 
    var $width; 
    var $height; 
    var $font_file_path; 
   
    function mimage($image_path) { 
        $this->img_path = $image_path; 
        $image_info = getimagesize($this->img_path); 
        $this->width = $image_info[0]; 
        $this->height = $image_info[1]; 
    } 
   
    function resizeimage($max_w, $max_h, $new_file_dir = null, $new_file_name = null) { 
        if ($new_file_name) { 
            $new_file_path = $new_file_dir .'/'. $new_file_name; 
            $cmd = "convert ". $this->img_path ." -resize {$max_w}x{$max_h} {$new_file_path} "; 
            system($cmd); 
        } else { 
            $cmd = "convert ". $this->img_path ." -resize {$max_w}x{$max_h} -"; 
            return shell_exec($cmd); 
        } 
    } 
  
}
?>

 
This code retrieves the specified image file and resizes it to new width and height. The resizing process is performed using the convert -resize command.

Points to Note

The above method is very convenient because it allows you to resize images in real-time, but there are concerns about image quality degradation. Especially, if resizing is repeated multiple times, the quality of the image may deteriorate.

Therefore, if you want to display images on your website while maintaining quality, it is recommended to edit them to the appropriate size and capacity in advance using specialized software such as Photoshop or GIMP.

Conclusion

By utilizing PHP’s convert -resize, you can easily resize and compress images on web pages. However, if image quality is the top priority, consider using dedicated image editing software.

 
Please use it at your own risk.