Php uses the imagick module to scale, crop, and compress images.

Source: Internet
Author: User
Tags imagemagick
This article describes how to use the imagick module in php to scale, crop, and compress images. For more information about how to use the Imagick module in PHP to scale, crop, and compress images, including GIF images

Scale and crop

The code is as follows:
/**
* Crop images
* Cropping rules:
* 1. the height is null or zero and auto-adaptive based on width scaling height
* 2. the width is null or zero and auto-adaptive based on the zooming width of the height
* 3. adjust the width, height to a ratio of not empty or zero to scale or crop the image based on the aspect ratio. The image is cropped from the center of the header by default.
* @ Param number $ width
* @ Param number $ height
*/
Public function resize ($ width = 0, $ height = 0 ){
If ($ width = 0 & $ height = 0 ){
Return;
}

$ Color = ''; // 'rgba (255,255,255, 1 )';
$ Size = $ this-> image-> getImagePage ();
// Original width and height
$ Src_width = $ size ['width'];
$ Src_height = $ size ['height'];

// Adaptive scaling by width
If ($ width! = 0 & $ height = 0 ){
If ($ src_width> $ width ){
$ Height = intval ($ width * $ src_height/$ src_width );

If ($ this-> type = 'GIF '){
$ This-> _ resizeGif ($ width, $ height );
} Else {
$ This-> image-> thumbnailImage ($ width, $ height, true );
}
}
Return;
}
// Auto-scaling by height and width
If ($ width = 0 & $ height! = 0 ){
If ($ src_height> $ height ){
$ Width = intval ($ src_width * $ height/$ src_height );

If ($ this-> type = 'GIF '){
$ This-> _ resizeGif ($ width, $ height );
} Else {
$ This-> image-> thumbnailImage ($ width, $ height, true );
}
}
Return;
}

// The scaled size
$ Crop_w = $ width;
$ Crop_h = $ height;

// The cropped position after scaling
$ Crop_x = 0;
$ Crop_y = 0;

If ($ src_width/$ src_height) <($ width/$ height )){
// The width proportion is smaller than the target width proportion, and the width proportion is scaled up from the header at the target height.
$ Crop_h = intval ($ src_height * $ width/$ src_width );
// Crop from the top without calculating $ crop_y
} Else {
// Scale-up of the aspect ratio greater than the target width and height ratio and crop the image based on the center of the target width
$ Crop_w = intval ($ src_width * $ height/$ src_height );
$ Crop_x = intval ($ crop_w-$ width)/2 );
}

If ($ this-> type = 'GIF '){
$ This-> _ resizeGif ($ crop_w, $ crop_h, true, $ width, $ height, $ crop_x, $ crop_y );
} Else {
$ This-> image-> thumbnailImage ($ crop_w, $ crop_h, true );
$ This-> image-> cropImage ($ width, $ height, $ crop_x, $ crop_y );
}
}

How to process GIF images

The code is as follows:
/**
* To process a GIF image, you must process each GIF image.
* @ Param unknown $ t_w zoom width
* @ Param unknown $ t_h zoom height
* @ Param string $ whether isCrop is cropped
* @ Param number $ c_w crop width
* @ Param number $ c_h crop height
* @ Param number $ c_x crop coordinate x
* @ Param number $ c_y crop coordinate y
*/
Private function _ resizeGif ($ t_w, $ t_h, $ isCrop = false, $ c_w = 0, $ c_h = 0, $ c_x = 0, $ c_y = 0 ){
$ Dest = new Imagick ();
$ Color_transparent = new ImagickPixel ("transparent"); // transparent color
Foreach ($ this-> image as $ img ){
$ Page = $ img-> getImagePage ();
$ Tmp = new Imagick ();
$ Tmp-> newImage ($ page ['width'], $ page ['height'], $ color_transparent, 'GIF ');
$ Tmp-> compositeImage ($ img, Imagick: COMPOSITE_OVER, $ page ['x'], $ page ['Y']);

$ Tmp-> thumbnailImage ($ t_w, $ t_h, true );
If ($ isCrop ){
$ Tmp-> cropImage ($ c_w, $ c_h, $ c_x, $ c_y );
}

$ Dest-> addImage ($ tmp );
$ Dest-> setImagePage ($ tmp-> getImageWidth (), $ tmp-> getImageHeight (), 0, 0 );
$ Dest-> setImageDelay ($ img-> getImageDelay ());
$ Dest-> setImageDispose ($ img-> getImageDispose ());

}
$ This-> image-> destroy ();
$ This-> image = $ dest;
}

Compression during storage

