1. 程式人生 > >js壓縮圖片

js壓縮圖片

ID 數據轉換 ascii碼 獲得 bsp put base ase eat

/**
* 獲得base64
* @param {Object} obj
* @param {Number} [obj.width] 圖片需要壓縮的寬度,高度會跟隨調整
* @param {Number} [obj.quality=0.8] 壓縮質量,不壓縮為1
* @param {Function} [obj.before(this, blob, file)] 處理前函數,this指向的是input:file
* @param {Function} obj.success(obj) 處理後函數
* @example
*
*/


var gUploadImageSrcWitdh = 0;

$.fn.localResizeIMG = function(obj) {
this.on(‘change‘, function() {
var file = this.files[0];
var URL = window.URL || window.webkitURL;
var blob = URL.createObjectURL(file);

var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function (theFile) {
var image = new Image();
image.src = theFile.target.result;
image.onload = function () {
//alert("圖片的寬度為" + this.width + ",長度為" + this.height);
gUploadImageSrcWitdh = this.width;

if (gUploadImageSrcWitdh < 1000) return;
// 執行前函數
if ($.isFunction(obj.before)) {
obj.before(this, blob, file)
};

_create(blob, file);
this.value = ‘‘; // 清空臨時數據
};
};


});

/**
* 生成base64
* @param blob 通過file獲得的二進制
*/
function _create(blob) {
var img = new Image();
img.src = blob;

img.onload = function() {
var that = this;

//生成比例
var w = that.width,
h = that.height,
scale = w / h;
w = obj.width || w;
h = w / scale;

//gUploadImageSrcWitdh = that.width;

//alert(that.width.toString());

//生成canvas
var canvas = document.createElement(‘canvas‘);
var ctx = canvas.getContext(‘2d‘);
$(canvas).attr({
width: w,
height: h
});
ctx.drawImage(that, 0, 0, w, h);

/**
* 生成base64
* 兼容修復移動設備需要引入mobileBUGFix.js
*/
var base64 = canvas.toDataURL(‘image/jpeg‘, obj.quality || 0.8);

// 修復IOS
if (navigator.userAgent.match(/iphone/i)) {
var mpImg = new MegaPixImage(img);
mpImg.render(canvas, {
maxWidth: w,
maxHeight: h,
quality: obj.quality || 0.8
});
base64 = canvas.toDataURL(‘image/jpeg‘, obj.quality || 0.8);
}

// 修復android
if (navigator.userAgent.match(/Android/i)) {
var encoder = new JPEGEncoder();
base64 = encoder.encode(ctx.getImageData(0, 0, w, h), obj.quality * 100 || 80);
}

// 生成結果
var result = {
base64: base64,
clearBase64: base64.substr(base64.indexOf(‘,‘) + 1)
};

// 執行後函數
obj.success(result);
};
}
};

* 將以base64的圖片url數據轉換為Blob
* @param urlData
* 用url方式表示的base64圖片數據

function convertBase64UrlToBlob(urlData) {

var bytes = window.atob(urlData.split(‘,‘)[1]); //去掉url的頭,並轉換為byte

//處理異常,將ascii碼小於0的轉換為大於0
var ab = new ArrayBuffer(bytes.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < bytes.length; i++) {
ia[i] = bytes.charCodeAt(i);
}
return new Blob([ab], { type: ‘image/png‘ });
}

//convertBase64UrlToBlob函數是將base64編碼轉換為Blob
//formData.append("imageName",convertBase64UrlToBlob(base64Codes)); //append函數的第一個參數是後臺獲取數據的參數名,和html標簽的input的name屬性功能相同

//調用JS插件,然後把base64轉換
var gUploadImageBase64;
$(‘input:file‘).localResizeIMG({
width: 800,
quality: 0.8,
success: function (result) {
gUploadImageBase64 = result.base64;
}
});

html頁

<input type="file" id="file" name="file" accept="image/*" multiple="multiple" />

js壓縮圖片