Venky Rao
Venky Rao

Reputation: 106

Laravel - Cannot serve a .png image stored in my database as a base64 encoded string

I created a png image for a div on my page using HTML2Canvas, which creates a base64 encoded string for the image. I display it on the page as an inline:

<img id="headerImage" src="data:image/png;base64,iVBORw0KGg..." width="60">

I then save it in my database as a LONGTEXT.

In my controller, I seem unable to server the image back as a valid PNG. Tried a bunch of different ways, as evident in the code snippet:

                $imageStr = $plan->image;

                $pos = strpos($imageStr, ',');
                $trimmed = substr($imageStr, $pos+1);

                $image = base64_decode($trimmed);

                /*
                $im = imagecreatefromstring($image);
                if ($im !== false) {
                        header('Content-Type: image/png');
                        imagepng($im);
                        imagedestroy($im);
                } else {
                        echo 'Failed';
                }

                return;
                */

                $response = Response::make(trim($image), 200);
                $response->header('Content-Type', 'image/png');

                return $response;

                /*
                return Response::stream(function() use ($image) {
                        echo $image;
                        }, 200, array('Content-Type:image/png'));
                */

When I look at the headers, it looks reasonable:

t=4102 [st=437]        HTTP_TRANSACTION_READ_RESPONSE_HEADERS
                       --> HTTP/1.1 200 OK
                           Date: Tue, 24 Feb 2015 16:36:28 GMT
                           Server: Apache/2.4.7 (Ubuntu)
                           X-Powered-By: PHP/5.5.9-1ubuntu4.5
                           Cache-Control: no-cache
                           Set-Cookie: [362 bytes were stripped]
                           Keep-Alive: timeout=5, max=100
                           Connection: Keep-Alive
                           Transfer-Encoding: chunked
                           Content-Type: image/png
t=4102 [st=437]     -HTTP_TRANSACTION_READ_HEADERS

In all cases, the browser shows a broken image symbol. Getting to my wit's end at this point - appreciate any ideas on how to do this!

Upvotes: 2

Views: 4619

Answers (1)

Marcus Olsson
Marcus Olsson

Reputation: 2527

Your code should work as it is.

A note about Base64-encoded images; to decode them again, you have to remove the data:image/png;base64 part of the string.

So:

<?php
$imageStr = $plan->image; // Or wherever you get your string from
$image = base64_decode(str_replace('data:image/png;base64,', '', $imageStr));

$response = Response::make($image, 200);
$response->header('Content-Type', 'image/png');

return $response;

Also, imagecreatefromstring is superfluous in this case.

Upvotes: 6

Related Questions