HTML5 上传前预先调整图像大小 [英] HTML5 Pre-resize images before uploading

查看:21
本文介绍了HTML5 上传前预先调整图像大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个刮面器.

请记住,我们有 HTML5 本地存储和 xhr v2,还有什么没有.我想知道是否有人可以找到一个有效的例子,甚至只是给我一个是或否的问题:

是否可以使用新的本地存储(或其他)预先调整图像大小,以便对调整图像大小一无所知的用户可以将他们的 10mb 图像拖动到我的网站中,它使用新的本地存储,然后以较小的尺寸上传.

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.

我很清楚你可以用 Flash、Java 小程序、Active X 来做到这一点……问题是你是否可以用 Javascript + Html5.

I know full well you can do it with Flash, Java applets, active X... The question is if you can do with Javascript + Html5.

期待对此的回应.

暂且不谈.

推荐答案

是的,使用 File API,然后你可以使用 canvas 元素处理图像.

Yes, use the File API, then you can process the images with the canvas element.

这篇 Mozilla Hacks 博文将带您了解大部分过程.以下是博客文章中汇编的源代码供参考:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