Saturday, February 26, 2011

Save a Base64 Encoded Canvas image to a png file using PHP

This and the next post will demonstrate how to draw on a canvas and then save the file on a server using PHP. Here is the very simple server side code:



The next post will be the slightly more complicated front-end code. This was particularly designed for a Sencha Touch iPad app that will allow people to sign with their finger. It has some flaws, but the basics are pretty reusable and good!

Your result may look something like this:

106 comments:

  1. Weird, this is not working for me. I get a blank .png file. I am using the jQuery Webcam Plugin for the canvas. When I print out my Base64 encoded data it looks fine to me. It even has that beginning few characters that you strip out.

    Any ideas?

    ReplyDelete
  2. @murko. all i can say is to check the http://www.xarg.org/project/jquery-webcam-plugin/ docs for their suggestion about how to do it. they're using flash and doing their own things with the canvas. it's possible they use more than one canvas, make sure you're grabbing data from the correct one.

    Please check out some of these examples: http://www.nihilogic.dk/labs/canvas2image/

    ReplyDelete
  3. you saved my day !

    actually this one was not working for me:

    http://wiki.phonegap.com/w/page/39539478/Upload%20an%20Image%20to%20a%20PHP%20Script

    thx

    ReplyDelete
  4. Please send me a code to capture the image form webcam and should store that image in database using PHP and Flex 4.5 .Waiting for a good response from u people. Thx in advance.

    ReplyDelete
  5. Thank you greatly for this code.

    ReplyDelete
  6. Cool post, Jamund. I got inspired that I made a whole phonegap plugin. See below. Ciao.

    http://bit.ly/Na5iAB

    ReplyDelete
  7. thanks men - this was a great help.
    danny

    ReplyDelete
  8. What does the $_POST['img'] string contain?

    ReplyDelete
  9. I'm trying to do this exact task but client-side (in an Android app, in case they are offline). I have the Base64 encoded PNG in a JSONArray in my Java code, but haven't figured out how to turn that into an actual .PNG file to save on the user's phone/tablet. Any suggestions?

    ReplyDelete
  10. @Erin, not exactly what you're looking for, but you might want to check this out: http://thomasjbradley.ca/lab/signature-pad/

    @Einar, it would contain the base64 encoding of the PNG image: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA6IAAAEOC.................and on and on......."

    @Jamund! Thanks!

    ReplyDelete
  11. Thank you man, that's incredibly simple and neat!

    ReplyDelete
  12. This just saved me so much time. Thanks for putting this together. The logic you use is easy to understand as well, so +1 for making it readable!

    ReplyDelete
  13. Thank you so much sir, you helped a lot !

    However, this code didn't work the first time I runned it. I had to change the permission on my folder, so that the function file_put_contents could work.

    Have a great day

    ReplyDelete
    Replies
    1. Hi Laila,

      I am having the same problem. Can you please explain more as to what needs to be done?

      Because I am storing the file_put_contents in a variable $savedsignature which then I am trying to save in my database.

      However, the saved file is 0 bytes.

      Delete
  14. Thanks!
    missing this line almost made me crazy:
    $img = str_replace(' ', '+', $img);

    ReplyDelete
  15. Thank you so much !
    I have been looking for something like this for days and couldn't figure out why my code wasn't working.

    ReplyDelete
  16. Thank a lot sir. It helped me a lot.

    ReplyDelete
  17. Nice post, thanks so much, this helpul for me!

    ReplyDelete
  18. This comment has been removed by the author.

    ReplyDelete
  19. SO easy! Thank you...I've been looking everywhere for this.

    ReplyDelete
  20. Works a charm! Thank you for posting!!

    ReplyDelete
  21. my image create doesn't open :(

    ReplyDelete
    Replies
    1. ready !! ... thank you :) , i had syntax error

      Delete
  22. This comment has been removed by a blog administrator.

    ReplyDelete
  23. Your argument is excellent!! Unique points in the same, here one more website I like joomla development company.

    ReplyDelete
  24. This comment has been removed by a blog administrator.

    ReplyDelete
  25. brilliant bro!!!nice work..thanks a lot for help me out.

    ReplyDelete
  26. how can i decode multiple base64 images and upload into a folder?

    ReplyDelete
  27. Thank you !...
    this helped me a lot :-)

    ReplyDelete
  28. this is not working for me. I get a blank .png file. I try to save image which produce by canvas .any ideas??

    ReplyDelete
  29. This is what I was looking for. Thanks !

    ReplyDelete
  30. thanks , I spent several hours trying to solve the problem of file data transfer via AJAX

    ReplyDelete
  31. I solved my problem with this code..

    Thanks

    ReplyDelete
  32. Hi,

    When I use this code, I have get an empty/blank .png file...
    What is the possible issue....
    Please help....
    I am struggling with it for five days.....This made me mad...

    Thank you...

    ReplyDelete
  33. Thank you so much for sharing.
    It is working well for me.

    Have a nice day
    :)

    ReplyDelete
  34. Works for me, Thanks.

    function canvas_to_image($img , $file){
    $img = str_replace('data:image/png;base64,', '', $img);
    $img = str_replace(' ', '+', $img);
    $data = base64_decode($img);
    return (file_put_contents($file, $data))?$file:"";
    }

    ReplyDelete
  35. This comment has been removed by the author.

    ReplyDelete
  36. very nice article
    online tool for image decoding
    http://freeonlinetools24.com/base64-image

    ReplyDelete
  37. Are you looking for high quality canvas prints to decorate your wall space? We have an exclusive collection of readymade canvas prints, You will find our canvas prints vibrant and stunningly beautiful for your homes and offices
    Photo Mugs
    Photo Canvas
    Photo To Canvas
    Canvas Prints
    Personalized Photo Mugs

    ReplyDelete
  38. This comment has been removed by a blog administrator.

    ReplyDelete
  39. \\\\\\\\\\\\\\\\\o///////////////// Brazil !!!! I had two days of depression for lack of that knowledge! Thank you

    ReplyDelete
  40. really helpful thank you for awesome support.

    ReplyDelete
  41. I really like this example, you should also do give SuperSignature a try.
    It is a html5 signature pad that works on website and mobile browsers.
    Supports major devices, it is actively developed and backed with strong support :)

    ReplyDelete
  42. Hello,
    Please help me , i have already spend 2 hours but not work for me . below is my code
    $base64_string_img = "data:image/png;base64,iVBORw.........";
    $data = str_replace('data:image/png;base64,', '', $data);
    $data = str_replace(' ', '+', $data);
    $filename_path = md5(time()).".jpg";
    $decoded=base64_decode($data);
    file_put_contents("/var/www/html/".$filename_path,$decoded);


    If any one has demo then please send me on below email address: nidhisanghavi19@gmail.com


    Thanks
    Hardik Patel

    ReplyDelete
  43. Hello,this not work for me and i have already spend 3 days. The image doesn't save in my database. I have check the path and i can write intp the path. After i assign image name in the path, the path cannot work. below is my code

    $img = $_POST['img'];
    $img = str_replace('data:image/jpg;base64,', '', $img);
    $img = str_replace(' ', '+', $img);
    $data = base64_decode($img);
    $img_name = uniqid();
    $file_name = $img_name . '.jpg';
    $file_path = realpath("../media/rewardreceipt/");
    $file_path = $file_path . $file_name ;

    /*$success = file_put_contents($file_name, $data);
    $arr = array('result' =>$file);
    echo json_encode($arr);
    print $success ? $file : 'Unable to save the file.';*/

    if(file_put_contents($file_name, $data)) {
    $arr = array('result' =>$file_name);
    echo json_encode($arr);
    } else{
    $arr = array('result' =>'false');
    echo json_encode($arr);
    }


    If any one has guidelines then please send me on below email address: cmwoo@mfe.my

    Thankz in advances.

    ReplyDelete
  44. hey thx alottt it worked for me tq sooooo much

    ReplyDelete
  45. how to add multiple images using this code...?

    ReplyDelete
  46. hello plz help me, this is not working for me. I can not show image in folder .

    ReplyDelete
  47. Thank You So Much... Really Help Full

    ReplyDelete
  48. Nice blog. very much impressed and thanks for sharing
    Printing Malaysia

    ReplyDelete
  49. Nice blog and absolutely outstanding. You can do something much better but i still say this perfect.Keep trying for the best. Hire Sencha Touch Developer

    ReplyDelete
  50. This comment has been removed by the author.

    ReplyDelete
  51. Our online tool allows you to convert PDF documents to JPG images for free. No downloads required.

    If you want more information to click here Convert pdf to png

    ReplyDelete
  52. I have read this article it is really helpful for getting amazing tips on related topic. You have described everything in a professional way.

    marketing companies buffalo ny are available but Crysal Tech Solution provides professional digital marketing service for growing your business.

    ReplyDelete
  53. your blog is awesome. post is very useful and beneficial for us. thanks for you sharing this type post with us.
    PHP training in Chandigarh

    ReplyDelete
  54. very nice..post.
    https://shayarihindishayari.com/

    ReplyDelete
  55. nice code bro article are awesome follow my blog for php www.gajabwap.blogspot.in

    ReplyDelete
  56. I love this post.

    โปรโมชั่นGclub ของทางทีมงานตอนนี้แจกฟรีโบนัส 50%
    เพียงแค่คุณสมัคร Gclub กับทางทีมงานของเราเพียงเท่านั้น
    ร่วมมาเป็นส่วนหนึ่งกับเว็บไซต์คาสิโนออนไลน์ของเราได้เลยค่ะ
    สมัครสมาชิกที่นี่ >>> Gclub online

    ReplyDelete
  57. Very cool!

    เว็บไซต์คาสิโนออนไลน์ที่ได้คุณภาพอับดับ 1 ของประเทศ
    เป็นเว็บไซต์การพนันออนไลน์ที่มีคนมา สมัคร Gclub Royal1688
    และยังมีเกมส์สล็อตออนไลน์ 1688 slot อีกมากมายให้คุณได้ลอง
    สมัครสมาชิกที่นี่ >>> Gclub Royal1688

    ReplyDelete
  58. This is a really helpful post, very informative there is no doubt about it. If you want to download MS Office and need help, please call us at +1-800-651-5054 Microsoft office support phone number. Our technicians are there to help you with your problems, Not only do we help you set up, we ensure our work with premium support. Call us now and get the best service.

    microsoft technical support phone number

    office.com/setup

    office.com/myaccount

    office 365 setup install

    ReplyDelete
  59. This is a wonderful and quite informative blog. Thanks for sharing useful information and also visit my website about Information Technology. God willing it will be useful too.

    seo services in Ghaziabad

    website development company in Ghaziabad

    digital marketing company in Noida

    website designing company in Noida

    mobile app development company in Ghaziabad

    seo services company in Noida

    ReplyDelete
  60. Weird, this is not working for me. I get a blank .png file.

    ReplyDelete
  61. HP Printer Support Number1-855-499-1999 can also help you with opening times and other details of your local store. Many people prefer to go into a store before buying an expensive item so that they can have a demonstration of the product. If you are buying something for portability you will want to pick it up and hold it to make sure it is right for what you need.
    HP Printer Support Phone Number

    ReplyDelete