【问题标题】:Get pixel data from a BufferedImage从 BufferedImage 获取像素数据
【发布时间】:2013-11-06 13:45:53
【问题描述】:

我需要从 BufferedImage 中获取像素数据,以便从数据中重新创建图像。我查看了Raster,但似乎没有包含我需要的信息。如何从BufferedImage 获取数据,以便无需原始文件即可重新创建图像?

【问题讨论】:

  • 在没有原始文件的情况下重新创建是什么意思?
  • 我想获取图像的数据(像素颜色、大小等)并根据该数据保存并重新创建图像。
  • this examplethis 可能会有所帮助。
  • 您是否需要像素访问,来操作图像数据,或者只是为了避免需要原始文件的想法是需要在内存中执行,还是可以存储到(另一个)文件?

标签: java image bufferedimage


【解决方案1】:

你应该看看这个问题的答案

Java - get pixel array from image

一种方法是使用

ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(originalImage, "jpg", baos);
baos.flush();
byte[] imageBytes = baos.toByteArray();
baos.close();

现在当你想从你使用的数据中创建一个新的BufferedImage

ByteArrayInputStream bais = new ByteArrayInputStream(imageBytes);
BufferedImage newImage = null;
try {
    newImage = ImageIO.read(bais);
} catch (IOException e) {
    // handle exception
}

【讨论】:

  • 如何将该像素数据应用到另一个 BufferedImage?
  • @Charsmud 好问题!我在答案中添加了说明。
  • @Craigy 您无法使用 ImageIO 读取字节数组,就像在您的示例中一样。 ImageIO 读取以文件格式存储的图像。尽管您的代码可以编译,但newImage 将是null。您需要使用new BufferedImage(colormodel, raster, colormodel.isAlphaPremultiplied(), null) 重新创建(即,您需要知道ColorModel 以及栅格)。
  • @haraldK 你是对的。我已经更新了答案,以便可以重新创建图像。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-22
  • 2011-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多