【发布时间】: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