如果您使用的是标准图像 io,则可以执行以下操作:
BufferedImage image = ImageIO.read( <your image file> );
ByteArrayOutputStream baos=new ByteArrayOutputStream();
int width=image.getWidth(null);
int height=image.getHeight(null);
BufferedImage bi=new BufferedImage(width,height,BufferedImage.TYPE_BYTE_GRAY);
bi.getGraphics().drawImage(image,0,0,null);
ImageIO.write(bi,"RAW",baos);
baos.flush();
byte[] resultImageAsRawBytes = baos.toByteArray();
baos.close();
这基本上是:它将图像读入 a BufferedImage
,将其渲染为灰度图像并将结果写入 a ByteArrayOutputStream
,从而允许您访问原始字节。
不过有几点注意事项: - 你需要自己添加异常处理 - 我对"RAW"
格式不是 100% 确定(不幸的是我自己无法测试),但它应该让你开始
作为替代方案,您可以获取图像的栅格,例如通过调用image.getRaster()
,自己迭代像素,将它们转换为无符号字节并将它们放入字节数组中。