亲宝软件园·资讯

展开

png图片修改像素rgba值 Java png图片修改像素rgba值的操作

hello_world_j 人气:0
想了解Java png图片修改像素rgba值的操作的相关内容吗,hello_world_j在本文为您仔细讲解png图片修改像素rgba值的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Java图片,png图片,像素rgba值,下面大家一起来学习吧。

Java png图片修改像素rgba值

import javax.imageio.ImageIO; 
import javax.swing.ImageIcon;
import java.awt.*; 
import java.awt.image.BufferedImage;
import java.io.File; 
public class  ReadColorTest { 
    public static void setAlpha(String os) {
                try {
                  ImageIcon imageIcon = new ImageIcon(os);
                  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());
                  for (int j1 = bufferedImage.getMinY(); j1 < bufferedImage.getHeight(); j1++) {
                    for (int j2 = bufferedImage.getMinX(); j2 < bufferedImage.getWidth(); j2++) {
                      int pixel = bufferedImage.getRGB(j2, j1);//j2横坐标,j1竖坐标
                      int[]   rgb = new int[3];
                      rgb[0] = (pixel & 0x00ff0000) >> 16;//按位与获取red然后右移
                      rgb[1] = (pixel & 0x0000ff00) >> 8;//..获取green...
                      rgb[2] = (pixel & 0x000000ff);
                      int a=(pixel & 0xff000000)>>>24;//无符号右移获取alpha值
                      if(comp(rgb[0],rgb[1],rgb[2])||a==0) {
                    	  pixel = pixel | 0xffffffff;//透明或偏向白色射为白色
                      }else {
                    	  pixel = (pixel & 0xff000000)| 0xff000000;//否则为黑色
                      }
                      bufferedImage.setRGB(j2, j1, pixel);
                    }
                    System.out.println();
                  }
                  g2D.drawImage(bufferedImage, 0, 0, imageIcon.getImageObserver());
                  ImageIO.write(bufferedImage, "png",  new File("D:\\2.png"));
                }
                catch (Exception e) {
                  e.printStackTrace();
                }
    }
    public static boolean comp(int r,int g,int b) {//判断二值化为黑还是白,true为白,false为黑
    	int i = 0;
    	if(r>200) {
    		i++;
    	}
    	if(g>200) {
    		i++;
    	}
    	if(b>200) {
    		i++;
    	}
    	if(i>=2) {
    		return true;
    	}else {
    		return false;
    	}
    }
       
    public static void main(String[] args) throws Exception { 
        setAlpha("H:\\Test\\3.png");  
    } 
}

ARGB与RGB、RGBA的区别

PNG是一种使用RGBA的图像格式。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

加载全部内容

相关教程
猜你喜欢
用户评论