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.scanlinefilters;
18  
19  import java.io.IOException;
20  
21  import org.apache.commons.imaging.ImagingException;
22  
23  public class ScanlineFilterPaeth implements ScanlineFilter {
24      private final int bytesPerPixel;
25  
26      public ScanlineFilterPaeth(final int bytesPerPixel) {
27          this.bytesPerPixel = bytesPerPixel;
28      }
29  
30      private int paethPredictor(final int a, final int b, final int c) {
31          // ; a = left, b = above, c = upper left
32          final int p = a + b - c; // ; initial estimate
33          final int pa = Math.abs(p - a); // ; distances to a, b, c
34          final int pb = Math.abs(p - b);
35          final int pc = Math.abs(p - c);
36          // ; return nearest of a,b,c,
37          // ; breaking ties in order a,b,c.
38          if (pa <= pb && pa <= pc) {
39              return a;
40          }
41          if (pb <= pc) {
42              return b;
43          }
44          return c;
45      }
46  
47      @Override
48      public void unfilter(final byte[] src, final byte[] dst, final byte[] up) throws ImagingException, IOException {
49          for (int i = 0; i < src.length; i++) {
50              int left = 0;
51              final int prevIndex = i - bytesPerPixel;
52              if (prevIndex >= 0) {
53                  left = dst[prevIndex];
54              }
55  
56              int above = 0;
57              if (up != null) {
58                  above = up[i];
59              }
60              // above = 255;
61  
62              int upperLeft = 0;
63              if (prevIndex >= 0 && up != null) {
64                  upperLeft = up[prevIndex];
65              }
66              // upperLeft = 255;
67  
68              final int paethPredictor = paethPredictor(0xff & left, 0xff & above, 0xff & upperLeft);
69  
70              dst[i] = (byte) ((src[i] + paethPredictor) % 256);
71              // dst[i] = (byte) ((src[i] + paethPredictor) );
72              // dst[i] = src[i];
73  
74              // dst[i] = (byte) 0;
75          }
76      }
77  }