javafx开发- ImageView标签设置图片不显示
图片不显示的原因没找到, 但是找到了解决办法 嘿嘿…
解决问题代码如下:
<ImageView fx:id="yj_img" fitHeight="16.0" fitWidth="16.0" layoutX="573.0" layoutY="8.0" pickOnBounds="true" preserveRatio="true">
<image>
<Image url="@../image/yj_green.png" />
</image>
</ImageView>
/**
* @Title: GetImageStrFromPath
* @Description: TODO(将一张本地图片转化成Base64字符串)
* @param imgPath
* @return
*/
public static String GetImageStrFromPath(String imgPath) {
InputStream in = null;
byte[] data = null;
// 读取图片字节数组
try {
in = new FileInputStream(imgPath);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
// 对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
// 返回Base64编码过的字节数组字符串, 在win环境中会自动换行, 因此需要把换行符给去掉
return encoder.encode(data).replaceAll("\r\n","");
}
@FXML
public ImageView yj_img;
@SneakyThrows
@Override
public void initialize(URL location, ResourceBundle resources) {
/** 这段的功能是实时时间的显示 */
//设置实时时间
SimpleDateFormat currentTime = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss"); //设置时间格式
EventHandler<ActionEvent> eventHandler = e->{
sj_La.setText(currentTime.format(new Date()));
// System.out.println(currentTime.format(new Date()));
};
//一秒刷新一次
Timeline animation = new Timeline(new KeyFrame(Duration.millis(1000), (javafx.event.EventHandler<ActionEvent>) eventHandler));
animation.setCycleCount(Timeline.INDEFINITE);
animation.play();
/** 这段的功能是实时时间的显示 */
/**
* 将图片转为base64字符串,然后放到ImageView标签中就可以显示了
*/
URL resource = getClass().getResource("/image/yj_gray.png");
String imgPath = resource.toURI().getPath().trim();
// System.out.println(imgPath);
String base64Str = Base64ImgUtil.GetImageStrFromPath(imgPath);
// System.out.println("64格式:--" + base64Str + "---" + base64Str.length());
// String base64String = "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAYVJREFUOE/Nk89LAlEQx2d2N3+EYqduQZeOEUFRCUUrbkS6KlR2ic5dvUbdqmuXDh06RgczUFcjWnPDwrpFdOw/6JQlKLr7JjQVF/IHdGlOj5nv+/CdN28Q/hjY7X48qUZq9VBAOuqk6w5QMtE6QPaGewLiaTXCMz4ry56Xpjh5pc7WzoEV6amZU5TshMEZnpDvx1XdgaZpQqGoXwPBuEWojulk9RHRNhFM1kUIzwzZiRX1dEUfeAOEV5dDWBZFUW+1EM3n7baP0iIz2CYAbCBClDG8RaTTNvvnHM+dlYfsd2G3u9Ry0BQkFHWXAHc4MvxOpyX3WarOkIEP7f0jwF5QlvabuZYDTdNshaL+DhwcVgaFY2tRzxLA9C+P9+VyCMOiKJZNDuKpzDwQ5Sy8MFJh1S0gPOg4YsSFkN97bwIk0+oqYxADwBggTAHRaCcAx8FawCddmgCJ1M06Edbn3isQKRz0L138M0BcUfMAMNfLfqP+GJIlt3kKjX/fJ6C1H12XqR/YN1DkmhHCB7aNAAAAAElFTkSuQmCC";
// System.out.println(base64String.length());
byte[] imageBytes = Base64.getDecoder().decode(base64Str);
InputStream inputStream = new ByteArrayInputStream(imageBytes);
DataInputStream dataInputStream = new DataInputStream(inputStream);
yj_img.setImage(new Image(dataInputStream));
/**
* 状态!=就绪, 按钮不可点击
*/
startTest_btu.setDisable(true);
}
还没有评论,来说两句吧...