Java从字节数组获取图像扩展 [英] Java get image extension from byte array
本文介绍了Java从字节数组获取图像扩展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码,用于保存字节数组中的图像.
I have the below code for saving an image from a byte array.
我可以使用以下代码成功保存图像.
I am able to save the image successfully using the below code.
当前,我正在保存".png"格式的图像,但我想从字节数组中获取图像扩展名并使用该扩展名保存图像.
Currently I am saving image with ".png" format but I want to get the image extension from byte array and save image with this extension.
这是我的代码
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.
I am using Java and Tomcat 8.
推荐答案
有很多解决方案.例如,非常简单:
There are many solutions. Very simple for example:
String contentType = URLConnection.guessContentTypeFromStream(new ByteArrayInputStream(imageBytes));
或者您可以使用第三方库.像 Apache Tika :
Or you can use third-party libraries. Like Apache Tika:
String contentType = new Tika().detect(imageBytes);
这篇关于Java从字节数组获取图像扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文