【问题标题】:Java encode raw bytes into image simple image fomat/ fileJava将原始字节编码为图像简单图像格式/文件
【发布时间】:2015-09-03 14:09:03
【问题描述】:

我对图像编码非常陌生,我宁愿不了解它。基本上我采用灰度字节数组,其中每个字节等于一个像素。我从 mnist 获取这些数据,在那里我得到 28x28 字节的图像。无论如何,下面是我的代码,所以你明白我想要完成的事情。

  private def getImages = {
    val filePath = getClass.getResource("/mnist/train-images.idx3-ubyte").getPath
    val fis = new FileInputStream(filePath)
    var bytes = new Array[Byte](4)
    fis.read(bytes)
    println((ByteBuffer.wrap(bytes).getInt()))
    fis.read(bytes)
    println((ByteBuffer.wrap(bytes).getInt()))
    fis.read(bytes)
    var rows = ByteBuffer.wrap(bytes).getInt()
    println("Number of rows: " + rows)
    fis.read(bytes)
    var cols = ByteBuffer.wrap(bytes).getInt()
    println("Number of cols: " + cols)
    var imageBytes = new Array[Byte](rows * cols)
    fis.read(imageBytes)
    imageBytes.foreach(println(_))

    // I created a byte array input stream to feed into ImageIO
    // which should create my image
    val b = new ByteArrayInputStream(imageBytes)

    // This is where your helpful answer would be placed
    // What is the code to encode this into jpeg, gif, or whatever?

    // This returns null because I have not encoded the bytes
    // in the proper format
    val img = ImageIO.read(b)

    // Errors out because img is null
    ImageIO.write(img, "gif", new File("/home/dev/woot.gif"))
  }

格式只是相邻放置的连续像素字节。我的问题是,有哪些 Java 库或函数可用于将这些原始字节转换为 jpeg、gif 或我需要的任何格式?

【问题讨论】:

  • 旁注:您可以将fis 包装在DataInputStream 中,而不是使用InputStream 读取4 字节数组,然后将其包装在ByteBuffer 中以获取int并使用其readInt() 方法。它可能更清洁,但更重要的是,它更安全。请注意,InputStream.read(byte[]) 不能保证填充整个数组,您必须检查返回值(除非发生 Scala 魔法)。
  • 很好的建议。我经常使用 Java,所以我经常忘记事情,谢谢!

标签: java image scala image-processing


【解决方案1】:

在用ImageIO 写出来之前,先创建一个BufferedImage。它可以像使用 setRGB 方法一样简单,并且还有一个额外的好处是允许您在写出之前观察图像。

【讨论】:

  • 谢谢,我不认为我可以直接使用 setRGB,但你的想法帮助我找到了 setData() ,它接收光栅化数据。非常感谢!
猜你喜欢
  • 1970-01-01
  • 2014-10-01
  • 2016-05-25
  • 1970-01-01
  • 2015-04-08
  • 1970-01-01
  • 2018-11-22
  • 2019-05-06
  • 1970-01-01
相关资源
最近更新 更多