导入Maven依赖
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.12</version>
</dependency>
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.9</version>
</dependency>
编码实现
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import static java.util.regex.Pattern.compile;
public class ImageUtil {
public static Logger logger = Logger.getLogger(ImageUtil.class);
public static String imageToBase64String(String imgPath){
InputStream in = null;
byte[] data = null;
String imgStr = "";
BASE64Encoder base64Encoder = new BASE64Encoder();
try {
in = new FileInputStream(imgPath);
data = new byte[in.available()];
in.read(data);
imgStr = base64Encoder.encode(data);
} catch (IOException e) {
logger.error("后台异常",e);
} finally {
data = null;
base64Encoder = null;
if(null != in) {
try {
in.close();
} catch (IOException e) {
}
}
}
return imgStr;
}
public static boolean base64StringToImage(String imgBase64, String imgPath) {
byte[] imgBytes = null;
OutputStream out = null;
if (StringUtil.isNotBlank(imgBase64)) {
try {
imgBytes = new BASE64Decoder().decodeBuffer(
compile("data:image/\\w{1,5};base64,").matcher(imgBase64).replaceFirst(""));
for (int i = 0; i < imgBytes.length; ++i) {
if (imgBytes[i] < 0) {
imgBytes[i] += 256;
}
}
out = new FileOutputStream(imgPath);
out.write(imgBytes);
out.flush();
} catch (Exception e) {
logger.error("文件上传失败! 原因:" + e);
System.err.println("文件上传失败! 原因:" + e);
return false;
} finally {
imgBytes = null;
if (null != out) {
try {
out.close();
} catch (IOException e) {
}
}
}
} else {
logger.error("base64图片为空!");
return false;
}
return true;
}
public static String getImageBase64Str(String imgSrcPath){
InputStream in = null;
byte[] data = null;
byte[] encodeBase64 = null;
String imgStr = "";
try {
in = new FileInputStream(imgSrcPath);
data = new byte[in.available()];
in.read(data);
encodeBase64 = Base64.encodeBase64(data);
imgStr = new String(encodeBase64);
} catch (IOException e) {
logger.error("后台异常",e);
} finally {
data = null;
encodeBase64 = null;
if(null != in) {
try {
in.close();
} catch (IOException e) {
}
}
}
return imgStr;
}
public static boolean generateBase64Image(String imgStr, String imgCreatePath){
if (imgStr == null){
return false;
}
byte[] b = null;
OutputStream out = null;
try {
b = Base64.decodeBase64(imgStr);
for(int i=0;i<b.length;++i) {
if(b[i]<0) {
b[i]+=256;
}
}
out = new FileOutputStream(imgCreatePath);
out.write(b);
out.flush();
return true;
} catch (Exception e){
return false;
} finally {
b = null;
try {
out.close();
} catch (IOException e) {
}
}
}
public static Map<String,String> getImageInfo(String imagePath){
Map<String,String> infoMap = new HashMap<>();
InputStream is = null;
BufferedImage src = null;
try{
is=new FileInputStream(imagePath);
src = javax.imageio.ImageIO.read(is);
int srcWidth = src.getWidth(null);
int srcHeight = src.getHeight(null);
infoMap.put("width", srcWidth+"");
infoMap.put("height", srcHeight+"");
}
catch(IOException ioe){
logger.error("获取图片尺寸时发生了异常!", ioe);
throw new RuntimeException(ioe);
} finally {
if(null != is) {
try {
is.close();
} catch (IOException e) {
}
}
src = null;
}
return infoMap;
}
public static boolean checkImageResolution(String imagePath,String imageHeight,String imageWidth){
Map<String,String> imageInfo=getImageInfo(imagePath);
String currentImageHeight=imageInfo.get("width");
String currentImageWidth=imageInfo.get("height");
logger.debug("tag:currentImageWidth:"+currentImageWidth+","+"currentImageHeight:"+currentImageHeight);
if(imageHeight.equals(currentImageHeight)&&imageWidth.equals(currentImageWidth)){
return true;
}
return false;
}
public static boolean checkImageSize(String imagePath,int imageHeight,int imageWidth){
Map<String,String> imageInfo=getImageInfo(imagePath);
String currentImageHeight=imageInfo.get("width");
String currentImageWidth=imageInfo.get("height");
if(imageHeight >= Integer.parseInt(currentImageHeight) && imageWidth >= Integer.parseInt(currentImageWidth)){
return true;
}
return false;
}
public static boolean changeImgSize(String imagePath,int width,int height){
boolean flag = false;
try{
File f = new File(imagePath);
if(f.getName().endsWith(".png")){
Thumbnails.of(f).size(width, height).outputFormat("png").toFile(f);
changeImgSuffix(f,"png");
}else{
Thumbnails.of(f).size(width, height).toFile(f);
}
flag = true;
} catch (IOException ioe) {
logger.error("改变图片分辨率时候出错", ioe);
}
return flag;
}
public static void changeImgSuffix(File f, String suffix){
String filename = f.getPath();
filename = filename.substring(0, filename.lastIndexOf(".") + 1)+suffix;
f.renameTo(new File(filename));
}
public static boolean checkImgNameByRegex(File f,String regex){
return f.getName().matches(regex);
}
public static boolean compressToTheSize(String imagePath, int size) {
final float rate = 0.9F;
File file = new File(imagePath);
if(file.exists()) {
int count = 0;
while(file.length() > 1024 * size) {
System.out.println("目前图片大小:" + file.length()/1024 + "KB,第"+(++count)+"次压缩图片!");
Map<String, String> imageInfo = getImageInfo(imagePath);
int width = Integer.parseInt(imageInfo.get("width"));
int height = Integer.parseInt(imageInfo.get("height"));
width *= rate;
height *= rate;
boolean changeImgSize = changeImgSize(imagePath, width, height);
System.out.println("压缩结果:" + changeImgSize);
}
System.out.println("最终图片大小:" + file.length()/1024 + "KB");
return true;
}
return false;
}
public static String imageTransitionBase64BySize(String imgPath, int sizekb){
File imgFile = new File(imgPath);
if(imgFile.exists()) {
if(imgFile.length() > 1024*sizekb) {
compressToTheSize(imgPath, 200);
}
String imgBase64 = getImageBase64Str(imgPath);
return imgBase64;
}
return null;
}
}