我想在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,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
。