Created
June 28, 2017 03:22
-
-
Save kehr/21368a4de76f1fec7b10adebca8bf032 to your computer and use it in GitHub Desktop.
nodejs 压缩本地图片,转换为 base64。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
perfect!