Java 将原始字节编码为图像简单图像格式/文件
Java encode raw bytes into image simple image fomat/ file
我对图像编码还很陌生,不想了解太多。基本上我采用灰度字节数组,其中每个字节等于一个像素。我从 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 或我需要的任何格式?
在用ImageIO
写出来之前,先创建一个BufferedImage
。它可以像使用 setRGB
方法一样简单,并且具有让您在写出图像之前观察图像的额外好处。
我对图像编码还很陌生,不想了解太多。基本上我采用灰度字节数组,其中每个字节等于一个像素。我从 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 或我需要的任何格式?
在用ImageIO
写出来之前,先创建一个BufferedImage
。它可以像使用 setRGB
方法一样简单,并且具有让您在写出图像之前观察图像的额外好处。