---
title: "把图片背景［白色］设置透明"
author: "philip01"
date: "2009-06-29T17:09:33Z"
tags: []
slug: "untitled"
draft: false
lastmod: "2009-06-30T12:48:35Z"
id: 417123
url: "https://philip01.iteye.com/blog/417123"
---

package com.goldgrid.socket.client;

import java.awt.Graphics2D;  
import java.awt.Image;  
import java.awt.image.BufferedImage;  
import java.io.ByteArrayOutputStream;  
import java.io.File;

import javax.imageio.ImageIO;  
import javax.swing.ImageIcon;

import org.apache.log4j.Logger;

public class Alpha {  
   
    protected static Logger logger = Logger.getLogger(ClientSocket.class);

 public byte\[] transferAlpha(Image image) {

  ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

  try {  
   ImageIcon imageIcon = new ImageIcon(image);  
   BufferedImage bufferedImage = new BufferedImage(imageIcon  
     .getIconWidth(), imageIcon.getIconHeight(),  
     BufferedImage.TYPE\_4BYTE\_ABGR);  
   Graphics2D g2D = (Graphics2D) bufferedImage.getGraphics();  
   g2D.drawImage(imageIcon.getImage(), 0, 0, imageIcon  
     .getImageObserver());  
   int alpha = 0;  
   for (int j1 = bufferedImage.getMinY(); j1 &lt; bufferedImage  
     .getHeight(); j1++) {  
    for (int j2 = bufferedImage.getMinX(); j2 &lt; bufferedImage  
      .getWidth(); j2++) {  
     int rgb = bufferedImage.getRGB(j2, j1);  
      
     int R =(rgb & 0xff0000 ) &gt;&gt; 16 ;  
     int G= (rgb & 0xff00 ) &gt;&gt; 8 ;  
     int B= (rgb & 0xff );  
     if(((255-R)&lt;30) && ((255-G)&lt;30) && ((255-B)&lt;30)){  
      rgb = ((alpha + 1) &lt;&lt; 24) | (rgb & 0x00ffffff);  
     }

     bufferedImage.setRGB(j2, j1, rgb);

    }  
   }

   g2D.drawImage(bufferedImage, 0, 0, imageIcon.getImageObserver());  
   //ImageIO.write(bufferedImage, "png", new File("d:/test.png.png"));

   ImageIO.write(bufferedImage, "png", byteArrayOutputStream);  
  } catch (Exception e) {  
   logger.error(e.toString());  
  }finally{  
     
  }

  return byteArrayOutputStream.toByteArray();

 }  
}