6

is it possible to create and display a picture file from dataURL received by POST? Something like:

<?
$imgstr = $_POST["imgdata"]; //data:image/png;base64,.... etc (it's always PNG)
echo base64_decode($imgstr); // idk what this really does
?>

I can't use <img> tag to display it. It needs to act like a "normal" image file.

3 Answers 3

6

Yes, try:

<img alt="Base64 Image" src="data:image/png;base64,{$imgstr}" />

Edit: make sure you clean up your $_POST, so people do not insert dangerous junk...

Sign up to request clarification or add additional context in comments.

Comments

4

If e.g. your input is

// Red dot graphic, stolen from Wikipedia
$imgstr = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==';

Then you can do what you want with

// Grab the MIME type and the data with a regex for convenience
if (!preg_match('/data:([^;]*);base64,(.*)/', $imgstr, $matches)) {
    die("error");
}

// Decode the data
$content = base64_decode($matches[2]);

// Output the correct HTTP headers (may add more if you require them)
header('Content-Type: '.$matches[1]);
header('Content-Length: '.strlen($content));

// Output the actual image data
echo $content;
die;

Comments

1

You must set correct header before echo.

header( 'Content-Type: image/jpeg' );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.