001/* 002Copyright 2006 Jerry Huxtable 003 004Licensed under the Apache License, Version 2.0 (the "License"); 005you may not use this file except in compliance with the License. 006You may obtain a copy of the License at 007 008 http://www.apache.org/licenses/LICENSE-2.0 009 010Unless required by applicable law or agreed to in writing, software 011distributed under the License is distributed on an "AS IS" BASIS, 012WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013See the License for the specific language governing permissions and 014limitations under the License. 015*/ 016 017package com.jhlabs.image; 018 019import java.awt.*; 020import java.awt.image.*; 021 022public class ImageCombiningFilter { 023 024 public int filterRGB(int x, int y, int rgb1, int rgb2) { 025 int a1 = (rgb1 >> 24) & 0xff; 026 int r1 = (rgb1 >> 16) & 0xff; 027 int g1 = (rgb1 >> 8) & 0xff; 028 int b1 = rgb1 & 0xff; 029 int a2 = (rgb2 >> 24) & 0xff; 030 int r2 = (rgb2 >> 16) & 0xff; 031 int g2 = (rgb2 >> 8) & 0xff; 032 int b2 = rgb2 & 0xff; 033 int r = PixelUtils.clamp(r1 + r2); 034 int g = PixelUtils.clamp(r1 + r2); 035 int b = PixelUtils.clamp(r1 + r2); 036 return (a1 << 24) | (r << 16) | (g << 8) | b; 037 } 038 039 public ImageProducer filter(Image image1, Image image2, int x, int y, int w, int h) { 040 int[] pixels1 = new int[w * h]; 041 int[] pixels2 = new int[w * h]; 042 int[] pixels3 = new int[w * h]; 043 PixelGrabber pg1 = new PixelGrabber(image1, x, y, w, h, pixels1, 0, w); 044 PixelGrabber pg2 = new PixelGrabber(image2, x, y, w, h, pixels2, 0, w); 045 try { 046 pg1.grabPixels(); 047 pg2.grabPixels(); 048 } catch (InterruptedException e) { 049 System.err.println("interrupted waiting for pixels!"); 050 return null; 051 } 052 if ((pg1.status() & ImageObserver.ABORT) != 0) { 053 System.err.println("image fetch aborted or errored"); 054 return null; 055 } 056 if ((pg2.status() & ImageObserver.ABORT) != 0) { 057 System.err.println("image fetch aborted or errored"); 058 return null; 059 } 060 061 for (int j = 0; j < h; j++) { 062 for (int i = 0; i < w; i++) { 063 int k = j * w + i; 064 pixels3[k] = filterRGB(x+i, y+j, pixels1[k], pixels2[k]); 065 } 066 } 067 return new MemoryImageSource(w, h, pixels3, 0, w); 068 } 069 070}