软件编程
位置:首页>> 软件编程>> java编程>> Java png图片修改像素rgba值的操作

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

作者:hello_world_j  发布时间:2022-08-11 06:57:21 

标签: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的区别

  • ARGB 是一种色彩模式,也就是RGB色彩模式附加上Alpha(透明度)通道,常见于32位位图的存储结构。

  • RGB 色彩模式是工业界的一种颜色标准,是通过对红(R)、绿(G)、蓝(B)三个颜色通道的变化以及它们相互之间的叠加来得到各式各样的颜色的,RGB即是代表红、绿、蓝三个通道的颜色,这个标准几乎包括了人类视力所能感知的所有颜色,是目前运用最广的颜色系统之一。

  • RGBA 是代表Red(红色) Green(绿色) Blue(蓝色)和 Alpha的色彩空间。虽然它有的时候被描述为一个颜色空间,但是它其实仅仅是RGB模型的附加了额外的信息。采用的颜色是RGB,可以属于任何一种RGB颜色空间,但是Catmull和Smith在1971至1972年间提出了这个不可或缺的alpha数值,使得alpha渲染和alpha合成变得可能。提出者以alpha来命名是源于经典的线性插值方程αA + (1-α)B所用的就是这个希腊字母。

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

来源:https://blog.csdn.net/hello_world_j/article/details/80724626

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com