使用jdk11原生api实现bitmap文件转换成图片
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import javax.imageio.ImageIO;
public class DataToImageConverter {
public static void main(String[] args) {
if (args.length != 4) {
System.err.println("Usage: java DataToImageConverter <data-file> <width> <height> <output-image-file>");
return;
}
String dataFile = args[0];
int width = Integer.parseInt(args[1]);
int height = Integer.parseInt(args[2]);
String outputImageFile = args[3];
try {
byte[] imageData = readDataFile(dataFile);
if (imageData.length < width * height * 4) {
throw new IllegalArgumentException("Data file size is too small for the given width and height.");
}
BufferedImage image = createImageFromData(imageData, width, height);
saveImage(image, outputImageFile);
System.out.println("Image saved to: " + outputImageFile);
} catch (IOException e) {
e.printStackTrace();
}
}
private static byte[] readDataFile(String dataFile) throws IOException {
File file = new File(dataFile);
byte[] data = new byte[(int) file.length()];
try (FileInputStream fis = new FileInputStream(file)) {
fis.read(data);
}
return data;
}
private static BufferedImage createImageFromData(byte[] imageData, int width, int height) {
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
int[] pixels = new int[width * height];
ByteBuffer buffer = ByteBuffer.wrap(imageData).order(ByteOrder.BIG_ENDIAN);
try {
buffer.asIntBuffer().get(pixels);
} catch (BufferUnderflowException e) {
System.err.println("Buffer underflow exception occurred. Check the data file size and image dimensions.");
throw e;
}
image.setRGB(0, 0, width, height, pixels, 0, width);
return image;
}
private static void saveImage(BufferedImage image, String outputFile) throws IOException {
File file = new File(outputFile);
ImageIO.write(image, "png", file);
}
}