Skip to content

Instantly share code, notes, and snippets.

@kehr
Created June 28, 2017 03:22
Show Gist options
  • Save kehr/21368a4de76f1fec7b10adebca8bf032 to your computer and use it in GitHub Desktop.
Save kehr/21368a4de76f1fec7b10adebca8bf032 to your computer and use it in GitHub Desktop.
nodejs 压缩本地图片,转换为 base64。
const fs = require('fs');
const Canvas = require('canvas');
function compress(buff) {
// 将文件绘制成图片对象
let image = new Canvas.Image;
image.src = buff;
// 获取原始图片宽高
let drawWidth=image.width;
let drawHeight=image.height;
// 以下改变一下图片大小
var maxSide = Math.max(drawWidth, drawHeight);
if (maxSide > 600) {
var minSide = Math.min(drawWidth, drawHeight);
minSide = minSide / maxSide * 1024;
maxSide = 600;
if (drawWidth > drawHeight) {
drawWidth = maxSide;
drawHeight = minSide;
} else {
drawWidth = minSide;
drawHeight = maxSide;
}
}
// 用 canvas 重绘
let canvas = new Canvas(drawWidth, drawHeight);
let context=canvas.getContext('2d');
context.drawImage(image, 0, 0, drawWidth,drawHeight);
// 压缩0.5就是压缩百分之50
canvas.toDataURL('image/jpeg', 0.7, (err, jpeg) => {
// 压缩后的数据写入文件
fs.writeFile('result.txt', jpeg, (err) => {
if (err) throw err;
console.log('It\'s saved!');
});
});
}
fs.readFile('WechatIMG3836.png', (err, sq) => {compress(sq)})
@assmdx
Copy link

assmdx commented May 16, 2018

perfect!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment