Minggu, 30 Agustus 2020

Save PNG image from HTML5 Canvas (the correct way, proved working!!)

This post is kind of a continuation of my previous post 'Take A Picture From Webcam With HTML5'. I had then an issue how to save the image localy. The image taken from the webcam is saved in base64 encoded data with this format data:image/png;base64,AAAFBfj....[base64 encoded data]

After I googled around, the most solution that I found told me just seperate the base64 data from that format and decode it directly to save the image. Unfortunately, its not that easy!!!

shortly, I'll show you how to do it correctly. This solution is shown here. Thanks mas bro Fazlurr!! you are the best.

again, I developed the application using Codeigniter and the code I show here is the function to save the image localy. This function is called by an AJAX function. 



function saveImage(){
     $img = str_replace('data:image/png;base64,', '', $_POST['data']);
     $img = str_replace(' ', '+', $img);
     $data = base64_decode($img);
     $file = FCPATH.'/image/page/'.$_POST['name'].'.png';
     $success = file_put_contents($file, $data);
     echo $success ? '1' : '0';
}



the AJAX send  two POST data; the image data taken from canva and the name used for this image. Take a look at the third line, this line is the key. Other solutions found in google don't have this line, so most of them failed to save the image correctly. 

Well, the funny thing is that I know it works but I don't know what does that third line do, so dont ask me why this code works...ehehehe....

Tidak ada komentar:

Posting Komentar