Node.js圖片處理庫sharp的使用
Node.js圖片處理庫sharp
1、sharp
sharp 是 Node.js 平臺(tái)上相當(dāng)熱門的一個(gè)圖像處理庫,其實(shí)際上是基于 C 語言編寫 的 libvips 庫封裝而來,因此高性能也成了 sharp 的一大賣點(diǎn)。
sharp 可以方便地實(shí)現(xiàn)常見的圖片編輯操作,如裁剪、格式轉(zhuǎn)換、旋轉(zhuǎn)變換、濾鏡添加等。
首先安裝下sharp:
npm install sharp
2、源碼
通過下面代碼實(shí)現(xiàn)了自動(dòng)轉(zhuǎn)換輸入圖片到數(shù)組定義尺寸
const sharp = require("sharp");
const fs = require("fs");
/**
?* 1、toFile
?* @param {String} basePicture 源文件路徑
?* @param {String} newFilePath 新文件路徑
?*/
function writeTofile(basePicture, newFilePath, width, height) {
? sharp(basePicture)
? ? .resize(width, height) //縮放
? ? .toFile(newFilePath);
}
function picTransition() {
? var picConfigure = [
? ? { name: "Default-568h@2x-1.png", width: 640, height: 1136 },
? ? { name: "Default-568h@2x.png", width: 640, height: 1136 },
? ? { name: "Default@2x-1.png", width: 640, height: 960 },
? ? { name: "Default@2x.png", width: 640, height: 960 },
? ? { name: "Loading@2x.png", width: 750, height: 1334 },
? ? { name: "Loading@3x.png", width: 1242, height: 2208 },
? ? { name: "LoadingX@3x.png", width: 1125, height: 2436 }
? ];
? picConfigure.map((item) => {
? ? writeTofile("./input.png", `./outImages/${item.name}`, item.width, item.height);
? });
}
picTransition();resize參數(shù)
// 摘抄于sharp庫
interface ResizeOptions {
? ? /** Alternative means of specifying width. If both are present this take priority. */
? ? width?: number;
? ? /** Alternative means of specifying height. If both are present this take priority. */
? ? height?: number;
? ? /** How the image should be resized to fit both provided dimensions, one of cover, contain, fill, inside or outside. (optional, default 'cover') */
? ? fit?: keyof FitEnum;
? ? /** Position, gravity or strategy to use when fit is cover or contain. (optional, default 'centre') */
? ? position?: number | string;
? ? /** Background colour when using a fit of contain, parsed by the color module, defaults to black without transparency. (optional, default {r:0,g:0,b:0,alpha:1}) */
? ? background?: Color;
? ? /** The kernel to use for image reduction. (optional, default 'lanczos3') */
? ? kernel?: keyof KernelEnum;
? ? /** Do not enlarge if the width or height are already less than the specified dimensions, equivalent to GraphicsMagick's > geometry option. (optional, default false) */
? ? withoutEnlargement?: boolean;
? ? /** Take greater advantage of the JPEG and WebP shrink-on-load feature, which can lead to a slight moiré pattern on some images. (optional, default true) */
? ? fastShrinkOnLoad?: boolean;
}3、sharp的其他操作
// 跨平臺(tái)、高性能、無運(yùn)行時(shí)依賴
const sharp = require('sharp');
const fs = require('fs');
const textToSvg = require('text-to-svg');
const basePicture = `${__dirname}/static/云霧繚繞.png`;
// 流轉(zhuǎn)Buffer緩存
function streamToBuffer(stream) {
? return new Promise((resolve, reject) => {
? ? const bufferList = []
? ? stream.on('data', data => {
? ? ? // 每一個(gè)data都是一個(gè)Buffer對(duì)象
? ? ? bufferList.push(data)
? ? })
? ? stream.on('error', err => {
? ? ? reject()
? ? })
? ? stream.on('end', () => {
? ? ? resolve(Buffer.concat(bufferList))
? ? })
? })
}
/**
?* 1、toFile
?* @param {String} basePicture 源文件路徑
?* @param {String} newFilePath 新文件路徑
?*/
function writeTofile(basePicture, newFilePath) {
? sharp(basePicture)
? ? .rotate(20) // 旋轉(zhuǎn)
? ? .resize(500, 500) //縮放
? ? .toFile(newFilePath)
}
// writeTofile(basePicture, `${__dirname}/static/云霧繚繞1.png`);
/**
?* 2、讀取圖片buffer
?* @param {String} basePicture 源文件路徑
?*/
function readFileBuffer(basePicture) {
? sharp(basePicture)
? ? .toBuffer()
? ? .then(data => {
? ? ? console.log(data)
? ? })
? ? .catch(err => {
? ? ? console.log(err)
? ? })
}
// readFileBuffer(basePicture);
/**
?* 3、對(duì)文件流進(jìn)行處理
?* @param {String} basePicture 源文件路徑
?*/
function dealWithStream(basePicture) {
? // 讀取文件流
? const readableStream = fs.createReadStream(basePicture)
? // 對(duì)流數(shù)據(jù)進(jìn)行處理
? const transformer = sharp().resize({
? ? width: 200,
? ? height: 200,
? ? fit: sharp.fit.cover,
? ? position: sharp.strategy.entropy
? })
? // 將文件讀取到的流數(shù)據(jù)寫入transformer進(jìn)行處理
? readableStream.pipe(transformer)
? // 將可寫流轉(zhuǎn)換為buffer寫入本地文件
? streamToBuffer(transformer).then(function(newPicBuffer) {
? ? fs.writeFile(`${__dirname}/static/云霧繚繞2.png`, newPicBuffer, function(
? ? ? err
? ? ) {
? ? ? if (err) {
? ? ? ? console.log(err)
? ? ? }
? ? ? console.log('done')
? ? })
? })
}
// dealWithStream(basePicture);
/**
?* 4、將文件的轉(zhuǎn)為JPEG,并對(duì)JPEG文件進(jìn)行處理
?* @param {String} basePicture 源文件路徑
?*/
function dealWithBuffer(basePicture) {
? sharp(basePicture)
? ? .resize(300, 300, {
? ? ? fit: sharp.fit.inside,
? ? ? withoutEnlargement: true
? ? })
? ? .toFormat('jpeg')
? ? .toBuffer()
? ? .then(function(outputBuffer) {
? ? ? fs.writeFile(`${__dirname}/static/云霧繚繞3.jpeg`, outputBuffer, function(
? ? ? ? err
? ? ? ) {
? ? ? ? if (err) {
? ? ? ? ? console.log(err)
? ? ? ? }
? ? ? ? console.log('done')
? ? ? })
? ? })
}
// dealWithBuffer(basePicture)
/**
?* 5、添加水印
?* @param ?{String} basePicture 原圖路徑
?* @param ?{String} watermarkPicture 水印圖片路徑
?* @param ?{String} newFilePath 輸出圖片路徑
?*/
function addWatermark(basePicture, watermarkPicture, newFilePath) {
? sharp(basePicture)
? ? .rotate(180) // 旋轉(zhuǎn)180度
? ? .composite([
? ? ? {
? ? ? ? input: watermarkPicture,
? ? ? ? top: 10,
? ? ? ? left: 10
? ? ? }
? ? ]) // 在左上坐標(biāo)(10, 10)位置添加水印圖片
? ? .withMetadata() // 在輸出圖像中包含來自輸入圖像的所有元數(shù)據(jù)(EXIF、XMP、IPTC)。
? ? .webp({
? ? ? quality: 90
? ? }) //使用這些WebP選項(xiàng)來輸出圖像。
? ? .toFile(newFilePath)
? ? .catch(err => {
? ? ? console.log(err)
? ? })
? // 注意水印圖片尺寸不能大于原圖
}
// addWatermark(
// ? basePicture,
// ? `${__dirname}/static/水印.png`,
// ? `${__dirname}/static/云霧繚繞4.png`
// )
?/**
? * 添加文字,類似添加水印
? * @param {String} basePicture 原圖路徑
? * @param {Object} font 字體設(shè)置
? * @param {String} newFilePath 輸出圖片路徑
? * @param {String} text 待粘貼文字
? * @param {Number} font.fontSize 文字大小
? * @param {String} font.color 文字顏色
? * @param {Number} font.left 文字距圖片左邊緣距離
? * @param {Number} font.top 文字距圖片上邊緣距離
? */
function addText(basePicture, font, newFilePath) {
? const { fontSize, text, color, left, top } = font;
? // 同步加載文字轉(zhuǎn)SVG的庫
? const textToSvgSync = textToSvg.loadSync();
? // 設(shè)置文字屬性
? const attributes = {
? ? fill: color
? };
? const options = {
? ? fontSize,
? ? anchor: 'top',
? ? attributes
? };
? // 文字轉(zhuǎn)svg,svg轉(zhuǎn)buffer
? const svgTextBuffer = Buffer.from(textToSvgSync.getSVG(text, options));
? // 添加文字
? sharp(basePicture)
? ? // ?.rotate(180) // 旋轉(zhuǎn)180度
? ? .composite([
? ? ? {
? ? ? ? input: svgTextBuffer,
? ? ? ? top,
? ? ? ? left
? ? ? }
? ? ]) // 在左上坐標(biāo)(10, 10)位置添加文字
? ? .withMetadata() // 在輸出圖像中包含來自輸入圖像的所有元數(shù)據(jù)(EXIF、XMP、IPTC)。
? ? .webp({
? ? ? quality: 90
? ? }) //使用這些WebP選項(xiàng)來輸出圖像。
? ? .toFile(newFilePath)
? ? .catch(err => {
? ? ? console.log(err)
? ? });
}
addText(
? basePicture,
? {
? ? fontSize: 50,
? ? text: '洋溢洋溢洋溢',
? ? color: 'yellow',
? ? left: 100,
? ? top: 100
? },
? `${__dirname}/static/云霧繚繞5.png`
);總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
垃圾回收器的相關(guān)知識(shí)點(diǎn)總結(jié)
本文是小編在網(wǎng)絡(luò)上整理的關(guān)于垃圾回收器的相關(guān)知識(shí)點(diǎn),很多語言和程序都用的到,有興趣的可以學(xué)習(xí)下。2018-05-05
Node.js完整實(shí)現(xiàn)博客系統(tǒng)詳解
這篇文章主要介紹了Node.js完整實(shí)現(xiàn)一個(gè)博客系統(tǒng)的流程,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-08-08
NestJS核心概念之Middleware中間件創(chuàng)建使用示例
這篇文章主要為大家介紹了NestJS核心概念之Middleware中間件創(chuàng)建使用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-08-08
vscode調(diào)試node.js的實(shí)現(xiàn)方法
這篇文章主要介紹了vscode調(diào)試node.js的實(shí)現(xiàn)方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-03-03
nodejs連接ftp上傳下載實(shí)現(xiàn)方法詳解【附:踩坑記錄】
這篇文章主要介紹了nodejs連接ftp上傳下載實(shí)現(xiàn)方法,結(jié)合實(shí)例形式詳細(xì)分析了node.js使用ftp模塊實(shí)現(xiàn)針對(duì)ftp上傳、下載相關(guān)操作的方法,并附帶記錄了傳輸速度慢的解決方法,需要的朋友可以參考下2023-04-04
node.js配置Token驗(yàn)證的2種方式總結(jié)
token驗(yàn)證,在設(shè)計(jì)登錄注冊(cè)和一些權(quán)限接口時(shí)發(fā)揮作用,下面這篇文章主要給大家介紹了關(guān)于node.js配置Token驗(yàn)證的2種方式,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-02-02
pnpm實(shí)現(xiàn)依賴包共享和依賴包項(xiàng)目隔離的方法詳解
pnpm是Node.js的包管理器,它是 npm 的直接替代品,相對(duì)于npm和yarn它的優(yōu)點(diǎn)就在于速度快和高效節(jié)省磁盤空間,本文主要講解pnpm相比于npm/yarn如何利用軟硬鏈接來節(jié)省磁盤空間,以及如何實(shí)現(xiàn)依賴包共享和依賴包項(xiàng)目隔離的,需要的朋友可以參考下2024-05-05