The code is as follows:
// Save to the specified path
Public function save_to ($ path ){
// Compress the image quality
$ This-> image-> setImageFormat ('jpeg ');
$ This-> image-> setImageCompression (Imagick: COMPRESSION_JPEG );
$ A = $ this-> image-> getImageCompressionQuality () * 0.60;
If ($ a = 0 ){
$ A = 60;
}
$ This-> image-> setImageCompressionQuality ($ );
$ This-> image-> stripImage ();

If ($ this-> type = 'GIF '){
$ This-> image-> writeImages ($ path, true );
} Else {
$ This-> image-> writeImage ($ path );
}
}

ImagickService. php

The code is as follows:

/**
* Image Processing Service
* Implementation using the php extension service Imagick
* Official ImageMagick website address [url] http: www.imagemagick.org/script/index.php#/url]
*
* @ Author weiguang3
* @ Since 20140403
*/
Class ImagickService {
Private $ image = null;
Private $ type = null;

// Constructor
Public function _ construct (){
}

// Destructor
Public function _ destruct (){
If ($ this-> image! = Null)
$ This-> image-> destroy ();
}

Public function init (){

}

// Load the image
Public function open ($ path ){
$ This-> image = new Imagick ($ path );
If ($ this-> image ){
$ This-> type = strtolower ($ this-> image-> getImageFormat ());
}
Return $ this-> image;
}

/**
* Crop images
* Cropping rules:
* 1. the height is null or zero and auto-adaptive based on width scaling height
* 2. the width is null or zero and auto-adaptive based on the zooming width of the height
* 3. adjust the width, height to a ratio of not empty or zero to scale or crop the image based on the aspect ratio. The image is cropped from the center of the header by default.
* @ Param number $ width
* @ Param number $ height
*/
Public function resize ($ width = 0, $ height = 0 ){
If ($ width = 0 & $ height = 0 ){
Return;
}

$ Color = ''; // 'rgba (255,255,255, 1 )';
$ Size = $ this-> image-> getImagePage ();
// Original width and height
$ Src_width = $ size ['width'];
$ Src_height = $ size ['height'];

// Adaptive scaling by width
If ($ width! = 0 & $ height = 0 ){
If ($ src_width> $ width ){
$ Height = intval ($ width * $ src_height/$ src_width );

If ($ this-> type = 'GIF '){
$ This-> _ resizeGif ($ width, $ height );
} Else {
$ This-> image-> thumbnailImage ($ width, $ height, true );
}
}
Return;
}
// Auto-scaling by height and width
If ($ width = 0 & $ height! = 0 ){
If ($ src_height> $ height ){
$ Width = intval ($ src_width * $ height/$ src_height );

If ($ this-> type = 'GIF '){
$ This-> _ resizeGif ($ width, $ height );
} Else {
$ This-> image-> thumbnailImage ($ width, $ height, true );
}
}
Return;
}

// The scaled size
$ Crop_w = $ width;
$ Crop_h = $ height;

// The cropped position after scaling
$ Crop_x = 0;
$ Crop_y = 0;

If ($ src_width/$ src_height) <($ width/$ height )){
// The width proportion is smaller than the target width proportion, and the width proportion is scaled up from the header at the target height.
$ Crop_h = intval ($ src_height * $ width/$ src_width );
// Crop from the top without calculating $ crop_y
} Else {
// Scale-up of the aspect ratio greater than the target width and height ratio and crop the image based on the center of the target width
$ Crop_w = intval ($ src_width * $ height/$ src_height );
$ Crop_x = intval ($ crop_w-$ width)/2 );
}

If ($ this-> type = 'GIF '){
$ This-> _ resizeGif ($ crop_w, $ crop_h, true, $ width, $ height, $ crop_x, $ crop_y );
} Else {
$ This-> image-> thumbnailImage ($ crop_w, $ crop_h, true );
$ This-> image-> cropImage ($ width, $ height, $ crop_x, $ crop_y );
}
}

