Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I have a base64 encoded png, how do I write the image to a file in PHP?

Tags:

php

png

gd

What's the proper way in PHP to create an image file (PNG), when I have the base64 encoding?

I've been playing around with:

  file_put_contents('/tmp/'. $_REQUEST['id'].'.png', $_REQUEST['data']);  

do I need to decode? should I be using the gd library?

like image 220
mmattax Avatar asked Oct 07 '09 17:10

mmattax


People also ask

Can a png be Base64?

World's simplest online Portable Network Graphics image to base64 converter. Just import your PNG image in the editor on the left and you will instantly get a base64-encoded string on the right. Free, quick, and very powerful. Import a PNG – get base64.

What format is data image png Base64?

data:image/png;base64 tells the browser that the data is inline, is a png image and is in this case base64 encoded. The encoding is needed because png images can contain bytes that are invalid inside a HTML document (or within the HTTP protocol even).

How can I download Base64 image in PHP?

header('Content-Disposition: attachment;filename="test. png"'); header('Content-Type: application/force-download'); echo base64_decode($base64strImg);


2 Answers

You need to use base64_decode(). AND. Sometimes it is not sufficient. Here is all code that you need:

$img = $_POST['data']; $img = str_replace('data:image/png;base64,', '', $img); $img = str_replace(' ', '+', $img); $fileData = base64_decode($img); //saving $fileName = 'photo.png'; file_put_contents($fileName, $fileData); 

P.S. I used this code to get PNG image from html canvas.

like image 190
Yevgeniy Afanasyev Avatar answered Oct 01 '22 04:10

Yevgeniy Afanasyev


My best guess is that you simply need to call base64_decode() on $_REQUEST['data'] before writing it to the file. That should be plenty enough :).

like image 38
Thibault Martin-Lagardette Avatar answered Oct 01 '22 05:10

Thibault Martin-Lagardette