View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.commons.imaging.formats.png;
18  
19  import org.apache.commons.imaging.ImageReadException;
20  
21  class BitParser {
22      private final byte[] bytes;
23      private final int bitsPerPixel;
24      private final int bitDepth;
25  
26      public BitParser(final byte[] bytes, final int bitsPerPixel, final int bitDepth) {
27          this.bytes = bytes; // TODO clone?
28          this.bitsPerPixel = bitsPerPixel;
29          this.bitDepth = bitDepth;
30      }
31  
32      public int getSample(final int pixelIndexInScanline, final int sampleIndex)
33              throws ImageReadException {
34          final int pixelIndexBits = bitsPerPixel * pixelIndexInScanline;
35          final int sampleIndexBits = pixelIndexBits + (sampleIndex * bitDepth);
36          final int sampleIndexBytes = sampleIndexBits >> 3;
37  
38          if (bitDepth == 8) {
39              return 0xff & bytes[sampleIndexBytes];
40          } else if (bitDepth < 8) {
41              int b = 0xff & bytes[sampleIndexBytes];
42              final int bitsToShift = 8 - ((pixelIndexBits & 7) + bitDepth);
43              b >>= bitsToShift;
44  
45              final int bitmask = (1 << bitDepth) - 1;
46              return b & bitmask;
47          } else if (bitDepth == 16) {
48              return (((0xff & bytes[sampleIndexBytes]) << 8) | (0xff & bytes[sampleIndexBytes + 1]));
49          }
50  
51          throw new ImageReadException("PNG: bad BitDepth: " + bitDepth);
52      }
53  
54      public int getSampleAsByte(final int pixelIndexInScanline, final int sampleIndex)
55              throws ImageReadException {
56          int sample = getSample(pixelIndexInScanline, sampleIndex);
57  
58          final int rot = 8 - bitDepth;
59          if (rot > 0) {
60              sample = sample * 255 / ((1 << bitDepth) - 1);
61          } else if (rot < 0) {
62              sample >>= -rot;
63          }
64  
65          return 0xff & sample;
66      }
67  }