ImageMagick and imagick extensions of PHP

Source: Internet
Author: User
Tags imagemagick
Image processing artifacts ImageMagick and PHP imagick extensions in order to increase page loading speed and reduce traffic, we need to slim down website images, study a lot of solutions, and finally determine the use of ImageMagick, after learning about this software, it's really amazing. it's so easy to use and the effect is so obvious.

ImageMagick introduction:

ImageMagick is a powerful, stable, and open-source toolkit. it can be used to read, write, and process image files in over 89 basic formats, popular formats include TIFF, JPEG, GIF, PNG, PDF, and PhotoCD. By using ImageMagick, you can dynamically generate images based on the needs of web applications. you can also resize, rotate, sharpen, subtract, or add special effects to one or more images, save the operation results in the same format or other formats. you can use the command line to operate the image, you can also use C/C ++, Perl, Java, PHP, Python or Ruby programming. At the same time, ImageMagick provides a high-quality 2D toolkit that partially supports SVG. ImageMagic focuses on performance, bug reduction, and stable API and ABI.

ImageMagick is a software used to create, edit, and synthesize images. It can read, convert, and write images in multiple formats. Image cutting, Color Replacement, application of various effects, image rotation, combination, text, straight line, Polygon, elliptic, curve, attached to image stretching and rotation. ImageMagick is a free software: all source code is open and can be freely used, copied, modified, and released. Supports most operating systems.

ImageMagick command overview

[Convert | identify | mogrify | composite | montage | compare | display | animate | import | conjure]


Convert: convert image formats and sizes, Blur, crop, remove stains, jitter, approaching, draw images on images, add new images, and generate thumbnails.

Identify: describes the format and features of one or more image files.

Mogrify: The image is blurred, cropped, and jitters based on the specified size. Mogrify rewrite the original image file and then write it to a different image file.

Composite: generate an image based on one or more images.

Create a separate element image. Any decorative image containing element images, such as borders, structures, and image names.

Compare: evaluates different pictures in arithmetic and visual ways.

Display: If you have an X server system, it can display images in order.

Animate: Use X server to display animated images

Import: outputs image files in X server or any visible window. You can capture a single window, the entire screen or the rectangular part of any screen.

