我想使用Java和Javafx为图片添加一个帧,然后保存带框的图片。最好的方法是什么?
例如说我有一张风景照片,想要添加一个框架。带框照片应如下所示:
答案 0 :(得分:2)
您可以将两个图像(首先是帧,然后是图像)添加到相同的画布中,如下所示:
GraphicsContext gc1 = canvas.getGraphicsContext2D();
gc1.drawImage(frameimage,0,0,image.getFitWidth()+20,image.getFitHeight()+20);
GraphicsContext gc = canvas.getGraphicsContext2D();
gc.drawImage(i,10,10,image.getFitWidth(),image.getFitHeight());
然后使用 canvas.snapshot 函数将它们保存为png(或您喜欢的任何格式):
FileChooser fileChooser = new FileChooser();
FileChooser.ExtensionFilter extFilter =new FileChooser.ExtensionFilter("png files (*.png)", "*.png");
fileChooser.getExtensionFilters().add(extFilter);
Stage primaryStage = (Stage) canvas.getScene().getWindow();
File file = fileChooser.showSaveDialog(primaryStage);
if(file != null){
try {
WritableImage writableImage = new WritableImage((int)canvas.getWidth(), (int)canvas.getHeight());
canvas.snapshot(null, writableImage);
RenderedImage renderedImage = SwingFXUtils.fromFXImage(writableImage, null);
File file1 = new File(file.getAbsolutePath()+".png");
file.renameTo(file1);
ImageIO.write(renderedImage, "png", file1);
} catch (IOException ex) {
ex.printStackTrace();
}