gpt4 book ai didi

java - Webp 对 java 的支持

转载 作者:行者123 更新时间:2023-11-30 06:59:25 24 4
gpt4 key购买 nike

随着我们基于网络的应用程序爱上 webp 图像格式,我发现自己需要一种可以对其进行解码的方法或库,

我已经编写了这段代码,但它只错过了 native 解码器(但我更喜欢它是一个 jar 库):

public BufferedImage decodeWebP(byte[] encoded, int w, int h) {
int[] width = new int[]{w};
int[] height = new int[]{h};

byte[] decoded = decodeRGBAnative(encoded); //here is the missing part ,
if (decoded.length == 0) return null;

int[] pixels = new int[decoded.length / 4];
ByteBuffer.wrap(decoded).asIntBuffer().get(pixels);

BufferedImage bufferedImage = new BufferedImage(width[0], height[0], BufferedImage.TYPE_INT_RGB);

// bufferedImage.setRGB(x, y, your_value);

int BLOCK_SIZE = 3;

for(int r=0; r< height[0]; r++) {
for (int c = 0; c < width[0]; c++) {
int index = r * width[0] * BLOCK_SIZE + c * BLOCK_SIZE;
int red = pixels[index] & 0xFF;
int green = pixels[index + 1] & 0xFF;
int blue = pixels[index + 2] & 0xFF;
int rgb = (red << 16) | (green << 8) | blue;
bufferedImage.setRGB(c, r, rgb);
}
}
return bufferedImage;
}

最佳答案

请使用OpenCV。我使用 Maven 和 org.openpnp:opencv:4.5.1-2。对存储在 Mat 中的图像进行编码所需的全部操作是:

public static byte [] encodeWebp(Mat image, int quality) {
MatOfInt parameters = new MatOfInt(Imgcodecs.IMWRITE_WEBP_QUALITY, quality);
MatOfByte output = new MatOfByte();
if(Imgcodecs.imencode(".webp", image, output, parameters))
return output.toArray();
else
throw new IllegalStateException("Failed to encode the image as webp with quality " + quality);
}

我将其转换为 byte [] 数组,因为我主要将其存储在 S3 和 DB 中,而不是存储在文件系统中。

关于java - Webp 对 java 的支持,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41185807/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com