One might think this would be an easy task, and it is, unless you want it to look good. Unfortunately, imagick really only performs well when processing images with an alpha channel. I’ve found that PNG format works best. So, to add rounded corners to a jpg image with php’s imagick object, there are a few steps involved.
First, you have to create an imagick object from the source image. Then, convert it to PNG format before applying the rounded corners. Once in PNG format, the script applies the rounded corners. If you dont care about having the large size of a png file, you can simply output the the browser at this point, but, if you want the smaller file size of a jpg, you must take a few more steps.
After adding the rounded corners to your now PNG file, you must create another imagick image object of the same size as your original image, with your desired background color, of image type jpg. Then, you composite the rounded corner png over the new solid background color image you just created.
Now that you have your rounded corner image over the correct background and in jpg format, you can set the image compression type and quality. Once this is done, you are ready to output the resulting jpg to the browser. There is cache code commented out if you would like to save the resulting jpg to disk.
<? $background = "#FFFFFF"; $imagefile = "/path/to/your/image.jpg"; $cornerradius_x = 50; $cornerradius_y = 50; $quality = 70; //$cachefile = '/path/to/your/cachedimage.jpg'; //if (!file_exists($cachefile)) { try{ $canvas = new Imagick($imagefile); $canvas->setImageFormat('PNG'); $canvas->roundCorners($cornerradius_x,$cornerradius_y); $canvas2 = new Imagick(); $canvas2->newimage($canvas->getImageWidth(), $canvas->getImageHeight(), $background, 'jpg'); $canvas2->compositeImage($canvas, imagick::COMPOSITE_OVER, 0, 0); $canvas2->setImageFormat('JPG'); $canvas2->setImageCompression(Imagick::COMPRESSION_JPEG); $canvas2->setImageCompressionQuality($quality); //$canvas2->writeImage($cachefile); header( "Content-Type: image/jpg" ); echo $canvas2; $canvas->clear(); $canvas->destroy(); $canvas2->clear(); $canvas2->destroy(); }catch(Exception $e){ echo 'Error: ', $e->getMessage(), ""; } /* }else{ $canvas = new imagick($cachefile); header("Content-Type: image/png"); echo $canvas; } */ ?> |
NOTE: your “cachefile.jpg” folder must be writable by the server.
You don’t say?