1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.commons.imaging.formats.png;
19
20 import static org.junit.jupiter.api.Assertions.assertFalse;
21 import static org.junit.jupiter.api.Assertions.assertThrows;
22 import static org.junit.jupiter.api.Assertions.assertTrue;
23
24 import java.awt.image.BufferedImage;
25 import java.io.ByteArrayOutputStream;
26 import java.io.IOException;
27
28 import org.apache.commons.imaging.ImageInfo;
29 import org.apache.commons.imaging.common.AllocationRequestException;
30 import org.junit.jupiter.api.Test;
31
32 public class PngImageParserTest extends AbstractPngTest {
33
34 private static byte[] getPngImageBytes(final BufferedImage image, final PngImagingParameters params) throws IOException {
35 try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
36 new PngWriter().writeImage(image, os, params, null);
37 return os.toByteArray();
38 }
39 }
40
41 @Test
42 public void testGetImageSize() {
43 final byte[] bytes = {
44
45 (byte) 0x89, 'P', 'N', 'G', '\r', '\n', 0x1A, '\n',
46
47 (byte) 0b0111_1111, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF - 10,
48
49 'I', 'H', 'D', 'R', };
50 assertThrows(AllocationRequestException.class, () -> new PngImageParser().getImageSize(bytes));
51 }
52
53 @Test
54 public void testNoPalette() throws IOException {
55 final BufferedImage image = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
56 image.setRGB(1, 1, 0x00FFffFF);
57 final PngImagingParameters params = new PngImagingParameters();
58
59 final byte[] bytes = getPngImageBytes(image, params);
60 final ImageInfo imageInfo = new PngImageParser().getImageInfo(bytes, null);
61 assertFalse(imageInfo.usesPalette());
62 }
63
64 @Test
65 public void testPalette() throws IOException {
66 final BufferedImage image = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
67 image.setRGB(1, 1, 0x00FFffFF);
68 final PngImagingParameters params = new PngImagingParameters();
69 params.setForceIndexedColor(true);
70
71 final byte[] bytes = getPngImageBytes(image, params);
72 final ImageInfo imageInfo = new PngImageParser().getImageInfo(bytes, null);
73 assertTrue(imageInfo.usesPalette());
74 }
75 }