我有以下代码用于从字节数组保存图像。
我可以使用以下代码成功保存图像。
目前我正在以“.png”格式保存图像,但我想从字节数组中获取图像扩展名并使用此扩展名保存图像。
这是我的代码
public boolean SaveImage(String imageCode) throws Exception {
boolean status = false;
Connection dbConn = null;
CallableStatement callableStatement = null;
try {
String base64Image = imageCode.split(",")[1];
byte[] imageBytes = javax.xml.bind.DatatypeConverter.parseBase64Binary(base64Image);
Properties propFile = LoadProp.getProperties();
String filepath = propFile.getProperty(Constants.filepath);
File file = new File(filepath + "xyz.png");
FileOutputStream fos = new FileOutputStream(file);
try {
fos.write(imageBytes);
} finally {
fos.close();
}
} catch (Exception e) {
throw e;
} finally {
if (callableStatement != null) {
callableStatement.close();
}
if (dbConn != null) {
dbConn.close();
}
}
return status;
}
我正在使用 Java 和 Tomcat 8。
最佳答案
有很多解决方案。非常简单的例子:
String contentType = URLConnection.guessContentTypeFromStream(new ByteArrayInputStream(imageBytes));
或者您可以使用第三方库。喜欢Apache Tika :
String contentType = new Tika().detect(imageBytes);
关于Java从字节数组中获取图像扩展名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38452171/