Java BufferedImage 分别获得红色、绿色和蓝色

标签 java bufferedimage

getRGB() 方法返回单个 int。我怎样才能将红色、绿色和蓝色都分别作为 0 到 255 之间的值?

最佳答案

一个像素由一个 4 字节(32 位)整数表示,如下所示:

00000000 00000000 00000000 11111111
^ Alpha  ^Red     ^Green   ^Blue

所以,要获得单个颜色分量,您只需要一点二进制算术:

int rgb = getRGB(...);
int red = (rgb >> 16) & 0x000000FF;
int green = (rgb >>8 ) & 0x000000FF;
int blue = (rgb) & 0x000000FF;

这确实是java.awt.Color类方法:

  553       /**
  554        * Returns the red component in the range 0-255 in the default sRGB
  555        * space.
  556        * @return the red component.
  557        * @see #getRGB
  558        */
  559       public int getRed() {
  560           return (getRGB() >> 16) & 0xFF;
  561       }
  562   
  563       /**
  564        * Returns the green component in the range 0-255 in the default sRGB
  565        * space.
  566        * @return the green component.
  567        * @see #getRGB
  568        */
  569       public int getGreen() {
  570           return (getRGB() >> 8) & 0xFF;
  571       }
  572   
  573       /**
  574        * Returns the blue component in the range 0-255 in the default sRGB
  575        * space.
  576        * @return the blue component.
  577        * @see #getRGB
  578        */
  579       public int getBlue() {
  580           return (getRGB() >> 0) & 0xFF;
  581       }

关于Java BufferedImage 分别获得红色、绿色和蓝色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2615522/

相关文章:

java - 使用 Swing 应用程序框架的组件资源注入(inject)问题

java - maven项目中如何定义常用配置

java - 使用 Java (Swing) 在 JPanel/JFrame 中播放 .wav 声音文件

Java Web 应用程序作为桌面应用程序,我应该选择哪些框架?

java - QueryDsl 不使用 Spring Boot 和 Maven 生成 Q 类

java - 从小程序调用 JS 在 Firefox 和 Chrome 中有效,但在 Safari 中无效

java - 如何在 Android 中使用图像的同时实现正确的 MVP 架构?

Java - 获取缓冲图像的屏幕位置

java - 向灰度 BufferedImage 添加颜色

java - 如何将 BufferedImage 转换为 8 位?