Conjure: Explain the script written by MSL (Magick Scripting Language.


Installation:

sudo apt-get install imagemagick
Common use cases:

The size (occupied space) of the image depends on the profile and quality of the image.

  • Quality: The higher the quality, the larger the space occupied. Proper quality reduction can greatly reduce the image size. Generally, it is difficult for the naked eye to differentiate the quality from 100 to 85, but the size is greatly reduced. Imagemagick is set through-quality.
  • Profile: record some image descriptions. For example, camera information (Aperture, camera model), photoshop metadata, and color table. The occupied space can be from several KB to several hundred KB, or even larger. ImageMagicK can remove this information in two ways. + Profile "*" or-strip

  • Exif information is a series of information collected by a digital camera during the shooting process, which is placed in the header of a well-known jpg file, that is to say, Exif information is a set of shooting parameters embedded in the JPEG image file format, including the aperture, shutter, ISO, date and time of photography and other information related to the photography conditions at that time, camera brand model, color encoding, recording sound and GPS information. Simply put, it is like the date printing function of a dummies camera, except that Exif information records more detailed and complete information. However, JPEG image files with Exif information are slightly larger than common JPEG files. In addition, images processed by software such as PS will have "program comments ". If it is not a professional photography website, the information is useless and can be removed:

    convert +profile “*” -strip src.jpg src-profile.jpg

    Reduce the image quality to compress the image:

    convert -quality 85 src.jpg src-quality85.jpg


    The preceding two commands are used together:

    find /tmp/images -iname "*.jpg" -exec convert -strip +profile "*" -quality 80 {} {} \;


    After processing these two commands, your image can be reduced a lot. PS: Based on my experience, converting a png image to a jps image will reduce a lot, and then use the above two commands to process it. that's perfect.

    PNG can also be compressed by reducing the color quantity of PNG images. However, the image compressed in this way can be obviously distorted and displayed in a jagged state.
    For a PNG image in the real world (usually a photo), it is usually converted to JPG first, and then compressed through the above method.

    convert -format jpg input.png  input.jpg  

    Scaling a user's uploaded image cannot simply limit the size of the image you upload with css, because the entire large image will be loaded each time the image is loaded. Excessive bandwidth is used and the page loading speed is affected. Scale according to the actual display needs. For example, if you want the image size in your album to be greater than 500x300:

    Convert-resize "500x300>" input.jpg output.jpg # keep the image as it is if it is smaller than x to prevent the image from being enlarged or distorted.

    The following describes how to install the php imgick extension to process images:

    Installation:

    1. install imgick extension

    1) sudo apt-get install libmagick-dev2) sudo apt-get install php-pear php5-dev3) sudo pecl install imagick
    2. edit the php. ini file to load it.

    Open the php. ini file and add extension = imagick. so to it.

    /etc/php5/apache2/php.ini
    Restart the apache service to make it invalid.

    /etc/init.d/apache2 restart

    A simple example is provided to convert the image format:

    $thumb = new Imagick();$thumb->readImage('test.gif');$thumb->writeImage('test.jpg');$thumb->clear();$thumb->destroy();

    I will not list them one by one because I have provided the following materials for you to learn:

    Imgick Class API: http://php.net/manual/en/class.imagick.php

    Image compression experience: http://blog.lizhigang.net/archives/228

    ImageMagick official website: http://www.imagemagick.org/script/index.php

    Http://elf8848.iteye.com/blog/382528

    Instance: http://hi.baidu.com/7soon/item/d394c2b55bd3bb70254b09ed

    Finally, I have attached my own PHP class for processing images with Imgick:

    /** The image compression class re-encapsulates Imagick ** @ version 2014-07-30 * @ author andy1219111@163.com */class Imgick_tool {// Imagick object instance public $ obj = null; public function _ construct () {// Determine whether the extension if (! Extension_loaded ('imagick') {return false ;}$ this-> obj = new Imagick ();} /** convert png2jpg image format ** @ param string src_img source image path * @ param string dest_img path of the image to be generated * @ return boolean conversion returns true otherwise false */ public function png2jpg ($ src_img, $ dest_img) {if (! Is_object ($ this-> obj) {return false;} try {$ this-> obj-> readImage ($ src_img ); if ($ this-> obj-> writeImage ($ dest_img) {$ this-> destory (); return $ dest_img;} return false;} catch (ImagickException $ e) {return false ;}} /** remove image profile information ** @ param string src_img source image path * @ return string src_img image name otherwise false */public function strip_profile ($ src_img, $ dest_img = '') {if (! Is_object ($ this-> obj) {return false;} try {$ dest_img = empty ($ dest_img )? $ Src_img: $ dest_img; $ this-> obj-> readImage ($ src_img); $ this-> obj-> stripImage (); if ($ this-> obj-> writeImage ($ dest_img) {$ this-> destory (); return $ src_img;} return false;} catch (ImagickException $ e) {return false ;}} /** set jpg image quality ** @ param string src_img source image path * @ param string dest_img path of the image to be generated * @ return boolean conversion returns true otherwise false */public function set_quality ($ src_img, $ quality = 70, $ dest_img = '') {if (! Is_object ($ this-> obj) {return false;} try {$ dest_img = empty ($ dest_img )? $ Src_img: $ dest_img; $ this-> obj-> readImage ($ src_img); $ this-> obj-> setImageCompression (Imagick: COMPRESSION_JPEG ); $ this-> obj-> setImageCompressionQuality ($ quality); if ($ this-> obj-> writeImage ($ dest_img) {$ this-> destory (); return $ dest_img;} return false;} catch (ImagickException $ e) {return false ;}} /** Image slimming ** @ param string src_img source image path * @ param int quality sets the image compression quality * @ param string dest_img specifies the path of the image to be generated * @ Return boolean convert to return true otherwise false */public function slimming ($ src_img, $ quality = 60, $ dest_img = '',) {if (! Is_object ($ this-> obj) {return false;} try {$ dest_img = empty ($ dest_img )? $ Src_img: $ dest_img; $ this-> obj-> readImage ($ src_img); $ this-> obj-> setImageFormat ('jpeg '); $ this-> obj-> setImageCompression (Imagick: COMPRESSION_JPEG); // reduce the image quality to 60% $ quality = $ this-> obj-> getImageCompressionQuality () * $ quality/100; $ this-> obj-> setImageCompressionQuality ($ quality); $ this-> obj-> stripImage (); if ($ this-> obj-> writeImage ($ dest_img) {$ this-> destory (); return $ dest_img;} return false;} catch (ImagickException $ e) {return false ;}} /** generate a thumbnail ** @ param string src_img source image path * @ param int quality sets the image compression quality * @ param string dest_img converts the path of the image to be generated * @ return boolean true or false */public function thump ($ src_img, $ width = 250, $ height = '') {if (! Is_object ($ this-> obj) {return false;} try {$ file_info = pathinfo ($ src_img ); // Generate the thumbnail name $ file_name = substr ($ file_info ['basename'], 0, strrpos ($ file_info ['basename'], '. '); $ dest_img = $ file_info ['dirname']. '/'. $ file_name. '_ thump. '. $ file_info ['extension']; $ this-> obj-> readImage ($ src_img ); // calculate the height of the thumbnail to be obtained $ img_width = $ this-> obj-> getImageWidth (); $ img_height = $ this-> obj-> getImageHeight (); $ dest_height = $ img_height * ($ width/$ img_width); $ this-> obj-> resizeImage ($ width, $ dest_height, Imagick: FILTER_CATROM, 1, false ); // generate an image if ($ this-> obj-> writeImage ($ dest_img) {$ this-> destory (); return $ dest_img;} return false ;} catch (ImagickException $ e) {return false ;}/ ** Release resource **/function destory () {if (is_object ($ this-> obj )) {$ this-> obj-> clear (); $ this-> obj-> destroy ();}}}

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.