当我们基于网络的应用程序爱上 webp 图像格式时,我发现自己需要一种可以解码它的方法或库,
我已经编写了这段代码,但它只错过了本机解码器(我更喜欢它是一个 jar lib):
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;
}
Run Code Online (Sandbox Code Playgroud)
在所有可能的搜索中,这个是最好和最简单的:
https://bitbucket.org/luciad/webp-imageio
不是完整的java实现,但与其他实现相比非常容易