java - 图像未在 JavaFX ImageView 中显示
问题描述
我想在 JavaFX 的 ImageView 中显示图像。该图像应从 SQLite 数据库中获取并在场景加载时显示。我使用以下代码片段从数据库中获取代码并将其显示在先前创建的 ImageView 中。但图像未按预期显示。我做错了吗?ps 我已经测试了在FileOutputStream
从目录中读取文件时将路径更改为src/image.jpg
. 但似乎没有任何效果。但是当我手动将图像文件放入 src 目录并尝试读取它时,它就像一个魅力。但我想显示从数据库中获取的图像。
@FXML
private void loadEquipmentData() throws IOException {
try{
Connection conn = DatabaseConnection.getConnection();
PreparedStatement checkStmt = conn.prepareStatement(selectEquipmentQuery);
ResultSet rs = checkStmt.executeQuery();
while(rs.next()){
InputStream is = rs.getBinaryStream("Image");
OutputStream os = new FileOutputStream(new File("image.jpg"));
byte[] content = new byte[1024];
int size = 0;
while ((size = is.read(content)) != -1){
os.write(content, 0, size);
}
os.close();
is.close();
File file = new File("file:image.jpg");
image = new Image(file.toURI().toString());
this.eq_img.setImage(image);
this.eq_img.setPreserveRatio(true);
this.eq_img.setFitWidth(318.0);
this.eq_img.setFitHeight(253.0);
}
} catch (SQLException e) {
e.printStackTrace();
} catch (FileNotFoundException fnf) {
fnf.printStackTrace();
}
}
将图像写入数据库时,我使用此代码选择图像。
private FileChooser fileChooser;
private File file;
private FileInputStream fis;
@FXML
void chooseFiles() throws FileNotFoundException {
CommonStageSingleton stageSingleton = CommonStageSingleton.getInstance();
Stage userStage = stageSingleton.getMainWindow();
fileChooser = new FileChooser();
fileChooser.getExtensionFilters().addAll(
new FileChooser.ExtensionFilter("Image Files","*.jpg","*gif","*.jpeg","*.png")
);
file = fileChooser.showOpenDialog(userStage);
if(file != null){
fis = new FileInputStream(file);
ta_imagePath.setText(file.getAbsolutePath());
}
}
并将这些输入到数据库中。
Connection conn = DatabaseConnection.getConnection();
PreparedStatement checkStmt = conn.prepareStatement(checkEquipmentQuery);
PreparedStatement st = conn.prepareStatement(insertEquipmentQuery);
st.setBinaryStream(12, (InputStream)fis, (int)file.length());
我可能已经做了一些事情来将此图像保存为.jpg
.
解决方案
@dan1st 指出了我在这里缺少的东西。我在写入数据库时使用了 webp 图像作为输入图像。JavaFX 不支持 webp 图像类型。现在我使用jpeg,到目前为止没有任何问题。