需求:

1. 将url路径图片保存为base64

2. 把base64图片保存在本地

 案例:


 想要把图片转成 base64,存起来。

url转成Base64的工具类代码

  imageBase64(String imgUrl) 方法,传入一个url图片路径,然后获取到base64字符串。

  generateImage(String imgStr, String imgFilePath)方法,传入base64字符串,传入一个保存图片的路径(就是要把图片保存在哪里)

package com.angus.tasks.utils;


import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

/**
* @author angus
* @date 2021/10/18 14:36
* @description
*/
public class ImageUtil {
/**
* 通过图片的url获取图片的base64字符串
* @param imgUrl 图片url
* @return 返回图片base64的字符串
*/
public static String imageBase64(String imgUrl) {
URL url = null;
InputStream is = null;

ByteArrayOutputStream outStream = null;

HttpURLConnection httpUrl = null;

try{
//解决中午路径失效问题
url = new URL(URLEncoder.encode(imgUrl, "utf-8").replace("%3A", ":").replace("%2F", "/"));
//url = new URL(imgUrl);
httpUrl = (HttpURLConnection) url.openConnection();
httpUrl.connect();
httpUrl.getInputStream();
is = httpUrl.getInputStream();
outStream = new ByteArrayOutputStream();
//创建一个Buffer字符串
byte[] buffer = new byte[1024];
//每次读取的字符串长度,如果为-1,代表全部读取完毕
int len = 0;
//使用一个输入流从buffer里把数据读取出来
while( (len=is.read(buffer)) != -1 ){
//用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
outStream.write(buffer, 0, len);
}

// 对字节数组Base64编码,注意这个Base64Util的类,是自己提供的。下边有提供代码。
return Base64Util.encode(outStream.toByteArray());

}catch (Exception e) {
e.printStackTrace();
try {
System.out.println(URLEncoder.encode(imgUrl, "utf-8").replace("%3A", ":").replace("%2F", "/"));
} catch (UnsupportedEncodingException unsupportedEncodingException) {
unsupportedEncodingException.printStackTrace();
}
}

finally{
if(is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(outStream != null) {
try {
outStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(httpUrl != null) {
httpUrl.disconnect();
}
}
return imgUrl;
}


/**
* 对字节数组字符串进行Base64解码并生成图片
* @param imgStr 图片数据
* @param imgFilePath 保存图片全路径地址
* @return
*/
public static boolean generateImage(String imgStr, String imgFilePath) {
//
if (imgStr == null) // 图像数据为空
return false;
try {
// Base64解码
byte[] b = Base64Util.decode(imgStr);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {// 调整异常数据
b[i] += 256;
}
}
// 生成jpg图片
OutputStream out = new FileOutputStream(imgFilePath);
out.write(b);
out.flush();
out.close();
return true;
} catch (Exception e) {
return false;
}
}
public static void main(String[] args) throws UnsupportedEncodingException {

String url = "javascript:void(0)";

String s = imageBase64(url);

System.out.println(s);

//generateImage(s, "C:\\Users\\angus\\Desktop\\image.jpg");
//System.out.println(s);
}

}

 

Base64工具类

  注意要引入的是自己写的工具类。

package com.angus.tasks.utils;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.imageio.stream.FileImageInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
* @author angus
* @date 2021/10/18 15:05
* @description
*/
public class Base64Util {
/**
* 字符串转图片
* @param base64Str
* @return
*/
public static byte[] decode(String base64Str){
byte[] b = null;
BASE64Decoder decoder = new BASE64Decoder();
try {
b = decoder.decodeBuffer(replaceEnter(base64Str));
} catch (IOException e) {
e.printStackTrace();
}
return b;
}

/**
* 图片转字符串
* @param image
* @return
*/
public static String encode(byte[] image){
BASE64Encoder decoder = new BASE64Encoder();
return replaceEnter(decoder.encode(image));
}

public static String encode(String uri){
BASE64Encoder encoder = new BASE64Encoder();
return replaceEnter(encoder.encode(uri.getBytes()));
}

/**
*
* @path 图片路径
* @return
*/

public static byte[] imageTobyte(String path){
byte[] data = null;
FileImageInputStream input = null;
try {
input = new FileImageInputStream(new File(path));
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int numBytesRead = 0;
while((numBytesRead = input.read(buf)) != -1){
output.write(buf, 0, numBytesRead);
}
data = output.toByteArray();
output.close();
input.close();

} catch (Exception e) {
e.printStackTrace();
}

return data;
}



public static String replaceEnter(String str){
String reg ="[\n-\r]";
Pattern p = Pattern.compile(reg);
Matcher m = p.matcher(str);
return m.replaceAll("");
}

}