How to Perfectly Replace GD with ImageMagick for Image Processing in PHP

PNG images can also be compressed by reducing the number of colors. However, images compressed this way often show visible distortion with jagged edges. For real-world PNG images (typically photos), it’s common to convert them to JPG first and then apply the compression methods mentioned above. But note: when converting transparent or semi-transparent PNG images to JPG, the transparent areas will turn black… It’s recommended not to convert user avatars to JPG.. It looks terrible~~~ My own avatar is a victim of this.. Regarding image file extensions: I’ve noticed most websites tend to uniformly convert user-uploaded images (avatars, albums, etc.) to a specific format (usually jpg). The potential downside of this is that when processing with software like ImageMagick, it performs implicit format conversion based on the extension. Personally, I think saving images without an extension offers more flexibility in processing.

 Note: Adapting the command line above for use in Rails with mini_magick is very easy. mini_magick essentially calls system command lines anyway~~

Specific Example: Below is an image upload class:
It implements uniform resizing of images

 /**
 * @filesource upload.func.php
 * Upload image, requires ImageMagick
 */ 
/**
 * Upload file
 * $size: dimensions (format 100×100, lowercase x)
 * Return value:
 * 0 File type error
 */ 
function upFile($size, $subdir){ 
    set_time_limit(0); 
    $fileType = array("jpg","gif","bmp","jpeg","png"); 
    $upPath = dirname(dirname(dirname(__FILE__))) 
        .DIRECTORY_SEPARATOR.'rooms'.DIRECTORY_SEPARATOR.'Img' 
        .DIRECTORY_SEPARATOR.$subdir.DIRECTORY_SEPARATOR; 
    //if(file_exists($upPath)) unlink($upPath);mkdir($upPath); 
    if( !is_dir($upPath))   mkdir($upPath); 
    $a = strtolower( pathinfo($_FILES['uploadfile']['name'], PATHINFO_EXTENSION) ); 
    //Check file type 
    if(!in_array( $a, $fileType )) { 
        //$text=implode(",",$fileType); 
        return 2; //echo "You can only upload the following file types: ",$text,"<br>"; 
    } else{ //Generate target filename  
        $filename=explode(".", $_FILES['uploadfile']['name']); 
        do{  
            $filename[0]=$size; //Name image file by dimensions 
            $name=implode(".", $filename); 
            $uploadfile= $upPath.$name; 
        }while( file_exists($uploadfile) ); 
        try { 
            if ( copy($_FILES['uploadfile']['tmp_name'], $uploadfile) ){ 
                ///usr/bin/convert 
                exec("/usr/local/imagemagick/bin/convert -resize '{$size}>!' {$uploadfile} {$uploadfile}"); 
                return "/kkyoo/rooms/icoImg/{$subdir}/".$name; 
            } 
        }catch (Exception $e){ 
            echo $e->getMessage(); 
        } 
    } 
    return 0; 
}

Leave a Comment

Your email address will not be published.