001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.commons.imaging.formats.png.scanlinefilters; 018 019import java.io.IOException; 020 021import org.apache.commons.imaging.ImagingException; 022 023public class ScanlineFilterPaeth implements ScanlineFilter { 024 private final int bytesPerPixel; 025 026 public ScanlineFilterPaeth(final int bytesPerPixel) { 027 this.bytesPerPixel = bytesPerPixel; 028 } 029 030 private int paethPredictor(final int a, final int b, final int c) { 031 // ; a = left, b = above, c = upper left 032 final int p = a + b - c; // ; initial estimate 033 final int pa = Math.abs(p - a); // ; distances to a, b, c 034 final int pb = Math.abs(p - b); 035 final int pc = Math.abs(p - c); 036 // ; return nearest of a,b,c, 037 // ; breaking ties in order a,b,c. 038 if (pa <= pb && pa <= pc) { 039 return a; 040 } 041 if (pb <= pc) { 042 return b; 043 } 044 return c; 045 } 046 047 @Override 048 public void unfilter(final byte[] src, final byte[] dst, final byte[] up) throws ImagingException, IOException { 049 for (int i = 0; i < src.length; i++) { 050 int left = 0; 051 final int prevIndex = i - bytesPerPixel; 052 if (prevIndex >= 0) { 053 left = dst[prevIndex]; 054 } 055 056 int above = 0; 057 if (up != null) { 058 above = up[i]; 059 } 060 // above = 255; 061 062 int upperLeft = 0; 063 if (prevIndex >= 0 && up != null) { 064 upperLeft = up[prevIndex]; 065 } 066 // upperLeft = 255; 067 068 final int paethPredictor = paethPredictor(0xff & left, 0xff & above, 0xff & upperLeft); 069 070 dst[i] = (byte) ((src[i] + paethPredictor) % 256); 071 // dst[i] = (byte) ((src[i] + paethPredictor) ); 072 // dst[i] = src[i]; 073 074 // dst[i] = (byte) 0; 075 } 076 } 077}