// ==UserScript==
// @name 图片压缩
// @namespace http://tampermonkey.net/
// @version 0.2
// @description select img to zip!
// @author Paul
// @match *://www.baidu.com
// @require https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.js
// @require https://cdnjs.cloudflare.com/ajax/libs/layer/2.3/layer.js
// @grant GM_addStyle
// @run-at document-end
// @downloadURL none
// ==/UserScript==
(function() {
'use strict';
({
$container: null,
reader: null,
img:null
, addCss: function () {
$(document.head).append('')
GM_addStyle('.btnContainer{ position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);width:60px;height:35px;line-height:35px; }\
.btnContainer .ubtn{ display:block; text-align:center;width:100%;height:100%;background-color:#38f;color:#fff; }\
.btnContainer .ufile{display:block; position:absolute;top:0;left:0;width:100%;height:100%;opacity:0; }\
.maxImg{ max-height:100%;max-width:100%; }');
}
, createBtn: function () {
var htmlStr = '
选择图片
';
this.addCss();
this.$container = $(htmlStr);
this.$container.appendTo($('body'));
this.addEvent();
}
, addEvent: function () {
var that = this;
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
this.img.onload = function () {
// 图片原始尺寸
var originWidth = this.width;
var originHeight = this.height;
// 最大尺寸限制,可通过国设置宽高来实现图片压缩程度
var maxWidth = 800,
maxHeight = 800;
// 目标尺寸
var targetWidth = originWidth,
targetHeight = originHeight;
// 图片尺寸超过400x400的限制
if (originWidth > maxWidth || originHeight > maxHeight) {
if (originWidth / originHeight > maxWidth / maxHeight) {
// 更宽,按照宽度限定尺寸
targetWidth = maxWidth;
targetHeight = Math.round(maxWidth * (originHeight / originWidth));
} else {
targetHeight = maxHeight;
targetWidth = Math.round(maxHeight * (originWidth / originHeight));
}
}
// canvas对图片进行缩放
canvas.width = targetWidth;
canvas.height = targetHeight;
// 清除画布
context.clearRect(0, 0, targetWidth, targetHeight);
// 图片压缩
context.drawImage(that.img, 0, 0, targetWidth, targetHeight);
/*第一个参数是创建的img对象;第二个参数是左上角坐标,后面两个是画布区域宽高*/
//压缩后的图片base64 url
/*canvas.toDataURL(mimeType, qualityArgument),mimeType 默认值是'image/jpeg';
* qualityArgument表示导出的图片质量,只要导出为jpg和webp格式的时候此参数才有效果,默认值是0.92*/
var newUrl = canvas.toDataURL('image/jpeg', 0.80);//base64 格式
//console.log(canvas.toDataURL('image/jpeg', 0.92));
layer.open({
type: 1,
title: '压缩后图片',
content: '',
success: function () {
layer.msg('在图片上右键,另存为即可');
}
});
};
this.reader.onload=function (e) { this.img.src = e.target.result; }.bind(this);
this.$container.find('input:first').on('change', this.change.bind(this));
}
, change: function (e) {
var file = e.target.files[0];
if (file.type.indexOf("image") == 0) {
this.reader.readAsDataURL(file);
}
}
, run: function () {
this.reader = new FileReader();
this.img = new Image();
this.createBtn();
}
}).run();
// Your code here...
})();