Thursday, July 24, 2014

Simple, best and standard way to make Thumbnail Images in PHP using Imagick

There is lot of way and plugins available to make thumbnail images in PHP. But that was the problem, because we are confused about which was the best one. After I research on these, I found using Imagick is the best one(Its only on my point of view.).

Imagick
Its an PHP extension to create or modify images. Imagick = Image + Magick. In old periods peoples wrote Magic as Magick. To install these run following command on your linux terminal.

pecl install imagick

After installing Imagick using above command, add “extension=imagick.so“ at the end on php.ini file which is located on /etc/php5/apache2/php.ini and restart the apache.

Example
<?php
$img_old_path = 'images/sun.jpg';     // Input image.
$img_new_path = 'images/thumbnail/sun.jpg';      // Output thumbnail image.

$img = new Imagick($img_old_path);

// Orientation operation start.
// If you remove this orientation block, there will no issue on generating thumbnail. But image may rotated if it has high difference in height and width.
$orientation = $img->getImageOrientation();
switch($orientation) {
    case imagick::ORIENTATION_BOTTOMRIGHT: 
        $img->rotateimage("#000", 180); // rotate 180 degrees.
    break;

    case imagick::ORIENTATION_RIGHTTOP:
        $img->rotateimage("#000", 90); // rotate 90 degrees CW.
    break;

    case imagick::ORIENTATION_LEFTBOTTOM: 
        $img->rotateimage("#000", -90); // rotate 90 degrees CCW.
    break;
}
$img->setImageOrientation(imagick::ORIENTATION_TOPLEFT);
// Orientation operation end.

$img->thumbnailImage(200 , 200, TRUE);
/* Max width and max height with best fit. Will return boolean;
This is the best method to make thumbnail. Action behind the scene is...
1. If given image width is larger than heigh then make thumbnail width as 200(here) and fix height according to that.

2. Else if image hight is larger than width then make thumbnail height as 200 and fix width according to that.*/

$img->writeImage($img_new_path); // Write the generated thumbnail. Will return boolean.
?>

References

No comments:

Post a Comment

Learn JavaScript - String and its methods - 16

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>String and it's methods - JS&l...