• 首页
  • vue
  • TypeScript
  • JavaScript
  • scss
  • css3
  • html5
  • php
  • MySQL
  • redis
  • jQuery
  • 位置: php 中文手册 -> PECL扩展库

    ImageMagick(图像处理库)

    • 在Windows上安装的需求:版本信息与上面的没有区别。http://www.imagemagick.org/提供了一些二进制文件,因此您可以在Windows上加载此扩展,而无需编译器。
    • 在其它平台安装要求:需要PHP>=5.1.3和ImageMagick>=6.2.4。Imagick支持的文件格式数量完全取决于ImageMagick安装所支持的格式数量。例如,Imagemagick需要ghostscript来执行PDF操作。

    此PECL 扩展未与 PHP 捆绑。注:此分机的正式名称为imagick

    There is a big disclaimer that should be made to all those about to venture on ImageMagick programming using PHP: the great, vast majority of WAMP (Windows-Apache-MySQL-PHP) servers do not support ImageMagick commands at all, since it is a "different package," and there appears to be no way to install ImageMagick through standard Add/Remove Applications within Linux (as far as standard Debian linux releases go).  It's very easy to get Apache/PHP running in either Windows or Linux with pretty much any standard OS/distro supported so that you can run all of your own code on your own computer.  But that's definitely not the case when you want Imagick to cooperate with your Apache server and your PHP code!
    It took me almost an entire week just to get Apache/PHP/ImageMagick working all together nice and happily so that I could run my own PHP code on my own machine (natively, too).  So, I decided to simply write down the steps, to help anyone else out who could need help.
    Guide to Building an Apache/PHP/Imagick Server with Linux/CentOS 6.4:::
    1. Install CentOS 6.4.  (Theoretically, other versions of CentOS should work as well, but I simply chose the most recent one.)  Also, you can very easily emulate CentOS within Windows (for instance, the unfree choice of VMWare).
    2. Install PHP, PHP-Common, PHP-extensions, etc., from standard Application Package Manager ("Add/Remove Programs", usually in system tools somewhere).  (You don't have to worry about Apache, because that comes with CentOS 6.4 anyway.)
    3. Open up a terminal and enter admin mode with the command "su".  You'll need a password for this.
    4. Enter this command: yum install ImageMagick ImageMagick-devel
    5. Enter this command: pecl install imagick
    6. Modify php.ini and include the line "extension=imagick.so".  This file is located at "/etc/php.ini" normally.  The line must be exactly inserted in the section of "Dynamic Extensions", which begins with this commented out text:
    --------------------------------
    ;;;;;;;;;;;;;;;;;;;;;;
    ; Dynamic Extensions ;
    ;;;;;;;;;;;;;;;;;;;;;;
    --------------------------------
    Use the "search" feature of gedit to find the text.  Add the extension below the commented out note in this section so that the result looks like:
    --------------------------------
    ;;;;
    ; Note: packaged extension modules are now loaded via the .ini files
    ; found in the directory /etc/php.d; these are loaded by default.
    ;;;;
    extension=imagick.so
    --------------------------------
    Putting the extension directly at the top caused me serious permission issues in running Imagick code.  Also, with CentOS, the permissions automatically disable user control for this php.ini.  Enter the following terminal command: "chown [YOUR-USERNAME] -R /etc/php.ini", without the quotes to get control to modify it.  Note to insert your username where it states "[YOUR-USERNAME]".
    7. Enter this command: "service httpd restart", without quotes, from admin mode.  This restarts Apache/PHP/PHP's extensios now that you've installed ImageMagick.  If this gives you an error, just try "service httpd start".
    My favorite part about this method is that you can update your system with issuing the "yum update" command and then the "yum upgrade" command -- and the Apache/PHP/Imagick combo will still be working perfectly!  Unlike some other guides out there for this, you don't need to rely on antiquated, unsupported versions that can be nearly impossible to find.  Also, you don't need to worry about the MySQL, Hash, MBString, Exif packages, because they all seem to be installed and properly cooperating with PHP automatically after installing PHP from the Application Manager.  This solution makes everything work well together.
    The root directory of your public files is located at /var/www/html/.  Normally, this folder is not owned by the user, so you'll get a permission error when trying to add files or folders to it.  Correct that with entering admin mode in the terminal/command-line window ("su" command) and entering the following command: "chown [YOUR-USERNAME] -R /var/www/html/", without quotes.  Again, replace "[YOUR-USERNAME]" with your actual user name.  (Warning: The first time I did this, I was lazy and entered the command for only the "/var/" folder, which prevented my system ever from booting.  It would always freeze with the notorious and googleable erro-message: "Could not update ICEauthority file /var/lib/gdm/.ICEauthority".  So, make sure to change ownership only for "/var/www/html/".)
    To view your root directory files as compiled, resultant, PHP pages, open up a browser and enter "127.0.0.1" as the address.  So, a file in your root directory would be accessed at the following URL in your browser: http://127.0.0.1/your.file.php .  If you get a "could not connect" error message, try the command "service httpd start" at the terminal window from admin mode.  (You have to start this service manually every time the machine boots, although there's plenty of ways to automate it.)
    I hope this helps!  I tried a hundred different guides on getting Apache/PHP/Imagick to work together and none of them worked.  Don't give up!  ImageMagick is a package of really neat imaging functions!
    
    I tried installing imagick extension on WHM/Cpanel but it didn't work. the error message wascould not extract the package.xml fileThis seems to be a bug in PHP 5.5 as reported by users.I finally installed this extension from command line. Here are the steps I used just in case someone is experiencing similar problem and is looking for a solution.1. install ImageMagick from rpm repository in WHM. the version I installed is ImageMagick 6.7.2-72. log in the server via ssh,3. download the latest version of imagick, unpack and install. the version I downloaded is imagick-3.3.0RC2.tgzwget http://pecl.php.net/get/imagick-3.3.0RC2.tgztar xvf imagick-3.3.0RC2.tgzcd imagick-3.3.0RC2phpize./configuremakemake installthe extension was successfully installed4. in WHM, go to PHP configuration editor, in advanced mode, search extension, and add imagick.so in the list of extension enabled. this can of course be added using a command line editor.extension=imagick.so5. restart apache. imagick is there now.My server runsPHP Version 5.5cPanel Version 11.50.0 (build 30)I hope it works for someone else too.
    Installing Imagick on Windows isn't too hard. I followed the guide at http://valokuva.org/?page_id=50 and managed to install it without too much sweat.
    1. Visit http://imagemagick.org/script/binary-releases.php#windows and download "ImageMagick-6.5.4-6-Q16-windows-dll.exe"
    2. Pick a version at http://valokuva.org/outside-blog-content/imagick-windows-builds/ The directories are in YYMMDD format. The latest version that worked for me was 2008-Jul-09 so download 080709/php_imagick_dyn-Q16.dll respectively.
     
    3. Rename php_imagick_dyn-Q16.dll to "php_imagick.dll" and move it to php/ext
    4. open php.ini, and make sure 
    extension=php_imagick.dll
    appears in the file and uncommented then resave.
    Note: phpinfo() will tell you the location of the loaded php.ini file.
    5. Re-start your webserver.
    That's it, a simple test will tell you if your installation was successful.
    <?php
    $im = new Imagick();
    $im->newPseudoImage(100, 100, "magick:rose");
    $im->setImageFormat("png");
    $im->roundCorners(5,3);
    $type=$im->getFormat();
    header("Content-type: $type");
    echo $im->getimageblob();
    ?>
    

    运行时配置

    这些函数的行为受php.ini中的设置影响。

    Imagick configuration options
    名字默认可修改范围更新日志
    imagick.locale_fixFALSEPHP_INI_ALLAvailable since Imagick 2.1.0
    imagick.progress_monitorFALSEPHP_INI_SYSTEMAvailable since Imagick 2.2.2
    imagick.skip_version_checkFALSEPHP_INI_SYSTEMAvailable since Imagick 3.3.0

    基础用法

    Imagick makes image manipulation in PHP extremely easy through an OO interface. Here is a quick example on how to make a thumbnail:

    Example #1 Creating a thumbnail in Imagick

    <?php
    header('Content-type: image/jpeg');
    $image = new Imagick('image.jpg');
    // If 0 is provided as a width or height parameter,
    // aspect ratio is maintained
    $image->thumbnailImage(100, 0);
    echo $image;
    ?>
    

    Using SPL and other OO features supported in Imagick, it can be simple to resize all files in a directory (useful for batch resizing large digital camera images to be web viewable). Here we use resize, as we might want to retain certain meta-data:

    Example #2 Make a thumbnail of all JPG files in a directory

    <?php
    $images = new Imagick(glob('images/*.JPG'));
    foreach($images as $image) {
        // Providing 0 forces thumbnailImage to maintain aspect ratio
        $image->thumbnailImage(1024,0);
    }
    $images->writeImages();
    ?>
    

    This is an example of creating a reflection of an image. The reflection is created by flipping the image and overlaying a gradient on it. Then both, the original image and the reflection is overlayed on a canvas.

    Example #3 Creating a reflection of an image

    <?php
    /* Read the image */
    $im = new Imagick("test.png");
    /* Thumbnail the image */
    $im->thumbnailImage(200, null);
    /* Create a border for the image */
    $im->borderImage(new ImagickPixel("white"), 5, 5);
    /* Clone the image and flip it */
    $reflection = $im->clone();
    $reflection->flipImage();
    /* Create gradient. It will be overlayed on the reflection */
    $gradient = new Imagick();
    /* Gradient needs to be large enough for the image and the borders */
    $gradient->newPseudoImage($reflection->getImageWidth() + 10, $reflection->getImageHeight() + 10, "gradient:transparent-black");
    /* Composite the gradient on the reflection */
    $reflection->compositeImage($gradient, imagick::COMPOSITE_OVER, 0, 0);
    /* Add some opacity. Requires ImageMagick 6.2.9 or later */
    $reflection->setImageOpacity( 0.3 );
    /* Create an empty canvas */
    $canvas = new Imagick();
    /* Canvas needs to be large enough to hold the both images */
    $width = $im->getImageWidth() + 40;
    $height = ($im->getImageHeight() * 2) + 30;
    $canvas->newImage($width, $height, new ImagickPixel("black"));
    $canvas->setImageFormat("png");
    /* Composite the original image and the reflection on the canvas */
    $canvas->compositeImage($im, imagick::COMPOSITE_OVER, 20, 10);
    $canvas->compositeImage($reflection, imagick::COMPOSITE_OVER, 20, $im->getImageHeight() + 10);
    /* Output the image*/
    header("Content-Type: image/png");
    echo $canvas;
    ?>
    

    以上例程的输出类似于:

    This example illustrates how to use fill patterns during drawing.

    Example #4 Filling text with gradient

    <?php
    /* Create a new imagick object */
    $im = new Imagick();
    /* Create new image. This will be used as fill pattern */
    $im->newPseudoImage(50, 50, "gradient:red-black");
    /* Create imagickdraw object */
    $draw = new ImagickDraw();
    /* Start a new pattern called "gradient" */
    $draw->pushPattern('gradient', 0, 0, 50, 50);
    /* Composite the gradient on the pattern */
    $draw->composite(Imagick::COMPOSITE_OVER, 0, 0, 50, 50, $im);
    /* Close the pattern */
    $draw->popPattern();
    /* Use the pattern called "gradient" as the fill */
    $draw->setFillPatternURL('#gradient');
    /* Set font size to 52 */
    $draw->setFontSize(52);
    /* Annotate some text */
    $draw->annotation(20, 50, "Hello World!");
    /* Create a new canvas object and a white image */
    $canvas = new Imagick();
    $canvas->newImage(350, 70, "white");
    /* Draw the ImagickDraw on to the canvas */
    $canvas->drawImage($draw);
    /* 1px black border around the image */
    $canvas->borderImage('black', 1, 1);
    /* Set the format to PNG */
    $canvas->setImageFormat('png');
    /* Output the image */
    header("Content-Type: image/png");
    echo $canvas;
    ?>
    

    以上例程的输出类似于:

    Working with animated GIF images

    Example #5 Read in GIF image and resize all frames

    <?php
    /* Create a new imagick object and read in GIF */
    $im = new Imagick("example.gif");
    /* Resize all frames */
    foreach ($im as $frame) {
        /* 50x50 frames */
        $frame->thumbnailImage(50, 50);
        /* Set the virtual canvas to correct size */
        $frame->setImagePage(50, 50, 0, 0);
    }
    /* Notice writeImages instead of writeImage */
    $im->writeImages("example_small.gif", true);
    ?>
    

    Working with ellipse primitive and custom fonts

    Example #6 Create a PHP logo

    <?php
    /* Set width and height in proportion of genuine PHP logo */
    $width = 400;
    $height = 210;
    /* Create an Imagick object with transparent canvas */
    $img = new Imagick();
    $img->newImage($width, $height, new ImagickPixel('transparent'));
    /* New ImagickDraw instance for ellipse draw */
    $draw = new ImagickDraw();
    /* Set purple fill color for ellipse */
    $draw->setFillColor('#777bb4');
    /* Set ellipse dimensions */
    $draw->ellipse($width / 2, $height / 2, $width / 2, $height / 2, 0, 360);
    /* Draw ellipse onto the canvas */
    $img->drawImage($draw);
    /* Reset fill color from purple to black for text (note: we are reusing ImagickDraw object) */
    $draw->setFillColor('black');
    /* Set stroke border to white color */
    $draw->setStrokeColor('white');
    /* Set stroke border thickness */
    $draw->setStrokeWidth(2);
    /* Set font kerning (negative value means that letters are closer to each other) */
    $draw->setTextKerning(-8);
    /* Set font and font size used in PHP logo */
    $draw->setFont('Handel Gothic.ttf');
    $draw->setFontSize(150);
    /* Center text horizontally and vertically */
    $draw->setGravity(Imagick::GRAVITY_CENTER);
    /* Add center "php" with Y offset of -10 to canvas (inside ellipse) */
    $img->annotateImage($draw, 0, -10, 0, 'php');
    $img->setImageFormat('png');
    /* Set appropriate header for PNG and output the image */
    header('Content-Type: image/png');
    echo $img;
    ?>
    

    以上例程的输出类似于:

    Be careful when loading multiple images by passing an array to a new Imagick object. This is from Example #2:
    <?php
    $images = new Imagick(glob('images/*.JPG'));
    ?>
    If you have lots of images inside the images folder, PHP will consume a lot of memory, ergo it is not recommended. I personally think it's a better idea to loop each image separately:
    <?php
    $image_files = glob('images/*.JPG');
    foreach ($image_files as $image_file) {
      $image = new Imagick($image_file);
      // Do something for the image and so on...
    }
    ?>
    This way only a single image is fitted into the memory at a time.
    on Example #3 Creating a reflection of an image
    ----------------------------------------------------
    /* Clone the image and flip it */
    $reflection = $im->clone();
    $reflection->flipImage();
    ----------------------------------------------------
    it was using the Imagick::clone function
    This function has been DEPRECATED as of imagick 3.1.0 in favour of using the clone keyword.
    use below code instead:
    ----------------------------------------------------
    /* Clone the image and flip it */
    $reflection = clone $im;
    $reflection->flipImage();
    ----------------------------------------------------
    http://php.net/manual/en/imagick.clone.php