/**
* To process a GIF image, you must process each GIF image.
* @ Param unknown $ t_w zoom width
* @ Param unknown $ t_h zoom height
* @ Param string $ whether isCrop is cropped
* @ Param number $ c_w crop width
* @ Param number $ c_h crop height
* @ Param number $ c_x crop coordinate x
* @ Param number $ c_y crop coordinate y
*/
Private function _ resizeGif ($ t_w, $ t_h, $ isCrop = false, $ c_w = 0, $ c_h = 0, $ c_x = 0, $ c_y = 0 ){
$ Dest = new Imagick ();
$ Color_transparent = new ImagickPixel ("transparent"); // transparent color
Foreach ($ this-> image as $ img ){
$ Page = $ img-> getImagePage ();
$ Tmp = new Imagick ();
$ Tmp-> newImage ($ page ['width'], $ page ['height'], $ color_transparent, 'GIF ');
$ Tmp-> compositeImage ($ img, Imagick: COMPOSITE_OVER, $ page ['x'], $ page ['Y']);

$ Tmp-> thumbnailImage ($ t_w, $ t_h, true );
If ($ isCrop ){
$ Tmp-> cropImage ($ c_w, $ c_h, $ c_x, $ c_y );
}

$ Dest-> addImage ($ tmp );
$ Dest-> setImagePage ($ tmp-> getImageWidth (), $ tmp-> getImageHeight (), 0, 0 );
$ Dest-> setImageDelay ($ img-> getImageDelay ());
$ Dest-> setImageDispose ($ img-> getImageDispose ());

}
$ This-> image-> destroy ();
$ This-> image = $ dest;
}


/**
* Change the image size
* $ Fit: Adaptive size mode
* 'Force': forces the image to be deformed to $ width X $ height.
* 'Scale': scales the image in the security box $ width X $ height proportionally. after the output is scaled, the image size is not completely equal to $ width X $ height.
* 'Scale _ fill': scale the image in the security box $ width X $ height proportionally, and fill the color with no pixels in the security box,
* When this parameter is used, you can set the background fill color $ bg_color = array (255,255,255) (red, green, blue, transparency)
* Transparency (0 opacity-127 completely transparent) Others: intelligent mode scales the image and carries the middle part of the image $ width X $ height pixel size
* $ Fit = 'force', 'scale', and 'scale _ fill ': outputs the complete image.
* $ Fit = when the image orientation value is specified, the correspondence between letters in the specified position and the image is as follows:
* North_west north north_east
* West center east
* South_west south south_east
*/
Public function resize_to ($ width = 100, $ height = 100, $ fit = 'center', $ fill_color = array (255,255,255, 0 )){
Switch ($ fit ){
Case 'Force ':
If ($ this-> type = 'GIF '){
$ Image = $ this-> image;
$ Canvas = new Imagick ();

$ Images = $ image-> coalesceImages ();
Foreach ($ images as $ frame ){
$ Img = new Imagick ();
$ Img-> readImageBlob ($ frame );
$ Img-> thumbnailImage ($ width, $ height, false );

$ Canvas-> addImage ($ img );
$ Canvas-> setImageDelay ($ img-> getImageDelay ());
}
$ Image-> destroy ();
$ This-> image = $ canvas;
} Else {
$ This-> image-> thumbnailImage ($ width, $ height, false );
}
Break;
Case 'scale ':
If ($ this-> type = 'GIF '){
$ Image = $ this-> image;
$ Images = $ image-> coalesceImages ();
$ Canvas = new Imagick ();
Foreach ($ images as $ frame ){
$ Img = new Imagick ();
$ Img-> readImageBlob ($ frame );
$ Img-> thumbnailImage ($ width, $ height, true );

$ Canvas-> addImage ($ img );
$ Canvas-> setImageDelay ($ img-> getImageDelay ());
}
$ Image-> destroy ();
$ This-> image = $ canvas;
} Else {
$ This-> image-> thumbnailImage ($ width, $ height, true );
}
Break;
Case 'scale _ fill ':
$ Size = $ this-> image-> getImagePage ();
$ Src_width = $ size ['width'];
$ Src_height = $ size ['height'];

$ X = 0;
$ Y = 0;

$ Dst_width = $ width;
$ Dst_height = $ height;

If ($ src_width * $ height> $ src_height * $ width ){
$ Dst_height = intval ($ width * $ src_height/$ src_width );
$ Y = intval ($ height-$ dst_height)/2 );
} Else {
$ Dst_width = intval ($ height * $ src_width/$ src_height );
$ X = intval ($ width-$ dst_width)/2 );
}

$ Image = $ this-> image;
$ Canvas = new Imagick ();

