2013-08-27 39 views
1

使用Java 2D可以創建圖像的最大尺寸是多少?如何在Java2D中創建更大尺寸的圖像

我使用Windows 7 Pro 64位操作系統和JDK 1.6.0_33,64位版本。我可以創建一個5 MB大小的BufferedImage。除此之外,我正在OutOfMemoryError。

請指導我如何使用Java 2D或JAI創建更大尺寸的圖像。

這是我的嘗試。

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(); 
} 
} 
+0

你給Java程序多少內存? – Kayaman

+0

您好Kayaman,我曾嘗試以下,Java的罐子MaxMemoryTest.jar以及Java的罐子-Xms512m -Xmx1024m MaxMemoryTest.jar – Sivagururaja

+0

你的大小9050 9050 X的圖像是利用每像素4個字節(TYPE_INT_RGB)。這導致327610000字節,或在內存中> 312 MB。你確定5MB的限制嗎?它應該可以用-Xmx1024m來實現,除非輸入圖像很大。還記得JVM需要的*連續可用空間*塊來爲你在堆上圖像的int數組。所以有1024 MB的堆不能保證(但它*應該*工作)。 – haraldK

回答

2

「最大尺寸」的形象,你可以使用Java 2D創建取決於很多事情。所以我會在這裏(糾正我,如果我錯了)做一些假設:

  • 所謂「大小」,則意味着尺寸(寬×高),而不是內存消耗
  • 所謂「圖像」,則意味着BufferedImage

在這些假設下,理論極限由給出(換句話說,您可以創建最大的陣列)。例如,對於TYPE_INT_RGBTYPE_INT_ARGB,您將使用每像素32位,並且傳輸類型也是32位。對於TYPE_3BYTE_RGB,您將使用每像素24位,但傳輸類型僅爲8位,所以最大尺寸實際上更小。

理論上可能會創建更大的平鋪的RenderedImage s。或者使用具有多個波段(多個陣列)的自定義Raster

在任何情況下,您的限制因素將是可用的連續內存。

爲了克服這個問題,我創建了一個DataBuffer implementation that uses a memory mapped file存儲JVM堆外的圖像數據。這完全是實驗性的,但我已經成功創建了BufferedImage s,其中width * height ~= Integer.MAX_VALUE/4。性能不是很好,但對某些應用程序可能是可以接受的。

+0

感謝您的回覆Harald。我沒有使用柵格和RenderedImage,我知道的只有BufferedImage。我必須在此更新自己。 – Sivagururaja