2009-10-06 40 views
0

如何將JComponent中的圖形保存爲tiff格式?我只知道如何保存整個Java文件,但我不知道如何保存特定的Jcomponent。幫幫我:-(將JComponent中的圖形保存爲Tiff文件

編輯:? 謝謝你們,現在我能到我的繪圖保存爲JPEG

不過,我只是想保存組件之一的c.paintAll(bufferedImage.getGraphics());似乎拯救了整個組件。不過,我只是想我怎麼能這樣做?謝謝保存該組件c.add(new PaintSurface(), BorderLayout.CENTER);沒有panel.add(saveBtn);

Container c = getContentPane(); 
c.setLayout(new BorderLayout());  
Panel panel = new Panel(); 
panel.add(saveBtn); 
c.add("South", panel); 
c.setBackground(Color.WHITE); 
c.add(new PaintSurface(), BorderLayout.CENTER); 

回答

1

這與broschb's解決方案基本相同,只使用正確的語法並實際調用相應的JAI例程。對於各種功能

public void saveComponentAsTiff(Component c, String filename, boolean subcomp) throws IOException { 
    saveComponentTiff(c, "tiff", filename, subcomp); 
} 

public void saveComponent(Component c, String format, String filename, boolean subcomp) throws IOException { 
    // Create a renderable image with the same width and height as the component 
    BufferedImage image = new BufferedImage(c.getWidth(), c.getHeight(), BufferedImage.TYPE_INT_ARGB); 

    if(subcomp) { 
     // Render the component and all its sub components 
     c.paintAll(image.getGraphics()); 
    } 
    else { 
     // Render the component and ignoring its sub components 
     c.paint(image.getGraphics()); 
    } 

    // Save the image out to file 
    ImageIO.write(image, format, new File(filename)); 
} 

文檔可以在這裏找到:

如果要以除tiff以外的格式保存,可以使用ImageIO.getWriterFormatNames()獲取JRE當前加載的所有圖像輸出格式的列表。

更新:如果您對繪製子組件不感興趣,可以使用Component.paint(...)將調用替換爲Component.paintAll(...)。我已經改變了示例代碼來反映這一點。將subcomponent設置爲true並渲染子組件並將其設置爲false將忽略它們。

+0

:-)謝謝Kevin – Jessy 2009-10-09 01:14:45

0

你可以得到部分的緩衝圖像,或通過創建一個緩衝圖像中包含繪圖板然後可以將面板內容繪製到面板上e緩衝圖像。然後,您可以使用JAI(Java Advanced Imaging)庫將緩存的圖像保存爲tiff。您必須查看該here上的文檔。

JComponent component; //this is your already created component 
BufferedImage image = new BufferedImage(component.getWidth(), 
             component.getHeight(), 
             Bufferedimage.TYPERGB) 

Graphics g = image.getGraphics; 
component.paintComponent(g); 

語法可能稍微偏離,我不是一個想法,但這是一般的想法。然後您可以使用JAI並將緩衝的圖像轉換爲TIFF。