$ Color = 'rgba ('. $ fill_color [0]. ','. $ fill_color [1]. ','. $ fill_color [2]. ','. $ fill_color [3]. ')';
If ($ this-> type = 'GIF '){
$ Images = $ image-> coalesceImages ();
Foreach ($ images as $ frame ){
$ Frame-> thumbnailImage ($ width, $ height, true );

$ Draw = new ImagickDraw ();
$ Draw-> composite ($ frame-> getImageCompose (), $ x, $ y, $ dst_width, $ dst_height, $ frame );

$ Img = new Imagick ();
$ Img-> newImage ($ width, $ height, $ color, 'GIF ');
$ Img-> drawImage ($ draw );

$ Canvas-> addImage ($ img );
$ Canvas-> setImageDelay ($ img-> getImageDelay ());
$ Canvas-> setImagePage ($ width, $ height, 0, 0 );
}
} Else {
$ Image-> thumbnailImage ($ width, $ height, true );

$ Draw = new ImagickDraw ();
$ Draw-> composite ($ image-> getImageCompose (), $ x, $ y, $ dst_width, $ dst_height, $ image );

$ Canvas-> newImage ($ width, $ height, $ color, $ this-> get_type ());
$ Canvas-> drawImage ($ draw );
$ Canvas-> setImagePage ($ width, $ height, 0, 0 );
}
$ Image-> destroy ();
$ This-> image = $ canvas;
Break;
Default:
$ Size = $ this-> image-> getImagePage ();
$ Src_width = $ size ['width'];
$ Src_height = $ size ['height'];

$ Crop_x = 0;
$ Crop_y = 0;

$ Crop_w = $ src_width;
$ Crop_h = $ src_height;

If ($ src_width * $ height> $ src_height * $ width ){
$ Crop_w = intval ($ src_height * $ width/$ height );
} Else {
$ Crop_h = intval ($ src_width * $ height/$ width );
}

Switch ($ fit ){
Case 'North _ West ':
$ Crop_x = 0;
$ Crop_y = 0;
Break;
Case 'North ':
$ Crop_x = intval ($ src_width-$ crop_w)/2 );
$ Crop_y = 0;
Break;
Case 'North _ East ':
$ Crop_x = $ src_width-$ crop_w;
$ Crop_y = 0;
Break;
Case 'West ':
$ Crop_x = 0;
$ Crop_y = intval ($ src_height-$ crop_h)/2 );
Break;
Case 'center ':
$ Crop_x = intval ($ src_width-$ crop_w)/2 );
$ Crop_y = intval ($ src_height-$ crop_h)/2 );
Break;
Case 'East ':
$ Crop_x = $ src_width-$ crop_w;
$ Crop_y = intval ($ src_height-$ crop_h)/2 );
Break;
Case 'South _ West ':
$ Crop_x = 0;
$ Crop_y = $ src_height-$ crop_h;
Break;
Case 'South ':
$ Crop_x = intval ($ src_width-$ crop_w)/2 );
$ Crop_y = $ src_height-$ crop_h;
Break;
Case 'South _ East ':
$ Crop_x = $ src_width-$ crop_w;
$ Crop_y = $ src_height-$ crop_h;
Break;
Default:
$ Crop_x = intval ($ src_width-$ crop_w)/2 );
$ Crop_y = intval ($ src_height-$ crop_h)/2 );
}

$ Image = $ this-> image;
$ Canvas = new Imagick ();

If ($ this-> type = 'GIF '){
$ Images = $ image-> coalesceImages ();
Foreach ($ images as $ frame ){
$ Img = new Imagick ();
$ Img-> readImageBlob ($ frame );
$ Img-> cropImage ($ crop_w, $ crop_h, $ crop_x, $ crop_y );
$ Img-> thumbnailImage ($ width, $ height, true );

$ Canvas-> addImage ($ img );
$ Canvas-> setImageDelay ($ img-> getImageDelay ());
$ Canvas-> setImagePage ($ width, $ height, 0, 0 );
}
} Else {
$ Image-> cropImage ($ crop_w, $ crop_h, $ crop_x, $ crop_y );
$ Image-> thumbnailImage ($ width, $ height, true );
$ Canvas-> addImage ($ image );
$ Canvas-> setImagePage ($ width, $ height, 0, 0 );
}
$ Image-> destroy ();
$ This-> image = $ canvas;
}
}

// Add a watermark image
Public function add_watermark ($ path, $ x = 0, $ y = 0 ){
$ Watermark = new Imagick ($ path );
$ Draw = new ImagickDraw ();
$ Draw-> composite ($ watermark-> getImageCompose (), $ x, $ y, $ watermark-> getImageWidth (), $ watermark-> getimageheight (), $ watermark );

If ($ this-> type = 'GIF '){
$ Image = $ this-> image;
$ Canvas = new Imagick ();
$ Images = $ image-> coalesceImages ();
Foreach ($ image as $ frame ){
$ Img = new Imagick ();
$ Img-> readImageBlob ($ frame );
$ Img-> drawImage ($ draw );

$ Canvas-> addImage ($ img );
$ Canvas-> setImageDelay ($ img-> getImageDelay ());
}
$ Image-> destroy ();
$ This-> image = $ canvas;
} Else {
$ This-> image-> drawImage ($ draw );
}
}

