How to fix 'Unable to annotate image' error when using ImageMagick? - php

I am using php 7.0.19 and ImageMagick 6.9.6-4 on a FreeBSD 11.0 server. I use imagemagick for quite a few things, but I am just getting started with using it to overlay text on top of my images. The problem I'm having is that any time I try to use the annotateImage functionality an error is thrown that simply says 'Unable to annotate image.'
I have looked through quite a few questions related to annotateImage here on stackoverflow and I have checked the docs to see if I could resolve the issue on my own, but I'm stuck. On other annotateImage questions I have seen that some people have trouble due to not having a specific font installed, and that may be my problem as well, but I have tried placing a font file (the ttf file) in the same directory as my script and I am still having the same issue.
Running convert -list font returns an empty result, indicating that there are no fonts that imagemagick has direct/default access to; however, I was thinking that by including the font file in the same directory as my script I could make it work anyway. Perhaps this is a mistaken assumption?
Here is the code I am using for my test:
$imagick = new Imagick('originalImage.jpg');
$draw = new ImagickDraw();
$draw->setFillColor('#ffffff');
$draw->setFont('ARIAL.TTF');
$draw->setFontSize(20);
$imagick->annotateImage($draw, 20, 100, 0, 'The quick fox jumps over the lazy dog');
$imagick->drawImage($draw);
$imagick->writeImage('finalImage.jpg');
I have also tried other example scripts that don't require an original image, and received the same error. For example, this script produces the same error:
$image = new Imagick();
$draw = new ImagickDraw();
$pixel = new ImagickPixel( 'gray' );
$image->newImage(800, 75, $pixel);
$draw->setFillColor('black');
$draw->setFont('ARIAL.TTF');
$draw->setFontSize( 30 );
$image->annotateImage($draw, 10, 45, 0,
'The quick brown fox jumps over the lazy dog');
$image->setImageFormat('png');
header('Content-type: image/png');
echo $image;
With this simple test I was expecting to add 'The quick fox jumps over the lazy dog' over the top of my image, but instead an exception is thrown and the error message simply says: Unable to annotate image.
Any ideas or suggestions on how I can resolve the error?
Thanks!

Through posting this question on the imagemagick forum, I was able to get it figured out. The problem was that our ImageMagick install is missing the 'freetype' delegate, which is required for rendering text from fonts.
Thanks!

Related

PHP Imagick timing out during execution while annotating image

I'm running into an unusual issue here. I'm simply trying to annotate an image with ImageMagick on PHP (installed via PECL), and the script times out. I've been able to narrow it down to where I annotate the image due to the fact that PHP tells me it times out at line 13 (code below):
<?
$imagick = new Imagick();
$imagick->readImage("static/image.jpg");
$draw = new ImagickDraw();
$draw->setStrokeColor("white");
$draw->setFillColor("black");
$draw->setStrokeWidth(2);
$draw->setFontSize(36);
//$draw->setFont("static/fonts/Impact.ttf");
$imagick->annotateimage($draw, 40, 40, 0, "Lorem Ipsum!");
header("Content-Type: image/jpg");
echo $imagick;
?>
At this point in time I've just copied and pasted code from a tutorial. I did have my own code but it didn't work, so I decided to copy just to see whether I'd done something wrong. Lo and behold, this doesn't work either. If I remove both of the two lines ($draw->setFont) and the annotateImage it outputs the image just fine. For some reason I can not annotate correctly.
I can verify that it does not work if I use 'Arial' as the font instead of the copy of Impact.ttf that I have.
To clarify: I'm on OS X, using XAMPP.

Losing transparency of png with php magickwand and imagemagick when rotation is applied

