1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.imaging.formats.png.chunks;
18
19 import java.nio.charset.StandardCharsets;
20
21 import org.apache.commons.imaging.ImagingException;
22 import org.apache.commons.imaging.common.BinaryFunctions;
23
24 public class PngChunkScal extends PngChunk {
25
26 private final double unitsPerPixelXAxis;
27 private final double unitsPerPixelYAxis;
28 private final int unitSpecifier;
29
30 public PngChunkScal(final int length, final int chunkType, final int crc, final byte[] bytes) throws ImagingException {
31 super(length, chunkType, crc, bytes);
32
33 unitSpecifier = bytes[0];
34 if (getUnitSpecifier() != 1 && getUnitSpecifier() != 2) {
35 throw new ImagingException("PNG sCAL invalid unit specifier: " + getUnitSpecifier());
36 }
37
38 final int separator = BinaryFunctions.findNull(bytes, "PNG sCAL x and y axis value separator not found.");
39 final int xIndex = 1;
40 final String xStr = new String(bytes, xIndex, separator - 1, StandardCharsets.ISO_8859_1);
41 unitsPerPixelXAxis = toDouble(xStr);
42
43 final int yIndex = separator + 1;
44 if (yIndex >= length) {
45 throw new ImagingException("PNG sCAL chunk missing the y axis value.");
46 }
47
48 final String yStr = new String(bytes, yIndex, length - yIndex, StandardCharsets.ISO_8859_1);
49 unitsPerPixelYAxis = toDouble(yStr);
50 }
51
52 public int getUnitSpecifier() {
53 return unitSpecifier;
54 }
55
56 public double getUnitsPerPixelXAxis() {
57 return unitsPerPixelXAxis;
58 }
59
60 public double getUnitsPerPixelYAxis() {
61 return unitsPerPixelYAxis;
62 }
63
64 private double toDouble(final String str) throws ImagingException {
65 try {
66 return Double.parseDouble(str);
67 } catch (final NumberFormatException e) {
68 throw new ImagingException("PNG sCAL error reading axis value - " + str);
69 }
70 }
71 }