// Add watermark text
Public function add_text ($ text, $ x = 0, $ y = 0, $ angle = 0, $ style = array ()){
$ Draw = new ImagickDraw ();
If (isset ($ style ['font'])
$ Draw-> setFont ($ style ['font']);
If (isset ($ style ['font _ size'])
$ Draw-> setFontSize ($ style ['font _ size']);
If (isset ($ style ['fill _ color'])
$ Draw-> setFillColor ($ style ['fill _ color']);
If (isset ($ style ['Under _ color'])
$ Draw-> setTextUnderColor ($ style ['Under _ color']);

If ($ this-> type = 'GIF '){
Foreach ($ this-> image as $ frame ){
$ Frame-> annotateImage ($ draw, $ x, $ y, $ angle, $ text );
}
} Else {
$ This-> image-> annotateImage ($ draw, $ x, $ y, $ angle, $ text );
}
}

// Save to the specified path
Public function save_to ($ path ){
// Compress the image quality
$ This-> image-> setImageFormat ('jpeg ');
$ This-> image-> setImageCompression (Imagick: COMPRESSION_JPEG );
$ A = $ this-> image-> getImageCompressionQuality () * 0.60;
If ($ a = 0 ){
$ A = 60;
}
$ This-> image-> setImageCompressionQuality ($ );
$ This-> image-> stripImage ();

If ($ this-> type = 'GIF '){
$ This-> image-> writeImages ($ path, true );
} Else {
$ This-> image-> writeImage ($ path );
}
}

// Output image
Public function output ($ header = true ){
If ($ header)
Header ('content-type: '. $ this-> type );
Echo $ this-> image-> getImagesBlob ();
}
Public function get_width (){
$ Size = $ this-> image-> getImagePage ();
Return $ size ['width'];
}
Public function get_height (){
$ Size = $ this-> image-> getImagePage ();
Return $ size ['height'];
}

// Set the image type, which is consistent with the source type by default.
Public function set_type ($ type = 'PNG '){
$ This-> type = $ type;
$ This-> image-> setImageFormat ($ type );
}

// Obtain the source image type
Public function get_type (){
Return $ this-> type;
}

Public function get_file_size (){
If ($ this-> image ){
Return 0; // $ this-> image-> getImageLength (); getImageLength not find
} Else {
Return 0;
}
}

Public function get_file_type (){
If ($ this-> image ){
Return $ this-> image-> getimagemimetype ();
} Else {
Return 0;
}
}

Public function get_sha1 (){
If ($ this-> image ){
Return sha1 ($ this-> image->__ tostring ());
} Else {
Return '';
}
}

// Whether the current object is an image
Public function is_image (){
If ($ this-> image)
Return true;
Else
Return false;
}

/*
* Add a border $ width: left and right border width $ height: Upper and Lower border width $ color: RGB color 'rgb (255, 0, 0) 'hexadecimal color' # ff000000' or 'white '/'red '...
*/
Public function border ($ width, $ height, $ color = 'rgb (220,220,220 )'){
$ Color = new ImagickPixel ();
$ Color-> setColor ($ color );
$ This-> image-> borderImage ($ color, $ width, $ height );
}
Public function blur ($ radius, $ sigma ){
$ This-> image-> blurImage ($ radius, $ sigma );
} // Fuzzy
Public function gaussian_blur ($ radius, $ sigma ){
$ This-> image-> gaussianBlurImage ($ radius, $ sigma );
} // Gaussian blur
Public function motion_blur ($ radius, $ sigma, $ angle ){
$ This-> image-> motionBlurImage ($ radius, $ sigma, $ angle );
} // Motion blur
Public function radial_blur ($ radius ){
$ This-> image-> radialBlurImage ($ radius );
} // Radial blur
Public function add_noise ($ type = null ){
$ This-> image-> addNoiseImage ($ type = null? Imagick: NOISE_IMPULSE: $ type );
} // Add noise
Public function level ($ black_point, $ gamma, $ white_point ){
$ This-> image-> levelImage ($ black_point, $ gamma, $ white_point );
} // Adjust the color level
Public function modulate ($ brightness, $ saturation, $ hue ){
$ This-> image-> modulateImage ($ brightness, $ saturation, $ hue );
} // Adjust the brightness, saturation, and tone
Public function charcoal ($ radius, $ sigma ){
$ This-> image-> charcoalImage ($ radius, $ sigma );
} // Sketch
Public function oil_paint ($ radius ){
$ This-> image-> oilPaintImage ($ radius );
} // Oil painting effect
Public function flop (){
$ This-> image-> flopImage ();
} // Horizontal flip
Public function flip (){
$ This-> image-> flipImage ();
} // Vertical Flip
}

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.