很强大,图片转ico库,也可以转换各种图像格式

大家好我是辉子,遇到有用的东西就记录下来,也希望和您成为朋友。关注 公众号: 【罗米笔记】,有更好的笔记会及时更新,

昨天想找下直接在js转ico的库,以后用到项目中,就发现了这个,记录下来留着使用

Sharp库是一个用于处理图像的Node.js库,它提供了一组功能强大且易于使用的API,可以用于读取、写入和转换各种图像格式。Sharp库支持多种常见的图像格式,包括JPEG、PNG、GIF、BMP等,并且可以在不损失质量的情况下对图像进行缩放、旋转、裁剪等操作。此外,Sharp库还支持流式处理,可以在处理大型图像时节省内存。总之,Sharp库是一个非常实用的Node.js图像处理库,可以帮助开发者轻松地完成各种图像处理任务。

是在nodejs环境中使用,主要用在服务器端,可以使用nest进行测试 用法: npm install sharp

js 复制代码
// 转换图片格式并设置大小, 可以转换成多种图片格式 。
const inputImagePath = '/Users/wanghui/Desktop/test/images/1.png';
const outputIcoPath = './1.jpg';
const sharpImage = sharp(inputImagePath);
const resizeImage = sharpImage.resize(200, 200);
await resizeImage.toFile(outputIcoPath);
js 复制代码
// 通过这样的方式进行转化 
const transformer = sharp()
  .resize(200)
  .on('error', function (err) {
    console.log(err);
  });

const readableStream = fs.createReadStream(inputImagePath);
const writableStream = fs.createWriteStream(outputIcoPath);
readableStream.pipe(transformer).pipe(writableStream);
js 复制代码
// 输入生成的图片,buffer格式,可以转成base64输出
await sharp({
  // Create a 300x200 RGBA image with a red background
  create: {
    width: 300,
    height: 200,
    channels: 4,
    background: { r: 255, g: 0, b: 0, alpha: 0.5 },
  },
})
  // Use PNG format
  .png()
  // Convert to a buffer
  .toBuffer();
js 复制代码
// 转化gif为webp
await sharp('./2.gif', { animated: true }).toFile('out.webp');
js 复制代码
// 生成图片
const input = Uint8Array.from([255, 255, 255, 0, 0, 0, 255, 255, 0]); // or Uint8ClampedArray
const image = sharp(input, {
  // because the input does not contain its dimensions or how many channels it has
  // we need to specify it in the constructor options
  raw: {
    width: 3,
    height: 1,
    channels: 3,
  },
});
await image.toFile('./my-two-pixels.png');
js 复制代码
// 生成文字图片
await sharp({
  text: {
    text: `<span foreground="red">Red!</span><span background="cyan">blue</span>`,
    font: 'sans',
    rgba: true,
    dpi: 300,
  },
}).toFile('text_rgba.png');

当然还有很多的用法及参数。可以参照官网。这个适合做工具类的图片转换,当然也可以用到其他的场景中,就看是怎么使用了

github: github.com/lovell/shar...

相关推荐
神膘护体小月半4 小时前
css - 元素背景图由 hover 触发,初次加载时闪动的解决办法
前端·javascript·css
程序员大阳4 小时前
副队长ES6+教程(2)--let 与 const
前端·javascript·es6·const·let·var
syyjhchou4 小时前
自己搭企业内部中转站,怎么让请求更容易命中缓存
人工智能·后端·语言模型·aigc
特立独行的猫A5 小时前
Ionic + 仓颉语言的 cj-tauri 开发框架实战:开发精美移动端 APP
java·后端·python
deli0075 小时前
写满 200GB 后 SSD 为什么掉到 95MB/s?SLC 缓存模型实测
前端
SomeOtherTime5 小时前
Rust集合(AI回答)
开发语言·后端·rust
曦樂~6 小时前
【Web Development】03JavaScript 基础和事件
开发语言·前端·javascript
我不会起名字3226 小时前
req.Seqs[len-1]:空切片防御缺口与 RPC 二次校验
后端·mongodb·go·即时通讯·im·故障排查
deli0076 小时前
HTTPS 的锁是怎么挂上的?TLS 1.3 握手 6 步实测
前端
程序员大阳6 小时前
副队长ES6+教程(1)--ES6+初识
前端·ecmascript·es6