将img转换为文件并返回Javascript

时间:2014-04-30 16:08:44

标签: javascript html5

想象一下,网页上有一个需要上传的 img 标签。如何将其转换为文件对象,以便我可以将其发送?

另一方面,我有假设的img,转换为文件并发送给我。如何将其转换为HTML标记?

我对后半部分有一个初始起点:

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

1 个答案:

答案 0 :(得分:5)

如果您已将图像加载到html页面中,则可以将其编码为base64,然后通过ajax调用将其发送到服务器并保存

<强>的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'); }
});

服务器端您可以解码base64图像并将其保存,例如,以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);

}