Hi I'm porting a script from a windows environment running MagickWand 0.1.8 and ImageMagick 6.2.9 where transparency worked fine with MagickRotateImage.
New environment is linux running MagickWand 1.0.8 with ImageMagick 6.5.4-7 and transparency gets lost and it shows black as the background as soon as my logo image gets rotated.
From what I've found online, seems that PixelSetColor($bg,"none") doesn't work with the newer versions hence the black. Ultimately, I need to know what to replace PixelSetColor($bg,"none") with. I just don't have a background in image creation so struggling a bit with this.
First my php runs this function which makes a local 60x60 version of 600x600 png image gotten from a url.
function makeThumb($fileContents){
GLOBAL $localImgPath1;
GLOBAL $localImgPath2;
$wand = NewMagickWand();
$lg = MagickReadImageBlob($wand,$fileContents);
$lg_w = MagickGetImageWidth($wand);
$lg_h = MagickGetImageHeight($wand);
$max = max($lg_h,$lg_w);
$scale_factor = 60/$max;
MagickResizeImage($wand,$lg_w*$scale_factor,$lg_h*$scale_factor, MW_GaussianFilter, .7);
MagickWriteImage($wand, $localImgPath1);
if($localImgPath2!="")
MagickWriteImage($wand, $localImgPath2);
$resized_w = MagickGetImageWidth($wand);
$resized_h = MagickGetImageHeight($wand);
DestroyMagickWand($wand);
}
then, I use this to read that locally written png image and rotate it:
$logo = NewMagickWand();
$bg = NewPixelWand();
PixelSetColor($bg,"none");
MagickReadImage($logo, $localImgPath1);
MagickRotateImage($logo, $bg, $r);
header('Content-Type: image/PNG');
MagickEchoImageBlob($logo);
DestroyPixelWand($bg);
DestroyMagickWand($logo);
I've tried things like adding:
$transparent = NewPixelWand("#FFFFFF");
PixelSetAlpha($transparent, 0);
//and then making the rotate call:
MagickRotateImage($logo, $transparent, $r);
Also tried adding MagickSetImageAlphaChannel($logo, MW_SetAlphaChannel); before the rotate step. Saw some posts mentioning that method but possibly that's not the correct way to use it. Not sure.
I also have the same problem in a script that draws a text string with a set font onto the image. Black immediately shows there even before rotation is applied so hoping same fix for the logo script will be useable by the font script.
Any help would be greatly appreciated. Thanks.
You've got a choice of four values for a transparent background. Try each in turn:
"none", "transparent", "#00000000", or "rgba(0, 0, 0, 0.0)"
The problem was with ImageMagick 6.5.4-7. Must have been a buggy release. Upgraded to 6.8.4-10 and above code works fine, PixelSetColor($bg,"none") works for the transparency.

Imagick: Failed to query the font metrics

I'm working on (what should be) a simple script that will add text to an image. After going over my script several times looking for any mistakes I finally decided to try running a sample from php.net and I encountered the same, nondescript, error: "Failed to query the font metrics". Here's the code:
/* Text to write */
$text = "Hello World!";
/* Create Imagick objects */
$image = new Imagick();
$draw = new ImagickDraw();
$color = new ImagickPixel('#000000');
$background = new ImagickPixel('none'); // Transparent
/* Font properties */
$draw->setFont('Arial');
$draw->setFontSize(50);
$draw->setFillColor($color);
$draw->setStrokeAntialias(true);
$draw->setTextAntialias(true);
/* Get font metrics */
$metrics = $image->queryFontMetrics($draw, $text);
/* Create text */
$draw->annotation(0, $metrics['ascender'], $text);
/* Create image */
$image->newImage($metrics['textWidth'], $metrics['textHeight'], $background);
$image->setImageFormat('png');
$image->drawImage($draw);
/* Save image */
file_put_contents('/tmp/file.png', $image);
I can not for the life of me find any information via google about this error. Nor can I find adequate documentation on this method or potential causes of failure. Basically, I'm stumped. If anyone could provide insight or a fix it would be greatly appreciated.
ImageMagic version: ImageMagick 6.6.5-10 2011-04-06 Q16
Imagick module version: 3.1.0b1
have you tried cli version ? is imagemagick installed on server ? if yes
then run a command like
system('convert -background lightblue -fill blue \
-font Candice -pointsize 72 label:Anthony \
label.gif ');
see if you have imagenamed label.gif in server after running script.
for your reference http://www.imagemagick.org/Usage/text/
For those having similar issues, the PHP Imagick exceptions aren't always the most descriptive. I could have saved myself a lot of time examining the output from the Image Magic application installed on the server first. Just something to keep in mind. To view a list of the currently installed delegates(modules) use the command convert -list configure and examine the line that starts with "DELEGATES" from the output. If you encounter the same error, I recommend checking here first. I found I was missing the freetype and ghostscript delegates. After installing the dependancies and a quick recompile of ImageMagick everything works like a charm.

Imagick roundCorners makes image half-transparant

