最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Node.js圖片處理庫sharp的使用

 更新時間:2023年01月16日 14:16:58   作者:逆襲的菜鳥X  
這篇文章主要介紹了Node.js圖片處理庫sharp的使用,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

Node.js圖片處理庫sharp

1、sharp

sharp 是 Node.js 平臺上相當熱門的一個圖像處理庫,其實際上是基于 C 語言編寫 的 libvips 庫封裝而來,因此高性能也成了 sharp 的一大賣點。

sharp 可以方便地實現常見的圖片編輯操作,如裁剪、格式轉換、旋轉變換、濾鏡添加等。

首先安裝下sharp:

npm install sharp

2、源碼

通過下面代碼實現了自動轉換輸入圖片到數組定義尺寸

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參數

// 摘抄于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`;

// 流轉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) // 旋轉
? ? .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、對文件流進行處理
?* @param {String} basePicture 源文件路徑
?*/
function dealWithStream(basePicture) {
? // 讀取文件流
? const readableStream = fs.createReadStream(basePicture)
? // 對流數據進行處理
? const transformer = sharp().resize({
? ? width: 200,
? ? height: 200,
? ? fit: sharp.fit.cover,
? ? position: sharp.strategy.entropy
? })
? // 將文件讀取到的流數據寫入transformer進行處理
? readableStream.pipe(transformer)

? // 將可寫流轉換為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、將文件的轉為JPEG,并對JPEG文件進行處理
?* @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) // 旋轉180度
? ? .composite([
? ? ? {
? ? ? ? input: watermarkPicture,
? ? ? ? top: 10,
? ? ? ? left: 10
? ? ? }
? ? ]) // 在左上坐標(10, 10)位置添加水印圖片
? ? .withMetadata() // 在輸出圖像中包含來自輸入圖像的所有元數據(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 字體設置
? * @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;
? // 同步加載文字轉SVG的庫
? const textToSvgSync = textToSvg.loadSync();
? // 設置文字屬性
? const attributes = {
? ? fill: color
? };
? const options = {
? ? fontSize,
? ? anchor: 'top',
? ? attributes
? };
? // 文字轉svg,svg轉buffer
? const svgTextBuffer = Buffer.from(textToSvgSync.getSVG(text, options));

? // 添加文字
? sharp(basePicture)
? ? // ?.rotate(180) // 旋轉180度
? ? .composite([
? ? ? {
? ? ? ? input: svgTextBuffer,
? ? ? ? top,
? ? ? ? left
? ? ? }
? ? ]) // 在左上坐標(10, 10)位置添加文字
? ? .withMetadata() // 在輸出圖像中包含來自輸入圖像的所有元數據(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`
);

總結

以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關文章

  • 垃圾回收器的相關知識點總結

    垃圾回收器的相關知識點總結

    本文是小編在網絡上整理的關于垃圾回收器的相關知識點,很多語言和程序都用的到,有興趣的可以學習下。
    2018-05-05
  • Node.js完整實現博客系統(tǒng)詳解

    Node.js完整實現博客系統(tǒng)詳解

    這篇文章主要介紹了Node.js完整實現一個博客系統(tǒng)的流程,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2022-08-08
  • 一行命令搞定node.js 版本升級

    一行命令搞定node.js 版本升級

    今天,又發(fā)現一個超級簡單的升級node.js的方法。一行命令搞定,省去了重新編譯安裝的過程。
    2014-07-07
  • NestJS核心概念之Middleware中間件創(chuàng)建使用示例

    NestJS核心概念之Middleware中間件創(chuàng)建使用示例

    這篇文章主要為大家介紹了NestJS核心概念之Middleware中間件創(chuàng)建使用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-08-08
  • Node.js中的異步生成器與異步迭代詳解

    Node.js中的異步生成器與異步迭代詳解

    這篇文章主要給大家介紹了關于Node.js中異步生成器與異步迭代的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2021-01-01
  • vscode調試node.js的實現方法

    vscode調試node.js的實現方法

    這篇文章主要介紹了vscode調試node.js的實現方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-03-03
  • nodejs連接ftp上傳下載實現方法詳解【附:踩坑記錄】

    nodejs連接ftp上傳下載實現方法詳解【附:踩坑記錄】

    這篇文章主要介紹了nodejs連接ftp上傳下載實現方法,結合實例形式詳細分析了node.js使用ftp模塊實現針對ftp上傳、下載相關操作的方法,并附帶記錄了傳輸速度慢的解決方法,需要的朋友可以參考下
    2023-04-04
  • 在Ubuntu上安裝最新版本的Node.js

    在Ubuntu上安裝最新版本的Node.js

    Node.js是一個軟件平臺,通常用于構建大規(guī)模的服務器端應用。Node.js使用JavaScript作為其腳本語言,由于其非阻塞I/O設計以及單線程事件循環(huán)機制,使得它可以交付超高的性能。
    2014-07-07
  • node.js配置Token驗證的2種方式總結

    node.js配置Token驗證的2種方式總結

    token驗證,在設計登錄注冊和一些權限接口時發(fā)揮作用,下面這篇文章主要給大家介紹了關于node.js配置Token驗證的2種方式,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下
    2023-02-02
  • pnpm實現依賴包共享和依賴包項目隔離的方法詳解

    pnpm實現依賴包共享和依賴包項目隔離的方法詳解

    pnpm是Node.js的包管理器,它是 npm 的直接替代品,相對于npm和yarn它的優(yōu)點就在于速度快和高效節(jié)省磁盤空間,本文主要講解pnpm相比于npm/yarn如何利用軟硬鏈接來節(jié)省磁盤空間,以及如何實現依賴包共享和依賴包項目隔離的,需要的朋友可以參考下
    2024-05-05

最新評論

应用必备| 额尔古纳市| 鸡泽县| 龙岩市| 金昌市| 洪洞县| 平遥县| 隆德县| 邢台市| 中西区| 襄城县| 兴宁市| 滦南县| 安阳县| 平和县| 武宣县| 龙陵县| 平果县| 夏邑县| 林芝县| 西充县| 重庆市| 芷江| 波密县| 长葛市| 梁山县| 故城县| 灵石县| 武平县| 昌宁县| 武强县| 蕲春县| 巴彦淖尔市| 布尔津县| 甘肃省| 务川| 遵义市| 利辛县| 利川市| 彭州市| 英吉沙县|