簡體   English   中英

在 NodeJS 上轉換內存中的文件圖像

[英]Convert in-memory File image, on NodeJS

我有一個后端接收 JPEG 圖像作為文件object (image/jpeg)。
我需要將 JPEG 圖像轉換為 WebP。
生成的 WebP 必須是文件 object (image/webp)。

例如:

文件 object(圖片/jpeg)=> 到 stream => 到 webp => 到文件 object(圖片/webp)

我已經將 stream 轉換為 webp,但我找不到任何關於如何將其轉換回文件的信息(或者至少是具有與文件完全相同的屬性/方法的修改后的 Blob)。

需要說明的是,這就是我所說的File object 的意思:

File {
  _events: [Object: null prototype] {},
  _eventsCount: 0,
  _maxListeners: undefined,
  size: 38718,
  path: '/var/folders/17/lk7n1gkd6m54kzmr0g7kqdn80000gp/T/upload_62e5a3f95bccb09b605722a21737cbc3',
  name: '09_scan_qr.jpg',
  type: 'image/jpeg',
  hash: null,
  lastModifiedDate: 2023-01-05T03:37:24.134Z,
  _writeStream: WriteStream {
    fd: null,
    path: '/var/folders/17/lk7n1gkd6m54kzmr0g7kqdn80000gp/T/upload_62e5a3f95bccb09b605722a21737cbc3',
    flags: 'w',
    mode: 438,
    start: undefined,
    pos: undefined,
    bytesWritten: 38718,
    closed: false,
    _writableState: WritableState {...},
    _events: [Object: null prototype] {},
    _eventsCount: 0,
    _maxListeners: undefined,
    [Symbol(kFs)]: {...}
}

我想到了。 至少就我而言,解決方案是這樣的:

const sharp = require('sharp');
const fse = require('fs-extra');

// This represents the File object that needs to be converted
let file = FILE_OBJECT;

// Convert the file referenced by the File object to webp
await fse.createReadStream(file.path).pipe(sharp().webp()).toFile(file.path);

// Update the properties of the File object to match the new file on-disk
file.name = file.name.replace(/\.(jpe?g|gif|png|tiff)$/, ".webp"); 
file.size = fse.statSync(file.path).size;
file.type = 'image/webp';

在此之后, file是一個文件(webp),我的意思是引用一個 webp 圖像的文件 object

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM