簡體   English   中英

將img轉換為文件並返回Javascript

[英]Convert an img to file and back in Javascript

想象一個網頁有一個img標簽,需要將其上傳。 如何將其轉換為文件對象,以便可以將其發送過來?

在另一端,我將假設的img轉換為文件並發送給我。 如何將其轉換為HTML標簽?

對於下一部分,我有一個初始起點:

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

如果您確實在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);

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM