UNPKG

yylib-quick-mobile

Version:

yylib-quick-mobile

92 lines (79 loc) 3.32 kB
'use strict'; var ADDR = require('../business/BaseHost'); var ajax = require('./ajax'); var _ = require('lodash'); function readImageAsBase64(item, callback) { if (!item || typeof item.getAsFile !== 'function') { return; } var file = item.getAsFile(); var reader = new FileReader(); reader.onload = function (evt) { callback(evt.target.result); }; reader.readAsDataURL(file); } var PasteImageUtils = {}; PasteImageUtils.getImageData = function (event, callback) { var clipboardData = event ? event.clipboardData : null; var found = false; var imageType = /^image/; if (!clipboardData) return; return Array.prototype.forEach.call(clipboardData.types, function (type, i) { if (found) return; if (type.match(imageType) || clipboardData.items[i].type.match(imageType)) { readImageAsBase64(clipboardData.items[i], callback); return found = true; } }); }; PasteImageUtils.getImageDom = function (event, callback) { PasteImageUtils.getImageData(event, function (imgData) { var element = document.createElement('img'); element.src = imgData; callback(element); }); }; PasteImageUtils.pasteTo = function (event, target) { PasteImageUtils.getImageDom(event, function (imgElement) { target.appendChild(imgElement); }); }; PasteImageUtils.bindPaste = function (target) { if (!target || !target.addEventListener) return; target.addEventListener('paste', function (event) { PasteImageUtils.pasteTo(event, this); }); }; PasteImageUtils.zipImg = function (imgBase64, callback, options) { console.log('原始大小:' + imgBase64.length); var img = new Image(); img.src = imgBase64; img.onload = function () { var canvas = document.createElement('CANVAS'); var ctx = canvas.getContext('2d'); var width = img.width; var height = img.height; var rate = 0.9; if (width > 800 && height > 480) rate = 0.8; if (width > 900 && height > 600) rate = 0.75; if (width > 960 && height > 720) rate = 0.7; if (width > 1024 && height > 768) rate = 0.65; if (width > 1280 && height > 768) rate = 0.6; if (options && options.rate) rate = options.rate; canvas.width = width * rate; canvas.height = height * rate; ctx.drawImage(img, 0, 0, width, height, 0, 0, width * rate, height * rate); var dataURL = canvas.toDataURL("image/jpeg", 0.8); console.log('压缩后大小:' + dataURL.length); if (typeof callback == 'function') callback(dataURL); canvas = null; }; }; PasteImageUtils.uploadImg = function () { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : { url: url, imgData: imgData, params: params, success: success, error: error }; var opts = options ? options : {}; var data = _.assign({}, opts.params, { content: opts.imgData.replace('data:image/png;base64,', '').replace('data:image/jpeg;base64,', '') }); ajax.postJSON(opts.url ? opts.url : ADDR + '/icop-file/file/uploadBase64', data, opts.success, opts.error); }; module.exports = PasteImageUtils;