24

i have already created my data (template-containing image,text,label etc) inside div now i want to convert it into image format. is there any technique to convert a specific div content into images without using canvas.anybody plz help me ! i want to convert entire "mydiv" content into image and save that image into my image directory, when i click on save ?

<html>
  <header>
  </header>
  <body>
    <label> Template Design</label>
    <div id="mydiv">
      <label> Good Morning</label>
      <img src="mug.png" id="img1" height="100" width="100"  />
    </div>
    <input name="save" type="button" value="SAVE" />
  </body>
</html>
João Pimentel Ferreira
  • 14,289
  • 10
  • 80
  • 109
luckyamit
  • 719
  • 2
  • 7
  • 19

2 Answers2

31

UPDATE (March 2018): Hello people of the future! This answer still gets a lot of traffic and I noticed that the old JSFiddle I'd put together was broken so it's been updated. New JSFiddle showing this technique is here: https://jsfiddle.net/Sq7hg/1913.

--

You might want to look into a Flash-based solution if you can't use <canvas> (though unless this specifically needs to work in old versions of IE I'm not sure why you can't).

http://flashcanvas.net/ is an emulation of <canvas> using Flash that might get you where you need to go. The documentation says that it supports toDataURL() so that might work for you.

Can you provide more insight into what your restrictions around <canvas> are and what you've attempted to try already?

//EDIT

According to your comment below you might be able to use <canvas>, in which case you can try using http://html2canvas.hertzen.com – it's a JavaScript solution that basically re-writes the DOM of a specified part of your code to a <canvas> and then allows you to interact with it however you want, including turning it into image data via toDataURL().

I've not used it before, but your JavaScript code would look something like this:

html2canvas([document.getElementById('mydiv')], {
    onrendered: function(canvas) {
       var data = canvas.toDataURL('image/png');
       // AJAX call to send `data` to a PHP file that creates an image from the dataURI string and saves it to a directory on the server
    }
});

I've knocked together a quick jsfiddle of this in action here: https://jsfiddle.net/Sq7hg/1913/ (note: updated link as per above)

This jsfiddle shows how to use the toDataURL() method to convert the canvas to an image and append it to the document. Saving the generated image to a server is an infinitely more complex task as it will require an AJAX call or somesuch to send the image data to a PHP script that converts the generated data: URL to an actual image and then saves it to a directory that you have permission to write to. If that's what you need to do, rather than going into that here I'd recommend starting with this Stack Overflow question: How to save an HTML5 Canvas as an image on a server?

Scott
  • 2,753
  • 1
  • 24
  • 31
  • Thanks Scottie but i have created my data (template-containing images text etc) inside div now i want to convert it into image format. is there any technique to convert a specific div content into images, or first convert it into canvas and then into image. if you have code for it then plz write here ? – luckyamit Aug 31 '13 at 06:31
  • Updated my answer above to include a ``-based solution. – Scott Aug 31 '13 at 06:35
  • yup there is a solution at http://html2canvas.hertzen.com/ but i unable to getting a clear code from there as i want its confusing for me could you provide me a filter code from there – luckyamit Aug 31 '13 at 06:40
  • Thank you so much can you provide me canvas to image conversion now ,how can i convert this output canvas into image format ? – luckyamit Aug 31 '13 at 11:51
  • 1
    Answer updated again with some more information on toDataURL(). – Scott Aug 31 '13 at 14:04
  • you are great ! This works perfectly...must be the simplest solution.I really appreciate your help. – luckyamit Sep 02 '13 at 05:48
  • Can we run this same process in an XHTML strict page and get the same results? – klewis Sep 10 '14 at 14:42
  • @blackhawk – I don't see why not. http://jsfiddle.net/Sq7hg/607/ is set up using the XHTML 1.0 Strict DTD (under "Fiddle Options" in the left-hand sidebar menu) and it all seems to work as expected. Haven't tried outside of jsfiddle, though. Give it a whirl and see what happens. – Scott Sep 10 '14 at 15:48
  • @Scottie : in my division, there is an image and it's url from some other website. So If I convert them to image, all other data will come. But this image will not come. Would you please suggest any solution? – manoos Jul 19 '16 at 06:33
  • @manoos the short answer is "you can't." The long answer is "you can't unless specific steps are taken, one which someone else needs to do." `` considers cross-domain images as "tainted" and generally won't act on them at all. This is a security consideration. The website you're pulling the image from needs to allow Cross Origin Resource Sharing which, if it's not your website, is probably not going to happen. You also need to set the crossOrigin attribute in your own JS code when you import the image – see https://blog.codepen.io/2013/10/08/cross-domain-images-tainted-canvas for how. – Scott Jul 22 '16 at 11:42
17

This works perfectly...must be the simplest solution .

//html

<div id="mydiv" style="background-image:url(Koala.jpg) ;background-size: 100%;
background-size :200px 200px;
background-repeat: no-repeat;">
<p>text!</p>
<img src="mug.png" height="100" width="100"/></div>
<div id="canvas">
<p>Canvas:</p>
</div>

 <div style="width:200px; float:left" id="image">
 <p style="float:left">Image: </p>
 </div>
 <div style="float:left;margin-top: 120px;" class="return-data">
 </div>
 <script src="http://html2canvas.hertzen.com/build/html2canvas.js"></script>
 <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

//Style

#mydiv {
background-color: lightblue;
width: 200px;
height: 200px
}

//Script

  <script language="javascript">
    html2canvas([document.getElementById('mydiv')], {
    onrendered: function (canvas) {
    document.getElementById('canvas').appendChild(canvas);
    var data = canvas.toDataURL('image/png');
     //display 64bit imag
     var image = new Image();
    image.src = data;
    document.getElementById('image').appendChild(image);
    // AJAX call to send `data` to a PHP file that creates an PNG image from the dataURI string and saves it to a directory on the server

    var file= dataURLtoBlob(data);

// Create new form data
var fd = new FormData();
fd.append("imageNameHere", file);

$.ajax({
   url: "uploadFile.php",
   type: "POST",
   data: fd,
   processData: false,
   contentType: false,
}).done(function(respond){

    $(".return-data").html("Uploaded Canvas image link: <a href="+respond+">"+respond+"</a>").hide().fadeIn("fast");
    });

  }
});

function dataURLtoBlob(dataURL) {
// Decode the dataURL    
var binary = atob(dataURL.split(',')[1]);
// Create 8-bit unsigned array
var array = [];
for(var i = 0; i < binary.length; i++) {
    array.push(binary.charCodeAt(i));
 }
// Return our Blob object
return new Blob([new Uint8Array(array)], {type: 'image/png'});
 }

</script>

here is a sample demo

luckyamit
  • 719
  • 2
  • 7
  • 19
  • can you explain a little bit more please? I tried opening your sample demo link but I still don't understand because nothing's happening there.. – dapidmini Nov 29 '18 at 03:38
  • 1
    you can check my fiddle link : http://jsfiddle.net/Sq7hg/3120/ ,i have updated link in my answer too @dapidmini – luckyamit Nov 30 '18 at 14:59