【发布时间】:2013-09-28 23:22:23
【问题描述】:
我无法访问 BufferedImage 中的单个像素。我的图像是二进制的,只有黑色或白色。这意味着图像的每个字节包含 8 个像素(每像素 1 位)。
为了确保正确索引图像,我编写了一个快速测试将所有像素设置为 1(黑色):
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.io.File;
public class ImageTest {
public static void main(String... args) throws Exception {
File input = new File("stripes.bmp");
final BufferedImage image = ImageIO.read(input);
System.out.println(image);
byte[] byte_buffer = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
final int width = image.getWidth(), height = image.getHeight();
for (int j = 0; j < height; j++) {
for (int i = 0; i < width; i++) {
int byte_index = (i + j * width) / 8;
int bit_index = (i + j * width) % 8;
byte_buffer[byte_index] |= 1 << bit_index;
}
}
ImageIO.write(image, "bmp", new File("stripes_out.bmp"));
}
}
输入图像,stripes.bmp 看起来像:
输出是:
我希望图像显示为全黑,但底部有几行未修改。显然,我没有到达字节缓冲区的末尾。
进一步调查,数组中似乎有一些额外的字节。
width = 810, height = 723
-> width * height / 8 = 73203
byte_buffer.length = 73746
不幸的是,这 543 个额外的字节不仅仅是在开头,因为跳过前 543 个字节会在图像的开头留下几行未修改。
我错过了什么?如何正确索引各个像素?
【问题讨论】:
-
图片尺寸是多少?你试过通过光栅吗?可能是应用了填充以保持宽度为 4 的倍数。