我使用canvas和filereader api来执行客户端大小的图像调整大小,然后从canvas获取结果dataurl,使用隐藏的表单值上传到我的.Net后端。
感谢这个网站和我在这里找到的百万像素库:[megapix library] [1]
[1]:https://github.com/stomita/ios-imagefile-megapixel我能够在97%的时间内执行调整大小的客户端。
然而,在大约3%的情况下,进程在代码中失败,并且canvas对象永远不会获得调整大小的图像。当我读取空白画布时,我得到数据以创建黑色图像。 我试图找出为什么调整大小不起作用的原因。
代码在这里:
var fileInput = document.getElementById('fileInput');
fileInput.onchange = function () {
var fileName = fileInput.value;
if (fileName != '')
{
//Validate it's an image
//valid image types: jpeg,jpg,png
var fileExtension = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase();
if (fileExtension == 'jpg' || fileExtension == 'jpeg' || fileExtension == 'png')
{
var divUpload = document.getElementById('divUpload');
//divUpload.style.display = 'inline';
var file = fileInput.files[0];
var mpImg = new MegaPixImage(file);
var orient = 1;
var resCanvas1 = document.getElementById('canvas');
var resCanvasPreview = document.getElementById('canvasPreview');
fr = new FileReader; // to read file contents
fr.onloadend = function () {
var exif = EXIF.readFromBinaryFile(new BinaryFile(this.result));
if(exif)
orient = exif.Orientation;
mpImg.render(resCanvas1, { maxWidth: 600, maxHeight: 600, orientation: orient });
mpImg.render(resCanvasPreview, { maxWidth: 300, maxHeight: 300, orientation: orient });
divUpload.style.display = 'inline';
};
if (navigator.appName == 'Microsoft Internet Explorer') {
//ie - apparently this isn't a way to get this to work with IE
mpImg.render(resCanvas1, { maxWidth: 600, maxHeight: 600, orientation: orient });
mpImg.render(resCanvasPreview, { maxWidth: 300, maxHeight: 300, orientation: orient });
divUpload.style.display = 'inline';
}
else
{
fr.readAsBinaryString(file); // read the file
}
/*
var blobURL = window.URL.createObjectURL(mpImg.blob); // and get it's URL
var image = new Image();
image.src = blobURL;
image.onload = function () {
resize(image, 'canvas', 600, 600,orient);
resize(image, 'canvasPreview', 300, 300,orient);
}
*/
}
else
{
alert('Please pick a valid image file. Only jpeg and png file types supported.');
}
}