[H5-Compress-Image]利用canvas实现 javascript 图片压缩处理_基于requirejs模块化的代码实现
// 还存在有问题的代码,问题在于processFile()中
// 问题:在ipone 5c 下,某些图片压缩处理后,上传到服务器生成的文件size为0,即是空白 ;define(['mod/tool/formSubmit'] ,function(o_formSubmit) { return { init: function(id) {
var self = this;
self.sniff(id);
var $img = '';
var $inputField = '';
},
sniff: function(id) {
var self = this;
if (window.File && window.FileReader && window.FormData) { $inputField = $('#' + id); $inputField.on('change', function (e) { var file = e.target.files[0];
if($('.c-img-wrap').length >= 9)
{
Hnb.ui.showError('不能上传超过9张图片' , 3000);
return ;
} if (file) {
//alert(file.type);
//if(!file.type) file.type='image/jpeg';
//if (/^image\//i.test(file.type)) {
if($("#id_img_list").parent().attr("scrollWidth") > $(window).width())
{
$("#id_img_list").parent().scrollLeft($("#id_img_list").parent().attr("scrollWidth") - $(window).width());
}
$img = $('<a class="bg c-img-wrap" href="javascript:void(null);"><i class="pa c-img-close"></i></a>').insertBefore($("#id_last_img_wrap")); self.readFile(file);
//} else {
// Hnb.ui.showError('请在浏览器中打开该页面上传图片' , 3000);
// $inputField.val('');
//}
} });
$inputField.val('');
} else {
Hnb.ui.showError("当前您的浏览器不支持图片上传,请选择其他的浏览器进行上传。" , 3000);
$inputField.val('');
}
}, readFile: function (file) {
var self = this;
var reader = new FileReader();
var head = '';
reader.onloadend = function () {
//reader.onload = function () {
head = reader.result.substr(0, 20);
alert('head:' + head);
alert('file_type:' + file.type);
self.processFile(reader.result, file.type);
} reader.onerror = function () {
Hnb.ui.showError('上传图片过程中发生了网络异常,请稍后重试。' , 3000);
} reader.readAsDataURL(file);
},
processFile: function (dataURL, fileType) { var self = this;
var maxWidth = 3120;
var maxHeight = 4208; var image = new Image();
image.src = dataURL; image.onload = function () {
var width = image.width;
var height = image.height;
var shouldResize = (width > maxWidth) || (height > maxHeight); if (!shouldResize) {
//self.submitFile(dataURL);
self.sendFile(dataURL , fileType);
return;
} var newWidth;
var newHeight; if (width > height) {
newHeight = height * (maxWidth / width);
newWidth = maxWidth;
} else {
newWidth = width * (maxHeight / height);
newHeight = maxHeight;
} var canvas = document.createElement('canvas'); canvas.width = newWidth;
canvas.height = newHeight; var context = canvas.getContext('2d'); context.drawImage(this, 0, 0, newWidth, newHeight); dataURL = canvas.toDataURL(fileType);
alert(dataURL.length);
//window.location = dataURL;
//self.sendFile(dataURL , fileType);
/*
var file = canvas.mozGetAsFile("foo.png");
var f = document.createElement("form");
var i = document.createElement("input"); //input element, text
i.setAttribute('type',"file");
i.setAttribute('name',"upfile");
i.setAttribute('value' , dataURL);
f.appendChild(i);
*/
//$("#id_upfile").val(dataURL);
//document.forms[0].upfile.val = dataURL;
//window.location = dataURL; //var formData = new FormData(document.forms[0]);
//console.log(document.forms[0]);
//console.log(formData.get('upfile'));
//console.log(formData);
//return;
//formData.append('imageData', dataURL);
//formData.delete('upfile');
//console.log($inputField.files);
//formData.set('upfile', $inputField.files[0] , dataURL);
//self.submitFile($(f));
}; image.onerror = function () {
//alert('There was an error processing your file!');
Hnb.ui.showError('上传图片处理过程中发生了网络异常,请稍后重试。' , 3000);
};
},
submitFile: function(f) {
var self = this;
//console.log(f);
o_formSubmit.create(f , Hnb.WWW_CGI_URL + "/image/saveInCrossDomain").start().done(function(json_msg){
if(json_msg.state || !json_msg.data.real_url) {
Hnb.ui.showError("上传图片失败!" , 3000);
$img.remove();
} else { console.log(json_msg.data); $img.removeClass("bg").addClass("comBg").css("background-image" , "url(" + json_msg.data.real_url + ")").attr("hnb-src" , json_msg.data.real_url);
//$img.html('<img src="' + json_msg.data.real_url + '" alt="帖子图片">');
$("#id_top_wrap").addClass("active");
//$img.html("");
}
}).fail(function(json_error){
$img.remove();
Hnb.ui.showError("您的网络有点慢,请稍后重试" , 3000);
}).always(function(){
$img.removeClass("bg");
self.isSubmitingImgNum--;
});
},
sendFile: function (fileData , fileType) { var formData = new FormData(); formData.append('imageData', fileData);
formData.append('imageType' , fileType); $.ajax({
type: 'POST',
timeout: 300000,
url: Hnb.WWW_CGI_URL + '/image/saveCndCompressImage',
data: formData,
contentType: false,
processData: false,
success: function (json_msg) {
//console.log('返回json数据' + json_msg);
var json_msg = $.parseJSON(json_msg);
if(!json_msg.state)
{
// 跨域请求处理
document.domain = 'hinabian.com';
// 可以将上传到线上的图片,追加到预览图位置
// ...
} else {
Hnb.ui.showError('您的网络有点慢,请稍后再上传。' , 3000);
}
},
error: function (json_msg) {
Hnb.ui.showError('上传图片发生了网络异常,请稍后重试。' , 3000);;
}
}).always(
function() {
$inputField.val("");
$img.removeClass("bg");
}
); }
}
});
// 修改后,可以正常使用的代码 ;define(['mod/tool/formSubmit'] ,function(o_formSubmit) { return { init: function(id) {
var self = this;
self.sniff(id);
var $img = '';
var $inputField = '';
},
sniff: function(id) {
var self = this;
if (window.File && window.FileReader && window.FormData) { $inputField = $('#' + id);
$inputField.on('change', function (e) { var file = e.target.files[0];
if($('.c-img-wrap').length >= 9)
{
Hnb.ui.showError('不能上传超过9张图片' , 3000);
return ;
} if (file) {
//if(!file.type) file.type='image/jpeg';
//if (/^image\//i.test(file.type)) {
if($("#id_img_list").parent().attr("scrollWidth") > $(window).width())
{
$("#id_img_list").parent().scrollLeft($("#id_img_list").parent().attr("scrollWidth") - $(window).width());
}
$img = $('<a class="bg c-img-wrap" href="javascript:void(null);"><i class="pa c-img-close"></i></a>').insertBefore($("#id_last_img_wrap")); self.readFile(file);
}
});
} else {
Hnb.ui.showError("当前您的浏览器不支持图片上传,请选择其他的浏览器进行上传。", 3000);
//$inputField.val('');
}
$inputField.val('');
}, readFile: function (file) {
var self = this;
var reader = new FileReader();
var head = '';
reader.onloadend = function () {
//reader.onload = function () {
//head = reader.result.substr(0, 20);
self.processFile(reader.result, file.type);
} reader.onerror = function () {
Hnb.ui.showError('上传图片过程中发生了网络异常,请稍后重试。', 3000);
return;
} reader.readAsDataURL(file);
$inputField.val('');
}, processFile: function (dataURL, fileType) {
var self = this;
var unitSize = 480; var image = new Image();
image.src = dataURL; image.onload = function () {
var wFactor = image.width / unitSize;
var hFactor = image.height / unitSize;
var minFactor = Math.round(Math.min(wFactor, hFactor)); if (minFactor < 2) {
//self.submitFile(dataURL);
self.sendFile(dataURL, fileType);
return;
} var newWidth = image.width / minFactor;
var newHeight = image.height / minFactor;
var canvas = document.createElement('canvas');
canvas.width = newWidth;
canvas.height = newHeight; var context = canvas.getContext('2d');
context.drawImage(this, 0, 0, newWidth, newHeight); dataURL = canvas.toDataURL(fileType);
//window.location = dataURL;
self.sendFile(dataURL, fileType);
}; image.onerror = function () {
Hnb.ui.showError('上传图片处理过程中发生了网络异常,请稍后重试。' , 3000);
$inputField.val('');
};
}, submitFile: function(f) {
var self = this;
o_formSubmit.create(f , Hnb.WWW_CGI_URL + "/image/saveInCrossDomain").start().done(function(json_msg){
if(json_msg.state || !json_msg.data.real_url) {
Hnb.ui.showError("上传图片失败!" , 3000);
$img.remove();
} else {
$img.removeClass("bg").addClass("comBg").css("background-image" , "url(" + json_msg.data.real_url + ")").attr("hnb-src" , json_msg.data.real_url);
//$img.html('<img src="' + json_msg.data.real_url + '" alt="帖子图片">');
$("#id_top_wrap").addClass("active");
//$img.html("");
}
}).fail(function(json_error){
$img.remove();
Hnb.ui.showError("您的网络有点慢,请稍后重试" , 3000);
}).always(function(){
$img.removeClass("bg");
self.isSubmitingImgNum--; });
}, sendFile: function (fileData , fileType) { var formData = new FormData();
formData.append('imageData', fileData);
formData.append('imageType' , fileType); $.ajax({
type: 'POST',
timeout: 300000,
url: Hnb.WWW_CGI_URL + '/image/saveCndCompressImage',
data: formData,
contentType: false,
processData: false,
success: function (json_msg) {
var json_msg = $.parseJSON(json_msg);
if(!json_msg.state)
{
document.domain = 'hinabian.com';
$img.removeClass("bg").addClass("comBg").css("background-image" , "url(" + json_msg.data.real_url + ")").attr("hnb-src" , json_msg.data.real_url);
//$img.html('<img src="' + json_msg.data.real_url + '" alt="帖子图片">');
$("#id_top_wrap").addClass("active");
} else {
Hnb.ui.showError('您的网络有点慢,请稍后再上传。' , 3000);
}
},
error: function (json_msg) {
Hnb.ui.showError('上传图片发生了网络异常,请稍后重试。' , 3000);;
}
}).always(
function() {
$inputField.val("");
$img.removeClass("bg");
}
);
}
}
});
[H5-Compress-Image]利用canvas实现 javascript 图片压缩处理_基于requirejs模块化的代码实现的更多相关文章
- 前端JS利用canvas的drawImage()对图片进行压缩
对于大尺寸图片的上传,在前端进行压缩除了省流量外,最大的意义是极大的提高了用户体验. 这种体验包括两方面: 1.由于上传图片尺寸比较小,因此上传速度会比较快,交互会更加流畅,同时大大降低了网络异常导致 ...
- 基于canvas的前端图片压缩
/*common*/ /** * canvas图片压缩 * @param {[Object]} opt [配置参数] * @param {[Function]} cbk [回调函数] * @retur ...
- 利用canvas压缩图片
现在手机拍的照片动不动就是几M,当用户上传手机里的照片时一个消耗流量大,一个上传时间长,为了解决这个问题,就需要压缩图片: 想法:利用canvas重绘图片,保持宽高比不变,具体宽高根本具体情况而定. ...
- 利用canvas对上传图片进行上传前压缩
利用谷歌调式工具发现,图片大小直接影响着首屏加载时间. 且考虑到后期服务端压力,图片压缩特别必要. 本文是前端利用canvas实现图片.参考文章:https://www.cnblogs.com/007 ...
- 使用ajax上传图片,支持图片即时浏览,支持js图片压缩后上传给服务器
使用ajax上传图片,支持图片即时浏览,支持js图片压缩后上传给服务器 ajax上传主要使用了 var reader = new FileReader() 此方法 js图片压缩主要是利用canvas进 ...
- Js利用Canvas实现图片压缩
最近做的APP项目涉及到手机拍照上传图片,因为手机拍照的图片通常都比较大,所以上传的时候就会很慢.为此,需要对图片进行压缩处理来优化上传功能.以下是具体实现: /* * 图片压缩 * img 原始图片 ...
- Vue directive自定义指令+canvas实现H5图片压缩上传-Base64格式
前言 最近优化项目-手机拍照图片太大,回显速度比较慢,使用了vue的自定义指令实现H5压缩上传base64格式的图片 canvas自定义指令 Vue.directive("canvas&qu ...
- 使用canvas实现对图片的批量打码
最近有个需求,利用h5的canvas对图片一些涉及个人隐私的地方进行打码再上传,而且最好能实现批量打码.意思是在一张图片上对哪些地方做了打码,后续的所有图片都在同样的地方也可以自动打上码,不用人工一张 ...
- canvas 利用canvas中的globalCompositeOperation 绘制刮奖 效果
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <t ...
随机推荐
- triton,docker,mesos
triton user: jill /root/.sdc/docker/jill 下 root@1f6af9d8-8ed9-e940-9c6c-d9505ca25896:~/.sdc/docker/j ...
- dubbo通信协议
对dubbo的协议的学习,可以知道目前主流RPC通信大概是什么情况,本文参考dubbo官方文档 http://dubbo.io/User+Guide-zh.htm dubbo共支持如下几种通信协议: ...
- mac安装protobuf2.4.1时报错./include/gtest/internal/gtest-port.h:428:10: fatal error: 'tr1/tuple' file not found和google/protobuf/message.cc:175:16: error: implicit instantiation of undefined template
通过网上下载的protobuf2.4.1的压缩文件,然后进行安装,./configure和make时遇到了两个问题. 正常的安装步骤如下: ./configure make make check m ...
- win7卸载打印机驱动
无法删除的话停止Print Spooler服务 删除PRINTERS文件夹下面的文件 C:\Windows\System32\spool\PRINTERS目录下所有的文件,重新启动服务:print s ...
- 没有无线路由,如何让手机使用电脑的网络xyytit
前言: 智能手机已经越来越普遍,但国内的无线网络的步伐还是没有跟上智能机的脚步.纵使3G,4G已经相继推出,但国内的资费价格着实有点不接地气,所以无线wifi无疑是智能机使用最多的.各大软件上.设备商 ...
- handler通信机制
package com.example.gp08_day26_handler3; import android.os.Bundle; import android.os.Handler; import ...
- win 下 apache 实现负载均衡
1.打开apache的配置文件httpd.conf,打开如下项 LoadModule proxy_module modules/mod_proxy.so LoadModule proxy_ajp_mo ...
- Alluxio/Tachyon如何发挥lineage的作用?
在Spark的RDD中引入过lineage这一概念.指的是RDD之间的依赖.而Alluxio则使用lineage来表示文件之间的依赖.在代码层面,指的是fileID之间的依赖. 代码中的注释指出: * ...
- dir/
dos窗口输入dir命令是显示磁盘目录命令: addslashes()使用反斜线转义字符串: exec($command,$output,$return)执行一个外部程序 $command:要执行的命 ...
- 11个 常见UI/UX设计师调查问卷分析
作为专业人员,设计出优秀的作品是UI/UX设计师必备的技能,同样重要的是良好的沟通能力.进一步来讲,提出正确的问题也是作为设计师的技能之一. 任何项目的首要任务都是收集需要的信息,以便正确有效地完成我 ...