我如何在javafxports安卓应用程序中将javafx.image.Image保存到jpg文件?

时间:2016-05-04 11:26:31

标签: javafxports gluon-mobile

如何在javafxports安卓应用中将javafx.image.Image保存到jpg文件? 我找不到一个api我唯一创建的是在android上不支持的ImageIO。 我需要一些帮助 示例代码:

@覆盖     public void start(Stage primaryStage){

    StackPane root = new StackPane();

    Scene scene = new Scene(root, 400, 450);
    WritableImage wim = new WritableImage(300, 250);



    Canvas canvas = new Canvas(300, 250);
    GraphicsContext gc = canvas.getGraphicsContext2D();
    drawShapes(gc);
    canvas.snapshot(null, wim);
    root.getChildren().add(canvas);

    primaryStage.setTitle("Hello World!");
    primaryStage.setScene(scene);
    primaryStage.show();

    File file = new File("CanvasImage.png");


    try {

       //on desktop ImageIO.write(SwingFXUtils.fromFXImage(wim, null), "png", file);
//   on android ??????????

    } catch (Exception s) {
    }
}

1 个答案:

答案 0 :(得分:1)

在Android上,您可以使用android.graphics.Bitmap保存到文件:

  public void saveImageToPngFile(File file, WritableImage image) {
    int width = (int) image.getWidth();
    int height = (int) image.getHeight();
    Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    try {

        PixelReader pr = image.getPixelReader();
        IntBuffer buffer = IntBuffer.allocate(width * height);
        pr.getPixels(0, 0, width, height, PixelFormat.getIntArgbInstance(), buffer, width);
        bitmap.setPixels(buffer.array(), 0, width, 0, 0, width, height);

        FileOutputStream out = new FileOutputStream(file);
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}