所需的包
import java.io.*;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
编码
public static String getImageStr(String imgPath) {
InputStream inputStream = null;
byte[] data = null;
String base64="";
try {
File file=new File(imgPath);
if (!file.exists()) {
return "";
}
inputStream = new FileInputStream(imgPath);
data = new byte[inputStream.available()];
inputStream.read(data);
inputStream.close();
BASE64Encoder encoder = new BASE64Encoder();
base64=encoder.encode(data);
} catch (IOException e) {
e.printStackTrace();
return "";
}
return base64;
}
解码
public static Boolean getBase64Str(String imgDate,String imgPath){
if (imgDate == null){
return false;
}
BASE64Decoder decoder = new BASE64Decoder();
OutputStream out = null;
try {
out = new FileOutputStream(imgPath);
byte[] b = decoder.decodeBuffer(imgDate);
for (int i = 0; i < b.length; i++){
if (b[i] < 0){
b[i] += 256;
}
}
out.write(b);
}catch (FileNotFoundException e){
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
return true;
}
给图片进行压缩
public static String imageGenerateSmall(String path){
try {
log.info("文件完整的路径:"+path);
File bigFile = new File(path);
if (bigFile.exists() && bigFile.isFile()){
log.info("bigFile大小:"+bigFile.length());
Image image = ImageIO.read(bigFile);
log.info("OK:"+path);
int width = image.getWidth(null);
int height = image.getHeight(null);
if(bigFile.length() > (1024*100) || width > 960 || height > 960) {
int arr [] = imageWH(width,height);
int widthSmall = arr[0];
int heightSmall = arr[1];
BufferedImage buffi = new BufferedImage(widthSmall, heightSmall, BufferedImage.TYPE_INT_RGB);
Graphics g = buffi.getGraphics();
g.drawImage(image, 0, 0, widthSmall, heightSmall, null);
g.dispose();
ImageIO.write(buffi, "jpg", new File(path));
Thread.sleep(200);
}
return getImageStr(path);
}
} catch (Exception e) {
e.printStackTrace();
String info = getExceptionAllInfo(e);
log.error("压缩图片异常:"+info);
return "";
}
return "";
}
public static int[] imageWH(int w, int h){
if(w > 960 || h > 960) {
int wh = imageW(w);
int he = imageH(h);
return imageWH(wh, he);
}else {
return new int[] {w,h};
}
}
public static int imageW(int w){
w = (int) (w / 2);
return w;
}
public static int imageH(int h){
h = (int) (h / 2);
return h;
}