Return Imagick image as response - SOLVED


#1

Hi,

I have a some code, which looks like this:

$app->get(’/test’, function (Request $request, Response $response, array $args) {
$image = new Imagick();
$image->newImage(100, 100, new ImagickPixel(‘red’));
$image->setImageFormat(‘png’);
$imageData = base64_encode($image->getImageBlob());
$src = ‘data: ‘. ‘image/gif’ .’;base64,’.$imageData;
$response->withHeader(‘Content-Type’, ‘image/png’);
$response->write($src);
return $response;
});

When I look at the source view after running this, I see:

  1. (a blank line)
  2. data:
  3. image/gif;base64,iVBORw0KGgoAAA…[insert lots of base64 encoded stuff here]…uQmCC

If I look at the inspect view in Chrome, I see:
html
head
body
pre
data:
image/gif;base64,iVBORw0KGgoAAA…[insert lots of base64 encoded stuff here]…uQmCC
/pre
/body
/html

So, my question is how do I replace the response with the actual image, instead of the text representation of the image?

Many thanks,

Jase


#2

I eventually found the solution. Just incase anyone else wants to know how I did it, this works:

$app->get(’/test’, function (Request $request, Response $response, array $args) {
$image = new Imagick();
$image->newImage(100, 100, new ImagickPixel(‘red’));
$image->setImageFormat(‘png’);
$imageData = base64_encode($image->getImageBlob());
$src = ‘data: ‘. ‘image/gif’ .’;base64,’.$imageData;
header(“Content-Type: image/png”);
echo ‘’;
});