Node.js圖片處理庫(kù)sharp的使用
Node.js圖片處理庫(kù)sharp
1、sharp
sharp 是 Node.js 平臺(tái)上相當(dāng)熱門(mén)的一個(gè)圖像處理庫(kù),其實(shí)際上是基于 C 語(yǔ)言編寫(xiě) 的 libvips 庫(kù)封裝而來(lái),因此高性能也成了 sharp 的一大賣(mài)點(diǎn)。
sharp 可以方便地實(shí)現(xiàn)常見(jiàn)的圖片編輯操作,如裁剪、格式轉(zhuǎn)換、旋轉(zhuǎn)變換、濾鏡添加等。
首先安裝下sharp:
npm install sharp
2、源碼
通過(guò)下面代碼實(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庫(kù) 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)、高性能、無(wú)運(yùn)行時(shí)依賴(lài) 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ù)寫(xiě)入transformer進(jìn)行處理 ? readableStream.pipe(transformer) ? // 將可寫(xiě)流轉(zhuǎn)換為buffer寫(xiě)入本地文件 ? 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() // 在輸出圖像中包含來(lái)自輸入圖像的所有元數(shù)據(jù)(EXIF、XMP、IPTC)。 ? ? .webp({ ? ? ? quality: 90 ? ? }) //使用這些WebP選項(xiàng)來(lái)輸出圖像。 ? ? .toFile(newFilePath) ? ? .catch(err => { ? ? ? console.log(err) ? ? }) ? // 注意水印圖片尺寸不能大于原圖 } // addWatermark( // ? basePicture, // ? `${__dirname}/static/水印.png`, // ? `${__dirname}/static/云霧繚繞4.png` // ) ?/** ? * 添加文字,類(lèi)似添加水印 ? * @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的庫(kù) ? 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() // 在輸出圖像中包含來(lái)自輸入圖像的所有元數(shù)據(jù)(EXIF、XMP、IPTC)。 ? ? .webp({ ? ? ? quality: 90 ? ? }) //使用這些WebP選項(xiàng)來(lái)輸出圖像。 ? ? .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)文章
Node.js實(shí)現(xiàn)的簡(jiǎn)易網(wǎng)頁(yè)抓取功能示例
這篇文章主要介紹了Node.js實(shí)現(xiàn)的簡(jiǎn)易網(wǎng)頁(yè)抓取功能示例,本文使用了PhantomJS、node-phantomjs等庫(kù)實(shí)現(xiàn),需要的朋友可以參考下2014-12-12Windows下nodejs安裝及環(huán)境配置的實(shí)戰(zhàn)步驟
最近換了一個(gè)電腦,因?yàn)橐褂玫絅odeJS,我將我自己的安裝步驟分享給大家,下面這篇文章主要給大家介紹了關(guān)于Windows下nodejs安裝及環(huán)境配置的相關(guān)資料,文中通過(guò)圖文介紹的非常詳細(xì),需要的朋友可以參考下2023-02-02NodeJS使用formidable實(shí)現(xiàn)文件上傳
這篇文章主要為大家詳細(xì)介紹了NodeJS使用formidable實(shí)現(xiàn)文件上傳的相關(guān)方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-10-10nodejs語(yǔ)言實(shí)現(xiàn)驗(yàn)證碼生成功能的示例代碼
這篇文章主要介紹了nodejs語(yǔ)言實(shí)現(xiàn)驗(yàn)證碼生成功能的示例代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-10-10Node.js基礎(chǔ)入門(mén)之path模塊,url模塊,http模塊使用詳解
這篇文章主要為大家介紹了Node.js中的三個(gè)模塊(path、url、http)的使用詳解,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解一下2022-03-03node實(shí)現(xiàn)封裝一個(gè)圖片拼接插件
這篇文章主要介紹了node實(shí)現(xiàn)封裝一個(gè)圖片拼接插件,文章圍繞主題展開(kāi)詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的朋友可以參考一下2022-08-08