Add border around png image using imagick PHP -


how can add border around png image? whenever try add border using borderimage function available in imagick loses transparency if png image.

<?php  $image = new imagick(); $image->readimage('tux.png');  $image->borderimage(new imagickpixel("red") , 5,5);  // send result browser header("content-type: image/" . $image->getimageformat()); echo $image; 

this original image:

enter image description here

and after adding border:

enter image description here

border color applied onto background. want using imagick how can apply border transparent image without losing transparency?

if want achieve result this:

result image

then it. can give padding between border , image if want!

/** set source image location. can use url here **/ $imagelocation = 'tux.png';  /** set border format **/ $borderwidth = 10;  // can use color name, hex code, rgb() or rgba() $bordercolor = 'rgba(255, 0, 0, 1)';  // padding between image , border. set 0 give none $borderpadding = 0;   /** core program **/  // create imagick object source image $imagesource = new imagick( $imagelocation );  // image width , height, , automatically set wider // source image dimension give space border (and padding if set) $imagewidth = $imagesource->getimagewidth() + ( 2 * ( $borderwidth + $borderpadding ) ); $imageheight = $imagesource->getimageheight() + ( 2 * ( $borderwidth + $borderpadding ) );  // create imagick object final image border $image = new imagick();  // set image canvas $image->newimage( $imagewidth, $imageheight, new imagickpixel( 'none' ) );  // create imagickdraw object draw border $border = new imagickdraw();  // set fill color transparent $border->setfillcolor( 'none' );  // set border format $border->setstrokecolor( new imagickpixel( $bordercolor ) ); $border->setstrokewidth( $borderwidth ); $border->setstrokeantialias( false );  // draw border $border->rectangle(     $borderwidth / 2 - 1,     $borderwidth / 2 - 1,     $imagewidth - ( ($borderwidth / 2) ),     $imageheight - ( ($borderwidth / 2) ) );  // apply drawed border final image $image->drawimage( $border );  $image->setimageformat('png');  // put source image final image $image->compositeimage(     $imagesource, imagick::composite_default,     $borderwidth + $borderpadding,     $borderwidth + $borderpadding );  // prepare image , publish! header("content-type: image/png"); echo $image; 

i got method here. make rectangle transparent fill , formatted border using imagickdraw::rectangle, put image inside rectangle using imagick::compositeimage.

here result if set $borderpadding 10:

alternative result image

that's it! hope helps :)


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -