我正在使用 JavaFX 并使用 Javafx 中的 LineChart 概念来说明图表。 如果我绘制图表,我会使用此代码导出该图表的屏幕截图。
WritableImage image = lc.snapshot(new SnapshotParameters(), null);
File file = new File("Chart.png");
try {
ImageIO.write(SwingFXUtils.fromFXImage(image, null), "png", file);
}
catch (IOException e) {
//bla
}
这很完美!
现在:有没有一种简单的方法可以将这个“WritableImage”图像创建为 Base64 字符串?此外,我想用它在 PHP 中将此 Base64 字符串复制为 PNG 文件。
有什么想法吗? 谢谢
最佳答案
您的代码需要继续执行以下操作:
//File file = new File("Chart.png"); -> this is already there
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int read= 0;
while( (read = fis.read(buffer)) > -1){
baos.write(buffer, 0, read);
}
fis.close();
baos.close();
byte pgnBytes [] = baos.toByteArray();
Base64.Encoder base64_enc = Base64.getEncoder();
String base64_image = base64_enc.encodeToString(pgnBytes);
如果不需要将图形存储到文件中,可以进一步优化以将文件直接写入字节数组:
WritableImage image = lc.snapshot(new SnapshotParameters(), null);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
ImageIO.write(SwingFXUtils.fromFXImage(image, null), "png", baos);
}
catch (IOException e) {
//bla
}
byte pgnBytes [] = baos.toByteArray();
Base64.Encoder base64_enc = Base64.getEncoder();
String base64_image = base64_enc.encodeToString(pgnBytes);
}
在这两种情况下,图像都存储在内存中,如果图像太大等,可能会导致 OutOfMemory 错误。
关于JavaFX 图表到图像到 Base64 字符串在 PHP 中的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31407382/