【发布时间】:2015-10-22 12:20:16
【问题描述】:
我有这个代码:
[WebMethod]
public static string SaveImg(string imgdata)
{
string Path = "UploadedImages/";
string folderPath = HttpContext.Current.Server.MapPath(Path);
Guid gid=Guid.NewGuid();
string fileNameWitPath = folderPath + "img_" +gid + ".png";
FileStream fs = new FileStream(fileNameWitPath, FileMode.Create);
BinaryWriter bw = new BinaryWriter(fs);
byte[] data = Convert.FromBase64String(imgdata);
bw.Write(data);
bw.Close();
bw.Dispose();
return "/" + Path +"img_"+ gid + ".png";
}
witch 是一个函数,它接受一个 base64 字符串并将其转换为二进制并将图像保存到服务器
base64 数据取自在上传时加载图像的画布 图像看起来像这样:
除非您在新选项卡中打开示例图像,否则我的问题不会显示,您可以看到它周围包含白色边框,因为当它被上传到画布时它不适合画布大小
我的问题是如何在将图像保存到服务器(bw.write(data))之前从图像中删除那些白色边框(从字节数组中删除0 byte)
我试过这段代码,但它对我不起作用:
int i = data.Length - 1;
while(data[i] == 0)
--i;
// now data[i] is the last non-zero byte
byte[] bar = new byte[i+1];
Array.Copy(data, bar, i+1);
bw.Write(data);
这是客户端代码:
var canvas = $("#imageCanvas")[0];
var ctx = canvas.getContext("2d");
var uploadInput = $('#UploadFile');
var width = 382;
var height = 295;
uploadInput.on('change', function (e) {
RemoveDisabledClass();
handleImage(e);
});
function handleImage(e) {
var reader = new FileReader();
reader.onload = function (event) {
var img = new Image();
img.onload = function () {
// var canvas = ctx.canvas;
var hRatio = canvas.width / img.width;
var vRatio = canvas.height / img.height;
var ratio = Math.min(hRatio, vRatio);
var centerShift_x = (canvas.width - img.width * ratio) / 2;
var centerShift_y = (canvas.height - img.height * ratio) / 2;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0, img.width, img.height,
centerShift_x, centerShift_y, img.width * ratio, img.height * ratio);
}
img.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
}
$("#btn_save").click(function () {
if ($("#btn_save").hasClass("disabled")) return;
$("#dv_Error").css("display", "none");
var image = document.getElementById("imageCanvas").toDataURL();
image = image.replace('data:image/png;base64,', '');
$.ajax({
type: 'POST',
url: 'Default.aspx/SaveImg',
data: '{ "imgdata" : "' + image + '" }',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data) {
window.location.href = data.d;
},
error: function (request, status, error) {
$("#dv_Error").css("display", "block");
}
}); //ENd Ajax
}); //End Click event
【问题讨论】:
-
我认为尝试修改
byte[]以更改图像会使事情变得比他们需要的要困难得多。将图像放在画布上然后将其导出为 base64 字符串的代码在哪里?更改该代码,使其仅保存包含实际图像数据的图像,而不是超大画布。 -
请检查我的编辑
标签: javascript c# canvas