话不多说上代码
public static byte[] getImage(String imagePath)
{
InputStream is = getFile(imagePath);
try
{
return IOUtils.toByteArray(is);
}
catch (Exception e)
{
log.error("图片加载异常 {}", e);
return null;
}
finally
{
IOUtils.closeQuietly(is);
}
}
public static String byteToBase64(byte[] b) {
try {
return Base64.getEncoder().encodeToString(b);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static String getFileType(File file)
{
if (null == file)
{
return StringUtils.EMPTY;
}
return getFileType(file.getName());
}
调用
if (StringUtils.isEmpty(url)) {
return null;
}
byte[] image = getImage(url);
String s = byteToBase64(image);
File file = new File(url);
String fileType =getFileType(file);
String images= "data:image/"+fileType+";base64,"+s;
return images;