注册 登录
n/program · 2025-01-26 · 379 次浏览
u/Str荣誉会员王者
n/programu/Str 荣誉会员 · 2025-01-26

Nodejs 有没有什么库能把图片 LO-FI 化

我想的是把图片每2x4(2是底)为一块读取,然后提取出里面对比度最大的两个值

然后我用了 kmeans-plusplus ,但是这个库居然有语法错误(让gpt帮他修了)

然后我输入了这个:
Image description~~

这是他的输出:
Image description~~

这是我的代码

```
const Jimp = require('jimp');
const { Clusterer } = require('kmeans-plusplus');

async function lofiImage(imagePath, outputPath) {
try {
const image = await Jimp.read(imagePath);
let width = image.bitmap.width;
let height = image.bitmap.height;

    // 填充白色像素,使尺寸可以被 2x4 整除
    const paddingWidth = (2 - (width % 2)) % 2;
    const paddingHeight = (4 - (height % 4)) % 4;
    image.resize(width + paddingWidth, height + paddingHeight);
    width += paddingWidth;
    height += paddingHeight;


    const blockSize = { width: 2, height: 4 };
    const lofiData = [];

    for (let y = 0; y < height; y += blockSize.height) {
        for (let x = 0; x < width; x += blockSize.width) {
            const block = [];
            for (let j = y; j < y + blockSize.height; j++) {
                for (let i = x; i < x + blockSize.width; i++) {
                    const color = Jimp.intToRGBA(image.getPixelColor(i, j));
                    block.push([color.r, color.g, color.b]);
                }
            }

             console.log(block);
            // KMeans 聚类
            const clusterer = new Clusterer(block);
            const kmeansResult = clusterer.clusterize(3);
            const dominantColors = kmeansResult.centroids;

            // 颜色简化
            const reducedBlock = block.map(pixel => {
                const distances = dominantColors.map(color => {
                    const diffR = pixel[0] - color[0];
                    const diffG = pixel[1] - color[1];
                    const diffB = pixel[2] - color[2];
                    return diffR * diffR + diffG * diffG + diffB * diffB;
                });
                const closestColorIndex = distances.indexOf(Math.min(...distances));
                return dominantColors[closestColorIndex];
            });

            lofiData.push({ x, y, colors: dominantColors, reducedBlock });
        }
    }

    //  (你需要实现将 lofiData 转换为图片或其他格式的输出)
    //  此处仅打印 dominantColors,  你需要根据需求编写图片生成部分
    console.log(lofiData);


    // 创建一个新的 Jimp 图片,并填充颜色
    const outputImage = new Jimp(width, height, 0xFFFFFFFF); // 白色背景
    for (const { x, y, reducedBlock } of lofiData) {
      let k=0;
      for (let j = y; j < y + blockSize.height; j++) {
          for (let i = x; i < x + blockSize.width; i++) {
              const color = reducedBlock[k];
              outputImage.setPixelColor(Jimp.rgbaToInt(color[0], color[1], color[2], 255), i, j);
              k++;
          }
      }
    }
    await outputImage.writeAsync(outputPath);

} catch (error) {
    console.error('Error processing image:', error);
}

}

// 使用示例
lofiImage('input.png', 'output.png')
.catch(error => {
console.error("An error occurred:", error);
});

```

这是修复后的库文件(把后缀都改成 .js 然后覆盖 node_modules\kmeans-plusplus\dist )

~~[upl-file uuid=d1ab3b05-205d-4b8a-9609-7aebdbf21211 size=1kB]utils.txt[/upl-file]
[upl-file uuid=1172d386-bbcd-4547-98e3-498560965b74 size=4kB]~~index.bin[/upl-file]



对了jimp要装老版本的

0
4
登录后参与讨论。

4 条回复

排序
  1. Str 荣誉会员 王者 楼主 2025-01-26

    似乎老版本jimp处理png会出现问题,但是老版本jimp的代码不能直接用于新版本

    0
  2. dokke 🐸荣誉会员 钻石 2025-01-26

    这个不是看下新版本的语法就可以了嘛

    0
  3. awq 黄金 不离不弃 2025-01-26

    Image description~~
    https://www.digitalocean.com/community/tutorials/how-to-process-images-in-node-js-with-sharp
    Sharp

    描述: Sharp是一个高性能的Node.js图像处理库,支持多种图像格式的转换和处理。虽然它主要用于图像的缩放和压缩,但您可以通过调整图像的质量和颜色来实现低保真效果。
    使用示例:

    Image description
    Jimp
    Image description

    Canvas
    Image description~~

    0
  4. Str 荣誉会员 王者 楼主 2025-01-28

    也是解决了,手搓了个函数

    kmeans-plusplus库没用

    0