java中保存图片到本地_java保存网络图片到本地

导入两个包

commons-codec

commons-io

导入okhttp

com.squareup.okhttp3

okhttp

3.6.0

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();

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值