I'm in the process of writing an image script for a website I'm making, and for one of the image modes I need to both crop the image and make round corners for it. This is the code I'm using now:
$img = new Imagick();
$img->readImageBlob($data);
$img->resizeImage($width, $height, $img->FILTER_GAUSSIAN, 1);
$canvas = new Imagick();
$canvas->newImage($size[0], $size[1], new ImagickPixel('white'));
$canvas->compositeImage($img, imagick::COMPOSITE_OVER, 0, 0);
$canvas->roundCorners(10, 10);
$canvas->setImageFormat('png');
Resulting image
However, the resulting image is about half-transparent, as seen above, except for a 10-ish px border around the edge, created by roundCorner I assume. I've tried a lot of different ways of doing this, including cropping $img directly and roundCorner on it, but then the result is without round corners.
I suspect compositeImage to be the thief in this drama, but I can't say for sure. Anyone?
EDIT: Correction: If I do the crop and round solution, I end up with rounded corners, but they have a black background. This is the code I'm using here. Anyone spot the error/solution?
$img = new Imagick();
$img->readImageBlob($data);
$img->resizeImage($width, $height, $img->FILTER_GAUSSIAN, 1);
$img->cropImage($size[0], $size[1], 0, 0);
$img->roundCorners(10, 10);
EDIT 2:
The solution to the crop and round resolution was to make sure it's a png, so that is has alpha-support. However, the result is the same as the one produced from my original code.
EDIT 3:
Tried this script on my deployment server, and it worked as I wanted it to, so it seems like there's some problem with the version of imagick / php-imagick shipped with macports. Thanks for all the help!
You can tell imagemagick to give you an alpha background with
$img->setImageAlphaChannel ( imagick::ALPHACHANNEL_TRANSPARENT )
or try setting the image format to PNG24 explicitly before doing any transformations.
Order is important here, the image needs an alpha channel before you expose the background.
It was a problem with the version of Imagick / php-imagick shipped with current macports. Haven't solved it for my computer, but the script is working as intended on my deployment server.

What's the problem with my php generated png file?

I want to make a unique forum signature from my latest watched animes in PHP. These are contained in an RSS feed. On my local apache server, the image is generated well, but as I upload it onto a server, I get an error, the picture isn't generated at all.
Here is my code and I wonder what's the problem since neither Dreamweaver CS5 or phpDesigner 7 don't show any errors, although if I press the Run button in phpDesigner, I get an error, but I don't know what it means. The error is the following:
Line: 6 - Fatal error: Call to undefined function imagecreatefrompng() in [php's path here]
So the code is the following:
<?php
// title & description arrays
$titleCuts = array();
$descCuts = array();
// bg image
$bgimg = imagecreatefrompng('sig_robin.png');
// colors
$white = imagecolorallocate($bgimg, 255, 255, 255);
$textColor = imagecolorallocate($bgimg, 245, 193, 9);
$shapeColor = imagecolorallocate($bgimg, 27, 20, 0);
// sxe <- xml url
$sxe = new SimpleXMLElement('http://myanimelist.net/rss.php?type=rw&u=fema', NULL, TRUE);
// shape
imagefilledrectangle($bgimg, 255, 20, 567, 279, $shapeColor);
// TEXTS
imagettftext($bgimg, 20, 0, 263, 52, $white, "my.ttf", "Latest Watched:");
// episodes' text
for($i=0;$i<5;$i++)
{
// title cut and joint
$titleCuts = explode(' ', $sxe->channel->item[$i]->title, -2);
$titleCut = implode(' ',$titleCuts);
// description (ep) cut and joint
$descCuts = explode(' ', $sxe->channel->item[$i]->description);
// output
imagettftext($bgimg, 10, 0, 270, 77+($i*45), $textColor, "my.ttf", $titleCut);
imagettftext($bgimg, 10, 0, 270+(strlen($titleCut)*7.2), 92+($i*45), $textColor, "my.ttf", "ep. ".$descCuts[2]);
}
header('Content-type: image/png');
// generating image
imagepng($bgimg);
?>
Thanks in advance.
Edit:
As I removed the header, now I get a lot of error that it can't find the font file, but I'm dead sure that I wrote it correctly.
They look like this:
Warning: imagettftext() [function.imagettftext]: Could not find/open font in ... on line 19
This means that GD either wasn't compiled into PHP or hasn't been loaded. First, check your php.ini, the path for which you can find with phpinfo() for extension=php_gd2.dll and make sure it's not commented out with a semicolon. After changing the setting, restart the webserver, then look at phpinfo() again to see if GD is loaded.
IF imagecreatefrompng is not defined, most likely the GD library is not installed, or broken, see: http://php.net/manual/en/image.installation.php
Don't be alarmed by the 'you have to configure and rebuild PHP', normally the package manager of your OS can easily add GD support by installing an extra package.
Ok, the solution for the second problem is that its a php bug http://bugs.php.net/bug.php?id=41336
But its easy to solve, in following way:
Put a ./ before every *.ttf file like in following example:
imagettftext(IMAGE, 0, 0, 0, 0, TEXT_COLOR, "./ttf_file.ttf", TEXT);
To use this function (imagecreatefrompng) your php needs to be installed with the GD extensions (for more information see this page.
To check what is / isn't install create a php file on your local server with just:
And then compare the image (GD) sections to the same file running on your server.
Note that if you are on a shared hosting server you'll probably have to contact their admins to install / configure this for you.

Categories