0

我正在尝试运行简单的 JavaFx(2.0) 应用程序,它将三个图像显示为缩略图。操作系统是 Windows7,我使用的是 NetBeans 7.2 代码是这样的——

public class FX17 extends Application{

    public static void main(String[] args){
        launch(args);
    }
    public void start(Stage stage){

        HBox photoBar = new HBox();
        Group root = new Group();
        File f1 = new File("C:\\Users\\Pictures\\IMG_0021.jpg");
        File f2 = new File("C:\\Users\\Pictures\\IMG_0022.jpg");
        File f3 = new File("C:\\Users\\Pictures\\IMG_0023.jpg");

        Image i1 = new Image(f1.toURI().toString());
        Image i2 = new Image(f2.toURI().toString());
        Image i3 = new Image(f3.toURI().toString());
        ImageView iv1 = new ImageView(i1);
        //iv1.setImage(i1);
        iv1.setFitWidth(50);
        iv1.setPreserveRatio(true);
        iv1.setCache(true);

        ImageView iv2 = new ImageView(i2);
        //iv2.setImage(i2);
        iv2.setFitWidth(50);
        iv2.setPreserveRatio(true);
        iv2.setCache(true);

        ImageView iv3 = new ImageView(i3);
       // iv3.setImage(i3);
        iv3.setFitWidth(50);
        iv3.setPreserveRatio(true);
        iv3.setCache(true);

       photoBar.getChildren().add(iv1);
        photoBar.getChildren().add(iv2);
        photoBar.getChildren().add(iv3);
        //C:\Users\Public\Pictures\Sample Pictures

        BorderPane pane = new BorderPane();
        pane.setTop(photoBar);
        root.getChildren().add(photoBar);
        //pane.setLeft(linkBar);

        Scene scene = new Scene(root);
        scene.setFill(Color.BLACK);

        stage.setScene(scene);
        stage.setWidth(415);
        stage.setHeight(200);
        stage.sizeToScene();
        stage.show();
    }

}

对于两个图像程序运行并显示两个缩略图,但对于 3 个或更多图像,程序会抛出 OutOfMemoryError。图片为 jpg,平均大小为 2.5MB。我需要检查一些设置或图像格式吗?以下构造函数对我来说很好。Image img = new Image(file.toURI().toString(),100,100,false,false);纵横比,平滑为false。

4

1 回答 1

0

我猜你的 jpg 在高度和宽度方面非常大。

jpg 与加载的图像缓冲区所占用的内存是不同的。加载的图像是解码的未压缩位图,取决于图像的高度/宽度/颜色深度,而不是原始 jpg 文件大小。

要修复 OutOfMemory 情况:

  1. 使用程序外部的图像编辑器将 jpg 的大小调整为更小的高度和宽度(和/或更低的颜色深度)和/或
  2. 一次只将一个 jpg 加载到内存中,而不是同时加载三个和/或
  3. 增加 Java 应用程序可用的内存(例如 -Xmx1500m)和/或
  4. 在图像构造函数而不是图像视图中指定大小。

在图像构造函数中指定大小可确保加载图像后,Java 仅保留足够大的缓冲区以容纳调整大小的图像,而不是完整大小的未压缩图像。

于 2012-06-02T07:38:13.897 回答