使用字节数组设置 BufferedImage 的像素颜色

Setting the pixel color of BufferedImage using byte array

我已经使用以下代码将图像转换为数组:

BufferedImage bufferedImage = null;       
try {
   bufferedImage = ImageIO.read(new File("name.jpeg"));
} catch (IOException e) { }

byte[] b = ((DataBufferByte) bufferedImage.getRaster().getDataBuffer()).getData();

该数组每个像素包含 3 个字节。我的问题是如何将单个像素设置为白色,因为问题是 Java 中的字节已签名,因此只允许 -128 和 127 之间的值。但我想将我的像素设置为 255、255、255 . 如果我将所有三个值都设置为 127,则像素变为灰色。

将值设置为 -1,即无符号 255 字节的 signed representation

或者如果你想让代码更明显,(byte)255 也可以。

您还可以使用 Java 内置的 ByteBuffer 来帮助管理此类内容。不确定您是否需要专门拥有一个 byte[] 数组,但它是您可以利用的很酷的对象。