[英]Java get image extension from byte array
我有以下代码用于保存字节数组中的图像。
我可以使用以下代码成功保存图像。
目前我正在使用“.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);
你会使用base64图像数据的前缀头data:image/png;base64
吗?
从RFC,“数据”网址定义:
### 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......
然后你可以用gif获得扩展。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.