var OneImgUpLoad = {
OneImageType: 0,
OneImageData: null,
AddImg: function (id) {
var MyFiles = $("#" + id).prop('files');
var MyFile = MyFiles[0];
//检验是否为图像文件
if (!(MyFile.type == 'image/jpeg' || MyFile.type == 'image/png')) {
AlphaMS.JSToolkit.Dialog.MessageBox("请上传jpeg或png格式的图片文件!");
return;
}
var imageUrl = OneImgUpLoad.getObjectURL(MyFile);
OneImgUpLoad.convertImgToBase64(imageUrl, function (base64Img) {
//图片数据
var image_base64 = base64Img.split(",")[1];
//图片数据
OneImgUpLoad.OneImageType = MyFile.type == 'image/jpeg' ? 1 : 2;
OneImgUpLoad.OneImageData = image_base64;
if (OneImgUpLoad.OneImageData != "") {
$("#PhotoResultDiv").css("display", "block");
$("#PhotoResult").attr("src", base64Img);
}
$("#" + id).html("");
});
event.preventDefault();
},
convertImgToBase64(url, callback, outputFormat) {
var canvas = document.createElement('CANVAS');
var ctx = canvas.getContext('2d');
var img = new Image;
img.crossOrigin = 'Anonymous';
img.onload = function () {
var width = img.width;
var height = img.height;
// 按比例压缩4倍
var rate = (width < height ? width / height : height / width) / 4;
canvas.width = width * rate;
canvas.height = height * rate;
ctx.drawImage(img, 0, 0, width, height, 0, 0, width * rate, height * rate);
var dataURL = canvas.toDataURL(outputFormat || 'image/png');
callback.call(this, dataURL);
canvas = null;
};
img.src = url;
},
getObjectURL(file) {
var url = null;
if (window.createObjectURL != undefined) { // basic
url = window.createObjectURL(file);
} else if (window.URL != undefined) { // mozilla(firefox)
url = window.URL.createObjectURL(file);
} else if (window.webkitURL != undefined) { // web_kit or chrome
url = window.webkitURL.createObjectURL(file);
}
return url;
}
}