Reputation: 70
What is the maximum size of an image can be created using Java 2D?
I am using Windows 7 Pro 64 bit OS and JDK 1.6.0_33, 64 bit version. I can able to create a BufferedImage up to 5 MB of size. Beyond that I am getting OutOfMemoryError.
Please guide me how to create a bigger size image using Java 2D or JAI.
Here is my attempt.
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class CreateBiggerImage
{
private String fileName = "images/107.gif";
private String outputFileName = "images/107-Output.gif";
public CreateBiggerImage()
{
try
{
BufferedImage image = readImage(fileName);
ImageIO.write(createImage(image, 9050, 9050), "GIF", new File(System.getProperty("user.dir"), outputFileName));
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
private BufferedImage readImage(String fileName) throws Exception
{
BufferedImage image = ImageIO.read(new File(System.getProperty("user.dir"), fileName));
return image;
}
private BufferedImage createImage(BufferedImage image, int outputWidth, int outputHeight) throws Exception
{
int actualImageWidth = image.getWidth();
int actualImageHeight = image.getHeight();
BufferedImage imageOutput = new BufferedImage(outputWidth, outputHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = imageOutput.createGraphics();
for (int width = 0; width < outputWidth; width += actualImageWidth)
{
for (int height = 0; height < outputHeight; height += actualImageHeight)
{
g2d.drawImage(image, width, height, null);
}
}
g2d.dispose();
return imageOutput;
}
public static void main(String[] args)
{
new CreateBiggerImage();
}
}
Upvotes: 1
Views: 1034
Reputation: 27054
The "maximum size" of image you can create with Java 2D depends on a lot of things... So I'll make a few assumptions here (correct me if I'm wrong):
BufferedImage
With these assumptions, the theoretical limit is given by (width * height * bits per pixel / bits in transfer type) == Integer.MAX_VALUE
(in other words, the largest array you can create). As an example, for TYPE_INT_RGB
or TYPE_INT_ARGB
, you'll use 32 bits per pixel, and the the transfer type is also 32 bit. For TYPE_3BYTE_RGB
you'll use 24 bits per pixel, but the transfer type is only 8 bit, so the maximum size is actually smaller.
It's possible that you could theoretically create even larger tiled RenderedImage
s. Or use custom Raster
s with multiple bands (multiple arrays).
In any case, your limiting factor will be available contiguous memory.
To overcome this, I've created a DataBuffer implementation that uses a memory mapped file to store image data outside the JVM heap. It's entirely experimental, but I've successfully created BufferedImage
s where width * height ~= Integer.MAX_VALUE / 4
. Performance is not great, but may be acceptable for certain applications.
Upvotes: 2