php imagick rounded rectangle with border

In this post I will show you how to “draw” a rounded rectangle with a border. This will involve creating a new ImagickDraw object, then applying your draw settings to an Imagick object.

First, set up all your colors, image size, border width, and corner radius. After you have set all the input variables, the script will calculate the dimensions of the rectangle you are going to draw within the size of your image. To do this you must subtract the size of the border from the height and width of your desired image size, otherwise the rectangle will get cut off.

Then the script creates a new Imagick object, and applies your background color. The next step is to create your ImagickDraw object and set your fill color. If you have specified a border width greater than 0, the script will set the stroke color and width. Now the script sets up the rounded rectangle with all the settings you specified in the first step and what the script had calculated for the rectangle’s height and width.

Once the ImagickDraw object is all set up, the script will “draw” it onto the Imagick canvas previously created. And Voila! You have a rounded rectangle with a border. Uncomment the caching code if you want to have the script save the resulting image to disk.

$background = "transparent";
$fillcolor = "#C5E3FF";
$bordercolor = "#226FB6";
$borderwidth = 2;
$cornerradius = 10;
$height = 300;
$width = 300;
//$cachefile = 'path/to/your/cachefile.png';
//if (!file_exists($cachefile)) {
		$rectwidth = ($borderwidth>0?($width-($borderwidth+1)):$width-1);
		$rectheight = ($borderwidth>0?($height-($borderwidth+1)):$height-1);
		$canvas = new Imagick();
		$canvas->newImage($width, $height, $background, "png" );
		$draw = new ImagickDraw();
		$draw->roundRectangle($borderwidth, $borderwidth, $rectheight, $rectwidth, $cornerradius, $cornerradius);
		header("Content-Type: image/png");
		echo $canvas;
	}catch(Exception $e){
		echo 'Error: ',  $e->getMessage(), "";
	$canvas = new imagick($cachefile);
	header("Content-Type: image/png");
	echo $canvas;

NOTE: “$cachefile” path must be writable by the server if you want to save the image to disk.

1 Comment to php imagick rounded rectangle with border

  1. suman's Gravatar suman
    February 10, 2017 at 3:14 am | Permalink

    how to add text on a rectangle in PHP image magick

Leave a Reply

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>