Search code examples
phpimagemagickimagick

ImagickDraw Rectangle - image cannot be displayed error


I have two sites(same server) where a simple rectangle is drawn using ImagickDraw and it work fine on one and fails on second with the error -

The image "http://site_name/imagick/img?method=placeholder&params=258,150" cannot be displayed because it contains error.

Basically what code does is it take method and params(height & width) from the url and draw the image.

$params = explode(",", $_GET["params"]);
$width = (int) $params[0]; //258
$height = (int) $params[1]; //150

if ($method == "placeholder") { //This is true $method is set to placeholder
  $image = new Imagick();
  $image->newImage($width, $height, "#707070");
  $image->setImageFormat("png");

  $x = 0;
  $y = 0;
  $size = 40;
  $draw = new ImagickDraw();

  while ($y < $height) {
    $draw->setFillColor("#808080");

    $points = array(
      array("x" => $x, "y" => $y),
      array("x" => $x + $size, "y" => $y),
      array("x" => $x + $size * 2, "y" => $y + $size),
      array("x" => $x + $size * 2, "y" => $y + $size * 2),
    );
    $draw->polygon($points);

    $points = array(
      array("x" => $x, "y" => $y + $size),
      array("x" => $x + $size, "y" => $y + $size * 2),
      array("x" => $x, "y" => $y + $size * 2),
    );
    $draw->polygon($points);

    $x += $size * 2;
    if ($x > $width) {
      $x = 0;
      $y += $size * 2;
    }
  }

  $draw->setFillColor("#B0B0B0");
  $draw->setFontSize($width / 5);
  $draw->setFontWeight(800);
  $draw->setGravity(Imagick::GRAVITY_CENTER);
  $draw->annotation(0, 0, $width . " x " . $height);

  $image->drawImage($draw);

  header("Content-type: image/png");
  echo $image;
}

I've checked the buffer before header and it is empty also tried ob_clean() - still doesn't work.

Checked for white-spaces in the file as I've found it to be affecting the image file - but there is no white-space present.

Any ideas what might be wrong here or anyway to track the errors?


Solution

  • It was indeed the whitespace but not in the same file (weird weird weird).

    Checked for all the php files included in the project with -

    include_once('file_name.php');
    

    From multiple files, there was one such file(setting file which contains the db_name, base url, etc) which had a space before <?php tag. So if someone gets this error, make sure all the php files are whitespace free. It messes the png image generated.