0

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

@Override 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) {
    }
}
4

1 回答 1

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();
    }
}
于 2017-12-20T17:09:07.620 回答