一个可以将图片转成base64编码的工具类/**
*Copyright(c)-,玛雅牛(myaniuATgmaildotcom).
*
*LicensedundertheApacheLicense,Version2.0(the"License");
*youmaynotusethisfileexceptincompliancewiththeLicense.
*YoumayobtainacopyoftheLicenseat
*
*/licenses/LICENSE-2.0
*
*Unlessrequiredbyapplicablelaworagreedtoinwriting,software
*distributedundertheLicenseisdistributedonan"ASIS"BASIS,
*WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied.
*SeetheLicenseforthespecificlanguagegoverningpermissionsand
*limitationsundertheLicense.
*/
packagecom.jfinal.kit;
importjava.awt.image.BufferedImage;
importjava.io.ByteArrayOutputStream;
importjava.io.File;
importjava.io.IOException;
importjavax.imageio.ImageIO;
publicclassImageKit{
privateImageKit(){
}
/**
*生成形如data:image/jpeg;base64,iVBORw0KGgoA……的字符串,将图片文件DataURI化
*
*@paramimageFilePath图片文件路径
*@return形如data:image/jpeg;base64,iVBORw0KGgoA……的字符串
*@throwsIOException
*/
publicstaticStringencodeDataUri(StringimageFilePath)throwsIOException{
returnencodeDataUri(newFile(imageFilePath));
}
/**
*生成形如data:image/jpeg;base64,iVBORw0KGgoA……的字符串,将图片文件DataURI化
*
*@paramimageFile图片文件对象
*@return形如data:image/jpeg;base64,iVBORw0KGgoA……的字符串
*@throwsIOException
*/
publicstaticStringencodeDataUri(FileimageFile)throwsIOException{
Stringtype=FileKit.getFileExtension(imageFile).toLowerCase();
if("jpg".equals(type)){
type="jpeg";
}
return"data:image/"+type+";base64,"+encodeBase64(imageFile);
}
/**
*将文件编码成base64格式
*
*@paramimageFilePath图片文件路径
*@returnbase64编码格式的字符串
*@throwsIOException
*/
publicstaticStringencodeBase64(StringimageFilePath)throwsIOException{
returnencodeBase64(newFile(imageFilePath));
}
/**
*将文件编码成base64格式
*
*@paramimageFile图片文件对象
*@returnbase64编码格式的字符串
*@throwsIOException
*/
publicstaticStringencodeBase64(FileimageFile)throwsIOException{
BufferedImagebi=ImageIO.read(imageFile);
Stringtype=FileKit.getFileExtension(imageFile).toLowerCase();
ByteArrayOutputStreambaos=newByteArrayOutputStream();
ImageIO.write(bi,type,baos);
returnBase64Kit.encode(baos.toByteArray());
}
}