[英]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.