5

I have

image = canvas.toDataURL("image/png", 1);

but this is returning

data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDA.......

but I need normal image like src="myimage.png"

how can I get it from canvas? i googled a lot, cannot seem to find what i need...

doniyor
  • 36,596
  • 57
  • 175
  • 260
  • If you want to convert the base64 string to a file, you have to use a server side language, such as php. If you want to search for it, you'll need Base64 or BLOB as keywords. – Stephan Vierkant Dec 22 '14 at 12:39
  • 2
    @Cerbrus: I don't think the duplicate you have is quite what the OP was looking for. Here we're posting the base64 code to the server in order to save it to a database. There, it's just figuring out how to download the image client-side. – Cᴏʀʏ Dec 22 '14 at 13:34

1 Answers1

6

The string that you're getting can be used as the source attribute for an image, you just have to create a new Image element to which you can assign it:

var image = new Image();
image.src = canvas.toDataURL("image/png", 1);
// append image to DOM

EDIT: Given the comments, you want to turn this into something that be stored in a database. You should POST the result of toDataURL to your server. Use your server-side technology's IO/image/graphics libraries to decode the base64-encoded part of the data string and write that out to a new file. You can now store that path in your database.

Alternative: just store that whole data string in your database. Then when you render your <img> tag you can simply dump it into the src attribute:

<img src="<< base-64 encoded data string>>" />
Cᴏʀʏ
  • 105,112
  • 20
  • 162
  • 194
  • this is returning ``data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDA.......`` and NOT imagefile, i want normal file – doniyor Dec 22 '14 at 12:35
  • Are you looking for how to write a file or how to show that image as an img element? – Shomz Dec 22 '14 at 12:36
  • That base64 string *is* an image file. Do you mean that you want to have your browser prompt you to download/save an image file? – Cᴏʀʏ Dec 22 '14 at 12:36
  • @Cory i want to get a file object from this, which i can save into db. is ``image`` in this case an image file? – doniyor Dec 22 '14 at 12:37
  • What server-side technology are you using? – Cᴏʀʏ Dec 22 '14 at 12:38
  • 2
    @doniyor: Do you _really_ want to store a binary image file in the database? (Hint: you don't). This Base64 string is what you'll want. – Cerbrus Dec 22 '14 at 12:38
  • @Cerbrus I _dont_ save binary file of course, i will save the path of file into db and file itself in some directory – doniyor Dec 22 '14 at 12:40
  • @Cory django in backend – doniyor Dec 22 '14 at 12:40
  • @Cory the problem with your latest advice is that facebook doesnot crawl inline images, this is the only reason why this whole messup i am doing. ;) – doniyor Dec 22 '14 at 12:53