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.github.sarxos.webcam.util.jh; 018 019import java.awt.image.BufferedImage; 020import java.awt.image.WritableRaster; 021 022 023public class JHGrayFilter extends JHFilter { 024 025 protected boolean canFilterIndexColorModel = true; 026 027 @Override 028 public BufferedImage filter(BufferedImage src, BufferedImage dst) { 029 030 int width = src.getWidth(); 031 int height = src.getHeight(); 032 int type = src.getType(); 033 034 WritableRaster srcRaster = src.getRaster(); 035 036 if (dst == null) { 037 dst = createCompatibleDestImage(src, null); 038 } 039 040 WritableRaster dstRaster = dst.getRaster(); 041 042 int[] inPixels = new int[width]; 043 for (int y = 0; y < height; y++) { 044 if (type == BufferedImage.TYPE_INT_ARGB) { 045 srcRaster.getDataElements(0, y, width, 1, inPixels); 046 for (int x = 0; x < width; x++) { 047 inPixels[x] = filterRGB(inPixels[x]); 048 } 049 dstRaster.setDataElements(0, y, width, 1, inPixels); 050 } else { 051 src.getRGB(0, y, width, 1, inPixels, 0, width); 052 for (int x = 0; x < width; x++) { 053 inPixels[x] = filterRGB(inPixels[x]); 054 } 055 dst.setRGB(0, y, width, 1, inPixels, 0, width); 056 } 057 } 058 059 return dst; 060 } 061 062 private int filterRGB(int rgb) { 063 int a = rgb & 0xff000000; 064 int r = (rgb >> 16) & 0xff; 065 int g = (rgb >> 8) & 0xff; 066 int b = rgb & 0xff; 067 rgb = (r * 77 + g * 151 + b * 28) >> 8; // NTSC luma 068 return a | (rgb << 16) | (rgb << 8) | rgb; 069 } 070}