导入两个包
commons-codec
commons-io
导入okhttp
<dependencies>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.6.0</version>
</dependency>
</dependencies>
import java.io.*;
public class ImageBase64Utils {
public static String bytesToBase64(byte[] bytes) {
return org.apache.commons.codec.binary.Base64.encodeBase64String(bytes);// 返回Base64编码过的字节数组字符串
}
/**
* 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
*
* @param path 图片路径
* @return base64字符串
*/
public static String imageToBase64(String path) throws IOException {// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
byte[] data = null;
// 读取图片字节数组
InputStream in = null;
try {
in = new FileInputStream(path);
data = new byte[in.available()];
in.read(data);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return org.apache.commons.codec.binary.Base64.encodeBase64String(data);// 返回Base64编码过的字节数组字符串
}
/**
* 处理Base64解码并写图片到指定位置
*
* @param base64 图片Base64数据
* @param path 图片保存路径
* @return
*/
public static boolean base64ToImageFile(String base64, String path) throws IOException {// 对字节数组字符串进行Base64解码并生成图片
// 生成jpeg图片
try {
OutputStream out = new FileOutputStream(path);
return base64ToImageOutput(base64, out);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return false;
}
/**
* 处理Base64解码并输出流
*
* @param base64
* @param out
* @return
*/
public static boolean base64ToImageOutput(String base64, OutputStream out) throws IOException {
if (base64 == null) { // 图像数据为空
return false;
}
try {
// Base64解码
byte[] bytes = org.apache.commons.codec.binary.Base64.decodeBase64(base64);
for (int i = 0; i < bytes.length; ++i) {
if (bytes[i] < 0) {// 调整异常数据
bytes[i] += 256;
}
}
// 生成jpeg图片
out.write(bytes);
out.flush();
return true;
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
String url = "http://adminweb.himytunai.com/api/auth/captcha?width=120&height=50&serialId=fjKDNFie";
try {
OkHttpClient client = new OkHttpClient();
//获取请求对象
Request request = new Request.Builder().url(url).build();
//获取响应体
ResponseBody body = client.newCall(request).execute().body();
//获取流
InputStream in = body.byteStream();
byte[] bytes = IOUtils.toByteArray(in);
System.out.println(new String(bytes));
String s = ImageBase64Utils.bytesToBase64(bytes);
ImageBase64Utils.base64ToImageFile(s, "F:\\javatest\\src\\main\\java\\dfdfd.png");
} catch (IOException e) {
e.printStackTrace();
}
}
}
网友评论