Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Webp support for java

Tags:

java

webp

As our network based applications fall in love with webp image formats, I found my self in need of a method or a lib which can decode it,

I have written this piece of code, but it only misses the native decoder(how ever I prefer it to be a 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;
}
like image 312
Reza Avatar asked Oct 18 '22 20:10

Reza


1 Answers

Please use OpenCV. I use maven and org.openpnp:opencv:4.5.1-2. All it takes to encode an image that is stored in a Mat is:

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);
}

I am converting it to byte [] arrays since I store it mostly in S3 and DB and rather sheldom in the filesystem.

like image 151
Martin Kersten Avatar answered Oct 21 '22 03:10

Martin Kersten