How can I add a border around a png image? Whenever I try to add a border using borderImage function available in imagick it loses its transparency if it is a png image.
<?php
$image = new Imagick();
$image->readImage('tux.png');
$image->BorderImage(new ImagickPixel("red") , 5,5);
// send the result to the browser
header("Content-Type: image/" . $image->getImageFormat());
echo $image;
This is the original image:
and this is after adding a border:
Border color is also applied onto the background. I want to do this using imagick How can I apply a border to a transparent image without losing transparency?
If you want to achieve result like this:
then this is it. You can even give padding between border and image if you want!
/** Set source image location. You can use URL here **/
$imageLocation = 'tux.png';
/** Set border format **/
$borderWidth = 10;
// You can use color name, hex code, rgb() or rgba()
$borderColor = 'rgba(255, 0, 0, 1)';
// Padding between image and border. Set to 0 to give none
$borderPadding = 0;
/** Core program **/
// Create Imagick object for source image
$imageSource = new Imagick( $imageLocation );
// Get image width and height, and automatically set it wider than
// source image dimension to give space for border (and padding if set)
$imageWidth = $imageSource->getImageWidth() + ( 2 * ( $borderWidth + $borderPadding ) );
$imageHeight = $imageSource->getImageHeight() + ( 2 * ( $borderWidth + $borderPadding ) );
// Create Imagick object for final image with border
$image = new Imagick();
// Set image canvas
$image->newImage( $imageWidth, $imageHeight, new ImagickPixel( 'none' )
);
// Create ImagickDraw object to draw border
$border = new ImagickDraw();
// Set fill color to 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 to final image
$image->drawImage( $border );
$image->setImageFormat('png');
// Put source image to final image
$image->compositeImage(
$imageSource, Imagick::COMPOSITE_DEFAULT,
$borderWidth + $borderPadding,
$borderWidth + $borderPadding
);
// Prepare image and publish!
header("Content-type: image/png");
echo $image;
I got this method from here. Basically we just make a rectangle with transparent fill and formatted border using ImagickDraw::rectangle
, then we put the image inside the rectangle using Imagick::compositeImage
.
Here is the result if you set $borderPadding
to 10
:
That's it! Hope it helps :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With