From 37cdeff5f9267a8d4f909d134b6fb6d029fc3eff Mon Sep 17 00:00:00 2001 From: CPunisher <1343316114@qq.com> Date: Thu, 25 Jun 2020 17:49:44 +0800 Subject: [PATCH] image cropping --- src/containers/param/ParamUploadViewer.js | 2 +- src/qrbtf-logo.svg | 746 ---------------------- src/utils/imageUtils.js | 22 +- 3 files changed, 16 insertions(+), 754 deletions(-) delete mode 100644 src/qrbtf-logo.svg diff --git a/src/containers/param/ParamUploadViewer.js b/src/containers/param/ParamUploadViewer.js index 688be1a..daf1a0c 100644 --- a/src/containers/param/ParamUploadViewer.js +++ b/src/containers/param/ParamUploadViewer.js @@ -17,7 +17,7 @@ const mapDispatchToProps = (dispatch, ownProps) => ({ const file = e.target.files[0]; if (isPicture(file)) { handleUpload(); - toBase64(file, 500, 500).then(res => { + toBase64(file, 1.0).then(res => { dispatch(changeParam(ownProps.rendererIndex, ownProps.paramIndex, res)) }) } diff --git a/src/qrbtf-logo.svg b/src/qrbtf-logo.svg deleted file mode 100644 index cd55ec5..0000000 --- a/src/qrbtf-logo.svg +++ /dev/null @@ -1,746 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/utils/imageUtils.js b/src/utils/imageUtils.js index df5e263..defd81a 100644 --- a/src/utils/imageUtils.js +++ b/src/utils/imageUtils.js @@ -8,7 +8,7 @@ export function isPicture(file) { return fileTypes.includes(file.type); } -export function toBase64(file) { +export function toBase64(file, aspectRatio) { let canvas = document.createElement('canvas'); let ctx = canvas.getContext('2d'); let img = document.createElement('img'); @@ -16,14 +16,22 @@ export function toBase64(file) { return new Promise(resolve => { img.onload = () => { - let size = Math.min(img.width, img.height); - - canvas.setAttribute('width', size); - canvas.setAttribute('height', size); + let width, height; + if (img.width < img.height) { + width = img.width; + height = width / aspectRatio; + } + else { + height = img.height; + width = height * aspectRatio; + } + console.log(width + ' ' + height) + canvas.setAttribute('width', width); + canvas.setAttribute('height', height); ctx.fillStyle = 'white'; - ctx.fillRect(0, 0, size, size); - ctx.drawImage(img, (img.width - size) / 2, (img.height - size) / 2, size, size, 0, 0, size, size); + ctx.fillRect(0, 0, width, height); + ctx.drawImage(img, (img.width - width) / 2, (img.height - height) / 2, width, height, 0, 0, width, height); resolve(canvas.toDataURL(file.type, 0.9)); };