How to convert from BufferedImage to JavaFX 2.2 Image

本文介绍如何在JavaFX中直接加载和使用BufferedImage。通过使用WritableImage类及其PixelWriter接口,可以实现从BufferedImage到JavaFX Image的转换,而无需先将图像写入磁盘。这种方法提供了更灵活和高效的图像处理方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://blog.idrsolutions.com/2012/11/convert-bufferedimage-to-javafx-image/

——————————————————————————————————————————————————————————————————

 

Until recently, if you wanted to load a BufferedImage in JavaFX you were out of luck – the only way to do it was to write out the BufferedImage to disk and then read it back in as a JavaFX Image.

But, in August when JavaFX 2.2 was released, the update included a class called WritableImage which extends Image. Along with PixelWriter and PixelReader classes, this gives us greater control over images in JavaFX.

Using the PixelWriter and the getRGB method of BufferedImage, we are now able to read a BufferedImage into a WritableImage. As WritableImage extends Image, we can now use this however we would an Image!

Here’s how:

        BufferedImage bf =  null;
         try {
            bf = ImageIO.read( new File("C:/location/of/image.png"));
        }  catch (IOException ex) {
            System.out.println("Image failed to load.");
        }
 
        WritableImage wr =  null;
         if (bf !=  null) {
            wr =  new WritableImage(bf.getWidth(), bf.getHeight());
            PixelWriter pw = wr.getPixelWriter();
             for ( int x = 0; x < bf.getWidth(); x++) {
                 for ( int y = 0; y < bf.getHeight(); y++) {
                    pw.setArgb(x, y, bf.getRGB(x, y));
                }
            }
        }
 
        ImageView imView =  new ImageView(wr);

 

Alternatively, you could use the toFXImage method from SwingFXUtils, but where’s the fun in that?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值