欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

透明图片去掉透明色

程序员文章站 2022-04-09 09:15:24
...
package pngConvert;

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

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

public class Transfer {

	
	public static byte[] transferAlpha() {

		   ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		   File file = new File("D:/1.png");
		   InputStream is;
		   try {
		    is = new FileInputStream(file);//如果是MultipartFile类型,那么自身也有转换成流的方法:is = file.getInputStream();
		    BufferedImage bi=ImageIO.read(is);
		    Image image=(Image)bi;
		    ImageIcon imageIcon = new ImageIcon(image);
		    BufferedImage bufferedImage = new BufferedImage(imageIcon
		      .getIconWidth(), imageIcon.getIconHeight(),
		      BufferedImage.TYPE_INT_RGB);
		    
		    
		    Graphics2D g2D = (Graphics2D) bufferedImage.getGraphics();
		    g2D.drawImage(imageIcon.getImage(), 0, 0, imageIcon
		      .getImageObserver());
		    int alpha = 0;
		    for (int j1 = bufferedImage.getMinY(); j1 < bufferedImage
		      .getHeight(); j1++) {
		     for (int j2 = bufferedImage.getMinX(); j2 < bufferedImage
		       .getWidth(); j2++) {
		      int rgb = bufferedImage.getRGB(j2, j1);
		    
		      int a=(rgb & 0xff000000 ) >> 24 ;
		      int R =(rgb & 0x00ff0000 ) >> 16 ;
		      int G= (rgb & 0x0000ff00 ) >> 8 ;
		      int B= (rgb & 0xff );
		      
		      if(R==0&&G==0&&B==0) {
		    	  rgb=rgb|0x00ffffff;
		      }

		      bufferedImage.setRGB(j2, j1, rgb);
		      
		      
		     }
		    }
             
		    g2D.drawImage(bufferedImage, 0, 0, imageIcon.getImageObserver());
		    ImageIO.write(bufferedImage, "png", new File("D:/win.png"));//直接输出文件

		   // ImageIO.write(bufferedImage, "png", byteArrayOutputStream);//转换成byte数组
		   } catch (Exception e) {
		       e.printStackTrace();
		   }finally{
		   
		   }
		   return byteArrayOutputStream.toByteArray();
		}
		
	public static void main(String[] args) throws IOException {
		
		   transferAlpha();
	}

}

相关标签: 图片处理