图片转Base64(读取、下载):
/**
* 图片转BASE64
* */
public static String encodeToString(String imagePath) throws IOException {
String type = StringUtils.substring(imagePath, imagePath.lastIndexOf(".") + 1);
BufferedImage image = ImageIO.read(new File(imagePath));
String imageString = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ImageIO.write(image, type, bos);
byte[] imageBytes = bos.toByteArray();
BASE64Encoder encoder = new BASE64Encoder();
imageString = encoder.encode(imageBytes);
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
imageString = "data:image/jpeg;base64," + imageString.replaceAll("\r|\n", "");
return imageString;
}
说明:可直接将获得的Base64数据赋值给页面img的src属性或者background-img的url,由于页面中使用的Base64数据为完整的,所以由java后台转换得到的Base64数据需要加上Base64的头【data:image/jpeg;base64】,其中【jpeg】为图片类型,理论上,图片类型是否与原图类型一致并不影响显示,获得的Base64数据中可能存在换行,所以需要去掉.
Base64转图片(上传):
BASE64Decoder decoder = new BASE64Decoder();
String imgFilePath;
try
{
//Base64解码
byte[] b = decoder.decodeBuffer(imgStr);
for(int j=0;j<b.length;++j)
{
if(b[j]<0)
{//调整异常数据
b[j]+=256;
}
}
//生成jpeg图片
imgFilePath = "D:\\carsoulIMG" + count + ".jpg";
OutputStream out = new FileOutputStream(imgFilePath);
out.write(b);
out.flush();
out.close();
}
需要导入的包: