Java从字节数组获取图像扩展
我有下面从字节数组保存图像的代码 我能够使用下面的代码成功地保存图像 目前我正在使用“.png”格式保存图像,但我想从字节数组中获取图像扩展名,并使用此扩展名保存图像 这是我的密码Java从字节数组获取图像扩展,java,image,tomcat,Java,Image,Tomcat,我有下面从字节数组保存图像的代码 我能够使用下面的代码成功地保存图像 目前我正在使用“.png”格式保存图像,但我想从字节数组中获取图像扩展名,并使用此扩展名保存图像 这是我的密码 public boolean SaveImage(String imageCode) throws Exception { boolean status = false; Connection dbConn = null; CallableStatement callableStatement
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));
也可以使用第三方库。比如:
你会使用前缀header
data:image/png;base64图像数据的base64
从RFC中,“数据”url定义:
### Form : `data:[<mediatype>][;base64],<data>`
### Syntax:
`dataurl := "data:" [ mediatype ] [ ";base64" ] "," data
mediatype:= [ type "/" subtype ] *( ";" parameter )
data := *urlchar
parameter := attribute "=" value`
然后,您可以使用gif获取扩展名。可能重复的扩展名:有一个完整的幻数列表指示文件类型:问题中没有任何内容告诉我们字节是Base64编码的,并使用
数据:
URL。这仅适用于jpg图像的png图像,也作为png图像提供延伸
### Form : `data:[<mediatype>][;base64],<data>`
### Syntax:
`dataurl := "data:" [ mediatype ] [ ";base64" ] "," data
mediatype:= [ type "/" subtype ] *( ";" parameter )
data := *urlchar
parameter := attribute "=" value`
data:image/gif;base64,R0lGODdhMAAwAPAAAAAAAP///ywAAAAAMAAw......