Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CONVERT Image url to Base64

Using an Image File, I am getting the url of an image, that needs be to send to a webservice. From there the image has to be saved locally on my system.

The code I am using:

var imagepath = $("#imageid").val();// from this getting the path of the selected image  that var st = imagepath.replace(data:image/png or jpg; base64"/""); 

How to convert the image url to BASE64?

like image 864
im_chethi Avatar asked Mar 04 '14 12:03

im_chethi


People also ask

Can we convert image URL to Base64?

We can convert an image to a base64 URL by loading the image with the given URL into the canvas and then call toDataURL to convert it to base64.


1 Answers

HTML

<img id=imageid src=https://www.google.de/images/srpr/logo11w.png> 

JavaScript

function getBase64Image(img) {   var canvas = document.createElement("canvas");   canvas.width = img.width;   canvas.height = img.height;   var ctx = canvas.getContext("2d");   ctx.drawImage(img, 0, 0);   var dataURL = canvas.toDataURL("image/png");   return dataURL.replace(/^data:image\/(png|jpg);base64,/, ""); }  var base64 = getBase64Image(document.getElementById("imageid")); 

This method requires the canvas element, which is perfectly supported.

  • The MDN reference of HTMLCanvasElement.toDataURL().
  • And the official W3C documentation.
like image 124
ˈvɔlə Avatar answered Sep 21 '22 08:09

ˈvɔlə