2014년 10월 27일 월요일

JAVA 이미지의 색 마스크 처리.

//투명처리할 image를 파라미터로 넣고, 색의 범위를 주면, 그 색은 마스크처리를 해준다.
 protected Image TransformColorToTransparency( BufferedImage image, Color c1, Color c2 )
 {
  final int r1 = c1.getRed();
  final int g1 = c1.getGreen();
  final int b1 = c1.getBlue();
  final int r2 = c2.getRed();
  final int g2 = c2.getGreen();
  final int b2 = c2.getBlue();
 
  ImageFilter filter = new RGBImageFilter() {
   public int filterRGB(int x, int y, int rgb) {
    // TODO Auto-generated method stub
    int r = ( rgb & 0xFF0000 ) >> 16;
    int g = ( rgb & 0xFF00 ) >> 8;
    int b = ( rgb & 0xFF );
    if( r >= r1 && r <= r2 && g >= g1 && g <= g2 && b >= b1 && b <= b2 )
    {
     return rgb & 0xFFFFFF;
    }
    return rgb;
   }
  };
 
  ImageProducer ip = new FilteredImageSource( image.getSource(), filter );
  return Toolkit.getDefaultToolkit().createImage( ip );
 }

 protected BufferedImage ImageToBufferedImage( Image image, int width, int height )
 {
  BufferedImage dest = new BufferedImage( width, height, BufferedImage.TYPE_INT_ARGB );
  Graphics2D g2 = dest.createGraphics();
  g2.drawImage( image, 0, 0, null );
  g2.dispose();
  return dest;
 }

사용예)
  image = Toolkit.getDefaultToolkit().createImage( "C:/ktnet/sign/cmpnSign/sign.jpg" );
  mt = new MediaTracker( new Button() );
     mt.addImage( image, 0 );
     mt.waitForAll();
   
  BufferedImage biTmp = ImageToBufferedImage( image, image.getWidth( null ), image.getHeight( null ) );
  image = TransformColorToTransparency( biTmp, new Color( 230, 230, 230 ), new Color( 255, 255, 255 ) );
  mt = new MediaTracker( new Button() );
     mt.addImage( image, 0 );
     mt.waitForAll();
   
  graphics.drawImage( image, (int)( 350f * 1.75f ) , (int)(344f * 1.7f), 235, 95, null );

댓글 없음: