使用 ajax / javascript 尝试类似的操作...它将使用作为 datauri 参数传递给控制器的 ajax 数据参数将 base64 字符串发布到控制器。
MyFunc 会将图像转换为 base64 并将其发布到操作。
function MyFunc() {
con.drawImage(v, 0, 0, canvasWidth, canvasHeight);
var = document.getElementById('imgprvw');
dataURL = c.toDataURL('image/png');
var raw_image_data = dataURL.replace(/^data\:image\/\w+\;base64\,/, '');
$.ajax({
url: '@PathHelper.FullyQualifiedApplicationPath(Request)' + 'MySaveController/MySaveAction',
type: 'POST', dataType: 'json',
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
data:
{
datauri: JSON.stringify(raw_image_data),
},
error: function (xhr) {
alert('Error: ' + xhr.statusText);
},
success: function (result) {
alert('Image Saved');
}
});
}
在控制器中... MySaveAction 会将 base64 转换为位图,然后保存。
public ActionResult MySaveAction(string datauri)
{
// Some stuff.
if (datauri.Length > 0)
{
Byte[] bitmapData = new Byte[datauri.Length];
bitmapData = Convert.FromBase64String(FixBase64ForImage(datauri));
string fileLocationImageName = "C:/MYIMAGE.JPG";
MemoryStream ms = new MemoryStream(bitmapData);
using (Bitmap bitImage = new Bitmap((Bitmap)Image.FromStream(ms)))
{
bitImage.Save(fileLocationImageName, System.Drawing.Imaging.ImageFormat.Jpeg);
output = fileLocationImageName;
}
}
return Json(output, JsonRequestBehavior.AllowGet);
}
Helper 方法...这将提供 ajax url 参数所需的请求的完整路径。
public static class PathHelper
{
public static string FullyQualifiedApplicationPath(HttpRequestBase httpRequestBase)
{
string appPath = string.Empty;
if (httpRequestBase != null)
{
//Formatting the fully qualified website url/name
appPath = string.Format("{0}://{1}{2}{3}",
httpRequestBase.Url.Scheme,
httpRequestBase.Url.Host,
httpRequestBase.Url.Port == 80 ? string.Empty : ":" + httpRequestBase.Url.Port,
httpRequestBase.ApplicationPath);
}
if (!appPath.EndsWith("/"))
{
appPath += "/";
}
return appPath;
}
}
最后,这是对 base64 字符串的修复...即删除使用 JSON.Stringify 转换 base64 时插入的废话。
public string FixBase64ForImage(string image)
{
System.Text.StringBuilder sbText = new System.Text.StringBuilder(image, image.Length);
sbText.Replace("\r\n", String.Empty);
sbText.Replace(" ", String.Empty);
sbText.Replace("\"", String.Empty);
return sbText.ToString();
}