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:

145 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. thanks men - this was a great help.
    danny

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

    ReplyDelete
  8. 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
  9. @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
  10. Thank you man, that's incredibly simple and neat!

    ReplyDelete
  11. 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
  12. 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
  13. Thanks!
    missing this line almost made me crazy:
    $img = str_replace(' ', '+', $img);

    ReplyDelete
  14. 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
  15. Thank a lot sir. It helped me a lot.

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

    ReplyDelete
  17. Thanks a lot. Helpful post.. :)

    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. This comment has been removed by a blog administrator.

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

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

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

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

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

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

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

    Thanks

    ReplyDelete
  31. 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
  32. Thank you so much for sharing.
    It is working well for me.

    Have a nice day
    :)

    ReplyDelete
  33. 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
  34. This comment has been removed by the author.

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

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

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

    ReplyDelete
  38. really helpful thank you for awesome support.

    ReplyDelete
  39. 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
  40. 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
  41. 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
  42. hey thx alottt it worked for me tq sooooo much

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

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

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

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

    ReplyDelete
  47. 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
  48. 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
  49. 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
  50. Weird, this is not working for me. I get a blank .png file.

    ReplyDelete
  51. 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
  52. Epson Printer Support Phone Number
    has turned into the need of each individual utilizing innovation related howdy tech items. PC and printer clients additionally experience numerous issues at the season of utilization which propel them to secure the client support number(+1-888-326-0222) and get their help to determine the issues. As the innovation of a printer and comparable gadgets are not easy to use for some clients, subsequently, Epson Printer Support Phone Number is accessible online to help end-clients to tackle tech related issues.

    ReplyDelete
  53. Thanks for the post and coding assistance. This will help a lot of people that need it. ezcourtpay

    ReplyDelete
  54. If your purchase of Office came with a product key, you enter your product key on one of the websites listed below for your version of Office. After you enter your key, you can download and install Office, or you can renew your Office 365 subscription.office setup is the product arrangement record with this arrangement document you can introduce on your PC and a portion of the bolstered gadget to utilize www.office.com/setup.
    www.office.com/setup | WWW.WEBROOT.COM/SAFE

    ReplyDelete

  55. Office setup is the product arrangement record with this arrangement document you can introduce on your PC and a portion of the bolstered gadget to utilize

    www.office.com/setup.Sign in to enter office setup product key. Know how to benefit, download, install, set in movement, uninstall and reinstall MS office setup and Get Started by now Office setup.if you have any query related to officecom then contact us.
    www.office.com/setup
    www.webroot.com/safe

    ReplyDelete
  56. McAfee Software is known to be user-friendly and customizable.If you are looking mcafee product key activation for a convenient way to protect your device , McAfee security software. mcafee activate product key is the best answer for you.If you need any you can call toll free number +1-888-845-6052.

    ReplyDelete
  57. Are you looking for Aol mail login – find here step-by-step procedure to setup your AOL Mail Login and create a new Aol mail account. www.mail.aol.com If you forget your Aol mail password or find any other issue in AOL login/sign in or sign up/register, call AOL tech support number now.

    ReplyDelete
  58. Actually, blocked Facebook account can be got back in many ways but here you will know how easily recover Facebook account in no time. Through this process, every blocked Facebook users are able to recover their temporarily blocked account. So, keep reading at the end.

    ReplyDelete


  59. شركة من الشركات الرائدة في الخدمات المنزلية شركة المستقبل لخدمات النظافة يتميز بوجود عمالة متميزة وعلى أعلى دقة ونتميز ايضا لوجود الخبرات والعمل بأعلي المواد الخام أسعارنا لاتقبل المنافسة تواصل معنا الأن عبر الروابط التالية وسوف نلبي طلباتكم في اسرع وقت ممكن

    شركةجلى بلاط بالرياض
    شركة تنظيف منازل بالرياض
    شركة تنظيف بالبخار بالرياض
    شركة تنظيف شقق بالرياض
    شركة تنظيف وصيانة مكيفات بالرياض
    شركة مكافحة الصراصير بالرياض
    شركة مكافحة البق بالرياض
    شركة-مكافحة-حشرات-بالرياض
    شركة نظيف خزانات بالرياض
    شركة تخزين اثاث وعفش بالرياض

    ReplyDelete
  60. من المعروف ان نجاح اي شركة او مؤسسةت:0500466401 مبني على عمالها لذا فنحن في مؤسسة المستقبل و في شركة ترميم وصيانة منازل بالرياض نملك مجموعة ضخمه من العمال في كافة مجالات الصيانة
    و الترميم لتقديم كافة الخدمات التي يحتاجها المنزل فنحن نملك خبراء في اعمال الكهرباء و في اعمال السباكة و اعمال تركيب البلاط و البروسلين
    و الرخام و اعمال تركيب الباركييه بالاضافة الى وجود مجموعة من المتخصصين في اعمال صيانة الخزان و المسابح كل هذه الخدمات و اكثر متوفر من خلال شركة ترميم و صيانة منازل بالرياض .
    خدمات منزلية بأرخص الأسعار عالية الدقة قمة التميز في إختيار ماكينات التنظيف كافة عوامل النجاح تتوفر في شركة المستقبل لخدمات النظافة يمكنكم التتبع والتواصل معنا عبر الروابط التالية :
    شركة مقاولات كهرباء بالرياض
    شركة مقاولات سباكه بالرياض
    شركة ترميم وصيانه منازل بالرياض
    شركة كشف مباني بالرياض
    خدمات مكافحة الحشرات
    شركة رش مبيدات بالرياض
    شركة-مكافحة النمل الابيض الرياض

    ReplyDelete
  61. Online Casino Spielautomaten | Bestes Online Casino: Entdecken Sie Neue Online Casinos. Zum Casino Online >> Online Casino

    ReplyDelete
  62. I really happy found this website eventually. Really informative and inoperative, Thanks for the post and effort! Please keep sharing more such blog.

    www.norton.com/setup

    www.spectrum.net/login

    kaspersky activation

    aolmail.com

    mcafee.com/activate

    ReplyDelete
  63. Great way to express the knowledgeable content. Hoping to continue this effort in future. Thanks for sharing.
    mywakehealth
    www.mymilestoneCard.com
    securitasepay
    payonlineticket
    myinsuranceinfo
    mykohlscharge

    ReplyDelete
  64. I really happy found this website eventually. Really informative and inoperative, Thanks for the post and effort! Please keep sharing more such blog.

    www.norton.com/setup

    www.spectrum.net/login

    aolmail.com

    mcafee.com/activate

    ester and christmas ornaments

    ReplyDelete
  65. Thanks for sharing this with us.
    Are you looking to activating Microsoft office versions? if you have any kind of error that can contact our highly experienced engineer can resolve your problems. or visit: www.office.com/setup | www.office.com/myaccount | www.office.com/office login

    ReplyDelete
  66. I have been looking for something like this for days and couldn't figure out why my code wasn't working.
    best cat litter boxes for large cats

    ReplyDelete
  67. Really informative and inoperative, I really happy found this website eventually. Thanks for the post
    Apply With Coupon Code
    Fifth Third Bank
    Activation bank account

    ReplyDelete
  68. Are you looking for block emails on AOL have any issues can contact to our technical expert engineer?
    Are you looking for block emails on AOL have any issues can contact to our technical expert engineer?

    ReplyDelete
  69. Nice Digital marketing service is looking for such information all over the internet & finally my search end up here. thanks for sharing this wonderful article.

    ReplyDelete
  70. I am very thankful that I found such good content over the internet. Thanks for sharing such a well-written article. AOL Customer Care Phone Number and connect with the team of experts if you are facing any AOL and Gmail issues.

    ReplyDelete
  71. Hello, my name is Marvellous. I do manage a website Tecteem, Wwhen I step into your website, I really find it so wonderful and nice. I will wish to make mine just like yours to make mine more prefect. All the same, thank you for the information that you have shared here right for everyone of us.

    ReplyDelete
  72. Thankyou For infrormative informtion, keep it up and write more informative blog and if face any kind of issue regarding to QuickBooks Payroll Support dont go anywhere just call at +1-855-533-6333

    ReplyDelete
  73. This is an excellent post I seen thanks to share it. It is really what I wanted to see hope in future you will continue for sharing such a excellent post. Ontario Security License

    ReplyDelete
  74. FLEX PRINTING services provides jainand digital point at reasonable prices i like so very much.

    ReplyDelete
  75. Na našich stránkách najdete nejatraktivnější bonusy a propagace, stejně jako hry od nejlepších poskytovatelů. Čekáme na vás!
    https://top10casino.cz/nova-online-kasina/nejlepsi-uvitaci-bonusy/
    https://online-ruleta-czech.cz/

    ReplyDelete

  76. Fubo Tv is a popular app and is advancing its features and version to get compatible with different types of TV’s. At first, it was compatible with the basic TV types. Your post is very helpful and information is reliable. I am satisfied with your post. Thank you so much for sharing this wonderful post. Thanks for sharing! Know about fubo.tv/connect.

    ReplyDelete
  77. Thanks for Sharing This Article.It is very so much valuable content
    The best services of Website Designing Company in Noida & NCR. One of the best website developer companies with a affordable price. For more details call: 9015664619 or visit our website_ https://www.evermolpro.com/

    ReplyDelete
  78. Welcome to the party of my life here you will learn everything about me.
    토토사이트

    ReplyDelete
  79. it's really cool blog. Linking is very useful thing. You have really helped.
    토토사이트

    ReplyDelete
  80. Very awesome!!! When I seek for this I found this website at the top of all blogs in search engine.
    Oregon Business Registry

    ReplyDelete
  81. I am genuinely thankful to the holder of this web page who has shared this wonderful paragraph at at this place. 토토사이트

    ReplyDelete
  82. If you don’t mind proceed with this extraordinary work and I anticipate a greater amount of your magnificent blog entries. 메이저사이트

    ReplyDelete
  83. Cool stuff you have and you keep overhaul every one of us. Marketing tools

    ReplyDelete
  84. I'm happy to see the considerable subtle element here! biz-alchemy

    ReplyDelete
  85. office.com/setup- To get started with your Microsoft Office Installation you need valid product key code & visit www.Office.com/Setup and we can also help you with your entire process to setup office at office.com/setup.

    ReplyDelete
  86. This is an awesome motivating article. I am practically satisfied with your great work. You put truly extremely supportive data. Keep it up. Continue blogging. Hoping to perusing your next post.
    먹튀검증업체

    ReplyDelete
  87. Great tips and very easy to understand. This will definitely be very useful for me when I get a chance to start my blog. 먹튀검증업체

    ReplyDelete
  88. your web is very nice. Hello friends please check out of the best SATTA KING game PLAY BAZZAR .

    ReplyDelete
  89. Garmin is a focused GPS device accessing a device that needs to get the map updates on time. Get Garmin GPS Update in a easy access by using Garmin express software for Mac or Windows operating systems. Learn from here how you can easily get updated GPS Garmin device and connect it with your Mac or iPhone.

    ReplyDelete
  90. The post "Save a Base64 Encoded Canvas image to a png file using PHP" is very useful and important as it provide the information regarding how to Encoded Canvas image to a png file by using PHP.
    office.com/setup

    ReplyDelete
  91. You guys have shared an amazing and a wonderful post and the blog is pretty helpful and informative as well.
    office.com/setup

    ReplyDelete
  92. https://j-query.blogspot.com/2011/02/save-base64-encoded-canvas-image-to-png.html

    ReplyDelete
  93. Very useful post..! Save a Base64 Encoded Canvas image to a png file using PHP

    Will try in future..
    Top 5 Important Tips To Know Before Hiring An iOS Developer
    hire ios app developers

    ReplyDelete
  94. Thank you for your post. This is excellent information. It is amazing and wonderful to visit your site.You have some quality information here that any reader would enjoy. I got useful information this article.Thanks for this Information.
    Share Market Tips | Stock Market Tips

    ReplyDelete
  95. Positive site, where did u come up with the information on this posting? I'm pleased I discovered it though, ill be checking back soon to find out what additional posts you include.mymathlab answers

    ReplyDelete
  96. I guess your website appears adorable. The successful points are given in this text.That is in reality very extraordinary recommendations are given in this article. ThanksSatta King

    ReplyDelete
  97. If you need any significant information, you can simply check out the nighthawk ax3000 review. However, you must know that it is capable of up to 2Gb/s of total wifi throughout, and of course, this dual-band wifi six routers supports OFDMA technology as it allows the router to transmit the data up to 16 devices simultaneously.

    ReplyDelete
  98. Amazing I truly love your blog.It is very unique and very helpful.Thank you very much for sharing it with us.
    https://www.inwizards.com/hire-.net-developers-india.php

    ReplyDelete
  99. [TIP] Wil jij in een betrouwbaar casino online legaal slots spelen? Tip: bezoek hier de beste casino aanbieders van Nederland.

    ReplyDelete
  100. Fubotv is an first-rate way to maintain that spirit alive in you. World’s only sports-focused live TV, that’s what Fubotv says on its authentic website, however, that announcement matches so properly due to the fact no one else can compete with Fubo in handing over the sports-heavy live TV streaming. Moreover, Fubo can be activated on various streaming devices. fubotv connect

    ReplyDelete
  101. You will also get a free cloud DVR to record and upload your favorite live TV shows. You can enjoy your awaited sports later, finishing your work. Explore more channels and shows with fubo.tv/connect by yourself without asking your cable or disk operator to provide those to you. Operating TV will become more comfortable by fubotv activate.
    free live sport and shows

    ReplyDelete
  102. The blog post provides a useful solution for saving base64-encoded canvas images to PNG format. The step-by-step guide is well-explained and includes sample code snippets for the reader to follow. This is a valuable resource for web developers who are looking to implement this functionality on their websites. Jpeg To Png Online

    ReplyDelete