Jason Liu
Jason Liu

Reputation: 109

How to save a huge bmp file in java?

I am working a project involves visualizing a star catalog and create a printable bmp file. If I want to print a 24 by 24 picture with 1200 dpi resolution, it would be 28800*28800 and roughly 2.32 Gb.

Generally when create a bmp file, one would make a BufferedImage, graph something with the setRGB method, and save it as a bmp file with ImageIO.write.

But as I try to distribute my program, the end user may not have sufficient free RAM, and it will cause an OutOfMemoryError.

Is there a way to avoid saving every pixel of the image on RAM? If I can horizontally cut the image into several bands, and save them one by one to a single bmp file, it would be great (since I can get ride of the saved buffers).

Something similar would be:

Before I find the imageIO and awt package, I wrote a Bitmap class that saves a bitmap as a csv file and use an external software to render it. It has a toString method, and I use the method to save the content of the csv as a string instead of actually save it on the disk. When I want to make a large image, I create a fileWriter and a printWriter. I buffer a horizontal band of the image, and write it to the disk with the printWriter. Then I buffer the next band and replace the old band, and write it with the printWriter again. When it is finished, I close the writers and have the complete bitmap as a csv file on my disk.

Upvotes: 1

Views: 327

Answers (1)

Robert
Robert

Reputation: 42710

What you need is code that directly creates an image file without loading the data completely into memory (usually this is called tiled image processing). I don't know a Java library that allows to do so, therefore my recommendation would be to look at the BMP file format and just write the file manually. AFAIR the BMP file format is pretty simple.

Some time ago I have seen something similar for PNG output: PngXxlWriter.java

Upvotes: 1

Related Questions