<dependency>
<groupId>com.google.api-client</groupId>
<artifactId>google-api-client</artifactId>
<version>1.32.2</version>
</dependency>
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import com.google.api.client.util.Base64;
public class Base64Utils {
/**
* 图片转化成base64字符串
* @param imgPath
* @return string
*/
public static String imageToBase64(String imgPath) {
String imgFile = imgPath;// 待处理的图片
InputStream in = null;
byte[] data = null;
String encode = null; // 返回Base64编码过的字节数组字符串
// 对字节数组Base64编码
try {
// 读取图片字节数组
in = new FileInputStream(imgFile);
data = new byte[in.available()];
in.read(data);
encode = Base64.encodeBase64String(data);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return encode;
}
/**
* base64字符串转化成图片
* @param imgData 图片Base64编码
* @param imgFilePath 存放到本地路径
* @return bool
* @throws IOException
*/
public static boolean base64ToImage(String imgData, String imgFilePath) throws IOException {
if (imgData == null) // 图像数据为空
return false;
OutputStream out = null;
try {
out = new FileOutputStream(imgFilePath);
// Base64解码
byte[] b = Base64.decodeBase64(imgData);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {// 调整异常数据
b[i] += 256;
}
}
out.write(b);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
out.flush();
out.close();
return true;
}
}
}