2013-04-18 40 views
1

我制作了一个屏幕快照,并尝试获取图像的一部分,当我尝试将其保存到文件不起作用时。 将竭诚为得到任何建议如何将光栅转换为RenderedImage

Rectangle Rect = new Rectangle(10, 10, 50, 50); 
File file = new File("D:\\output.png"); 
RenderedImage renderedImage = SwingFXUtils.fromFXImage(browser.snapshot(null, null), null); 
try { 
    ImageIO.write((RenderedImage) renderedImage.getData(Rect),"png",file); 
       } catch (IOException ex { Logger.getLogger(JavaFXApplication3.class.getName()).log(Level.SEVERE, null, ex); 
       } 

所以在这里我终于和它的作品

     File file = new File("D:\\output.png"); 
       BufferedImage image = SwingFXUtils.fromFXImage(browser.snapshot(null, null), null); 
       try { 
        ImageIO.write(image.getSubimage(100, 100, 50, 50) , "png", file); 
       } catch (IOException ex) { 
        Logger.getLogger(JavaFXApplication3.class.getName()).log(Level.SEVERE, null, ex); 
       } 
+0

能否详细说明“不起作用”。输出是不是你所期望的或者是否会抛出异常? –

+0

它没有给我任何输出图像,并没有引发异常。程序刚刚卡住了 – Jason

+0

*“很乐意得到任何建议”* 1)为了更快地获得更好的帮助,请发布[SSCCE](http://sscce.org/)。 2)所述任务可以在J2SE中完成。不需要'SwingFXUtils'。 3)*“它不起作用”*可能是累了。不要模糊在这一点上。复制/粘贴结果的错误或异常输出,或者准确描述发生了什么,以及您预期会发生什么。 4)对代码块使用一致的逻辑缩进。代码的缩进旨在帮助人们理解程序流程! –

回答

2

在这里,我的猜测是,您有麻烦铸造从.getData()方法检索到Raster一个图像。虽然在技术上应该采取光栅,将其转换为WritableRaster并将其包装在RenderedImage中,但我建议您基本上复制图像的一部分。 快速SSCE

import javax.imageio.ImageIO; 
import java.awt.*; 
import java.awt.image.*; 
import java.io.File; 

public class Test { 

    public static void main(String[] args) throws Exception { 
     BufferedImage original = new BufferedImage(100, 100, BufferedImage.TYPE_3BYTE_BGR); 
     // Crop away 10 pixels pixels and only copy 40 * 40 (the width and height of the copy-image) 
     BufferedImage copy  = original.getSubimage(10, 10, 50, 50); 

     ImageIO.write(copy, "png", new File("Test.png")); 
    } 

} 

这对我的作品,所以如果你遇到麻烦进一步您可能会考虑确保输入被正确牵强。如果您的问题是程序“卡住”,请首先尝试使用虚拟图像上面的代码。

希望帮助:-)

编辑:我不知道有一个叫getSubimage方法,所以我换成上面用方法的代码。感谢Andrew Thompson。

1

一旦应用程序。参考BufferedImage,只需使用subImage(Rectangle)方法创建较小的图像。

import java.awt.*; 
import java.awt.image.BufferedImage; 
import java.io.File; 
import javax.imageio.ImageIO; 
import javax.swing.*; 

class ScreenSubImage { 

    public static void main(String[] args) throws Exception { 
     Robot robot = new Robot(); 
     Dimension d = Toolkit.getDefaultToolkit().getScreenSize(); 
     BufferedImage image = robot.createScreenCapture(new Rectangle(d)); 
     BufferedImage sub = image.getSubimage(0, 0, 400, 400); 
     File f = new File("SubImage.png"); 
     ImageIO.write(sub, "png", f); 
     final ImageIcon im = new ImageIcon(f.toURI().toURL()); 

     Runnable r = new Runnable() { 

      @Override 
      public void run() { 
       JOptionPane.showMessageDialog(null, new JLabel(im)); 
      } 
     }; 
     // Swing GUIs should be created and updated on the EDT 
     // http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html 
     SwingUtilities.invokeLater(r); 
    } 
}