AbstractWebPChunk readChunk()

in src/main/java/org/apache/commons/imaging/formats/webp/WebPImageParser.java [83:129]


        AbstractWebPChunk readChunk() throws ImagingException, IOException {
            while (sizeCount < fileSize) {
                final int type = read4Bytes("Chunk Type", is, "Not a valid WebP file", ByteOrder.LITTLE_ENDIAN);
                final int payloadSize = read4Bytes("Chunk Size", is, "Not a valid WebP file", ByteOrder.LITTLE_ENDIAN);
                if (payloadSize < 0) {
                    throw new ImagingException("Chunk Payload is too long:" + payloadSize);
                }
                final boolean padding = payloadSize % 2 != 0;
                final int chunkSize = SafeOperations.add(8, padding ? 1 : 0, payloadSize);

                if (firstChunk) {
                    firstChunk = false;
                    if (type != WebPChunkType.VP8.value && type != WebPChunkType.VP8L.value && type != WebPChunkType.VP8X.value) {
                        throw new ImagingException("First Chunk must be VP8, VP8L or VP8X");
                    }
                }

                if (chunkTypes != null) {
                    boolean skip = true;
                    for (final WebPChunkType t : chunkTypes) {
                        if (t.value == type) {
                            skip = false;
                            break;
                        }
                    }
                    if (skip) {
                        skipBytes(is, payloadSize + (padding ? 1 : 0));
                        sizeCount = SafeOperations.add(sizeCount, chunkSize);
                        continue;
                    }
                }

                final byte[] bytes = readBytes("Chunk Payload", is, payloadSize);
                final AbstractWebPChunk chunk = WebPChunkType.makeChunk(type, payloadSize, bytes);
                if (padding) {
                    skipBytes(is, 1);
                }

                sizeCount = SafeOperations.add(sizeCount, chunkSize);
                return chunk; // NOPMD How can we do this better?
            }

            if (firstChunk) {
                throw new ImagingException("No WebP chunks found");
            }
            return null;
        }