上传之前HTML5预先调整图像大小 [英] HTML5 Pre-resize images before uploading
问题描述
是否可以预先设定大小图像使用新的本地存储(或其他),以便不知道如何调整图像大小的用户可以将他们的10MB图像拖入我的网站,然后使用新的本地存储重新调整大小,然后以较小的尺寸上传它。
我完全知道你可以用Flash,Java applets,active X来做到这一点...问题是如果你可以用Javascript + Html5做。
期待这一回应。
Ta现在。
这篇Mozilla Hacks博客文章将引导您了解大部分流程。以下是博客文章中汇编的源代码:
//来自输入元素
var filesToUpload = input .files;
var file = filesToUpload [0];
var img = document.createElement(img);
var reader = new FileReader();
reader.onload = function(e){img.src = e.target.result}
reader.readAsDataURL(file);
var ctx = canvas.getContext(2d);
ctx.drawImage(img,0,0);
var MAX_WIDTH = 800;
var MAX_HEIGHT = 600;
var width = img.width;
var height = img.height;
if(width> height){
if(width> MAX_WIDTH){
height * = MAX_WIDTH / width;
width = MAX_WIDTH;
}
} else {
if(height> MAX_HEIGHT){
width * = MAX_HEIGHT / height;
height = MAX_HEIGHT;
}
}
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext(2d);
ctx.drawImage(img,0,0,width,height);
var dataurl = canvas.toDataURL(image / png);
//通过AJAX
将数据发送到服务器
Here's a noodle scratcher.
Bearing in mind we have HTML5 local storage and xhr v2 and what not. I was wondering if anyone could find a working example or even just give me a yes or no for this question:
Is it possible to Pre-size an image using the new local storage (or whatever), so that a user who does not have a clue about resizing an image can drag their 10mb image into my website, it resize it using the new localstorage and THEN upload it at the smaller size.
I know full well you can do it with Flash, Java applets, active X... The question is if you can do with Javascript + Html5.
Looking forward to the response on this one.
Ta for now.
Yes, use the File API, then you can process the images with the canvas element.
This Mozilla Hacks blog post walks you through most of the process. For reference here's the assembled source code from the blog post:
// from an input element
var filesToUpload = input.files;
var file = filesToUpload[0];
var img = document.createElement("img");
var reader = new FileReader();
reader.onload = function(e) {img.src = e.target.result}
reader.readAsDataURL(file);
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var MAX_WIDTH = 800;
var MAX_HEIGHT = 600;
var width = img.width;
var height = img.height;
if (width > height) {
if (width > MAX_WIDTH) {
height *= MAX_WIDTH / width;
width = MAX_WIDTH;
}
} else {
if (height > MAX_HEIGHT) {
width *= MAX_HEIGHT / height;
height = MAX_HEIGHT;
}
}
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, width, height);
var dataurl = canvas.toDataURL("image/png");
//Post dataurl to the server with AJAX
这篇关于上传之前HTML5预先调整图像大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!