简体   繁体   中英

Convert an img to file and back in Javascript

Imagine a web page has an img tag which needs to be uploaded. How do I convert this to a file object, so that I can send it over?

And on the other end, I have the hypothetical img, converted to file and sent to me. How do I convert this to a HTML tag?

I have an initial starting point for the latter part:

imageUrl = URL.createObjectURL(file);
image = document.createElement("img");
image.src = imageUrl;

If you alredy have your image loaded in html page, you can encode it to base64, then send it to your server by ajax call and save it

Javascript

function getBase64Image(img) {
  // Create an empty canvas element
  var canvas = document.createElement("canvas");
  canvas.width = img.width;
  canvas.height = img.height;

  // Copy the image contents to the canvas
  var ctx = canvas.getContext("2d");
  ctx.drawImage(img, 0, 0);

  // Get the data-URL formatted image
  // Firefox supports PNG and JPEG. You could check img.src to
  // guess the original format, but be aware the using "image/jpg"
  // will re-encode the image.
  var dataURL = canvas.toDataURL("image/png");

  return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}

$.ajax({
  type: "POST",
  url: "/yourPage.aspx/YourWebMethod",
  data: "{yourParameterName:'" + JSON.stringify(getBase64Image(yourAlreadyLoadedImage)) + "'}",
  contentType: "application/json; charset=utf-8",
  dataType: "json",
      async: false,
  success: function (data) {
    var result = data.d;
  },
  error: function () { alert('/yourPage.aspx/YourWebMethod'); }
});

Server side you can decode base64 image and save it, for example, in JPEG

C#

public void Base64ToImage(string coded)
{
  System.Drawing.Image finalImage;
  MemoryStream ms = new MemoryStream();
  byte[] imageBytes = Convert.FromBase64String(coded);
  using(var ms = new MemoryStream(imageBytes)) {
    finalImage = System.Drawing.Image.FromStream(ms);

  }

   finalImage.Save(yourFilePath, ImageFormat.Jpeg);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM