Node.js圖片處理庫sharp的使用
Node.js圖片處理庫sharp
1、sharp
sharp 是 Node.js 平臺上相當(dāng)熱門的一個圖像處理庫,其實際上是基于 C 語言編寫 的 libvips 庫封裝而來,因此高性能也成了 sharp 的一大賣點。
sharp 可以方便地實現(xiàn)常見的圖片編輯操作,如裁剪、格式轉(zhuǎn)換、旋轉(zhuǎn)變換、濾鏡添加等。
首先安裝下sharp:
npm install sharp
2、源碼
通過下面代碼實現(xiàn)了自動轉(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的其他操作
// 跨平臺、高性能、無運行時依賴
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 => {
? ? ? // 每一個data都是一個Buffer對象
? ? ? 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、對文件流進(jìn)行處理
?* @param {String} basePicture 源文件路徑
?*/
function dealWithStream(basePicture) {
? // 讀取文件流
? const readableStream = fs.createReadStream(basePicture)
? // 對流數(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,并對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選項來輸出圖像。
? ? .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選項來輸出圖像。
? ? .toFile(newFilePath)
? ? .catch(err => {
? ? ? console.log(err)
? ? });
}
addText(
? basePicture,
? {
? ? fontSize: 50,
? ? text: '洋溢洋溢洋溢',
? ? color: 'yellow',
? ? left: 100,
? ? top: 100
? },
? `${__dirname}/static/云霧繚繞5.png`
);總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Node.js實現(xiàn)的簡易網(wǎng)頁抓取功能示例
這篇文章主要介紹了Node.js實現(xiàn)的簡易網(wǎng)頁抓取功能示例,本文使用了PhantomJS、node-phantomjs等庫實現(xiàn),需要的朋友可以參考下2014-12-12
Windows下nodejs安裝及環(huán)境配置的實戰(zhàn)步驟
最近換了一個電腦,因為要使用到NodeJS,我將我自己的安裝步驟分享給大家,下面這篇文章主要給大家介紹了關(guān)于Windows下nodejs安裝及環(huán)境配置的相關(guān)資料,文中通過圖文介紹的非常詳細(xì),需要的朋友可以參考下2023-02-02
NodeJS使用formidable實現(xiàn)文件上傳
這篇文章主要為大家詳細(xì)介紹了NodeJS使用formidable實現(xiàn)文件上傳的相關(guān)方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-10-10
Node.js基礎(chǔ)入門之path模塊,url模塊,http模塊使用詳解
這篇文章主要為大家介紹了Node.js中的三個模塊(path、url、http)的使用詳解,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解一下2022-03-03

