import java.io.FileInputStream;
2 import java.io.FileOutputStream;
3 import java.io.IOException;
4 import java.io.InputStream;
5 import java.io.OutputStream;
6
7 import org.apache.commons.codec.binary.Base64;
8
9
10 /**
11 * 将图片转换为Base64<br>
12 * 将base64编码字符串解码成img图片
13 * @创建时间 2015-06-01 15:50
14 *
15 */
16 public class Img2Base64Util {
17
18 public static void main(String[] args) {
19 String imgFile = "d:\\3.jpg";//待处理的图片
20 String imgbese=getImgStr(imgFile);
21 System.out.println(imgbese.length());
22 System.out.println(imgbese);
23 String imgFilePath = "d:\\332.jpg";//新生成的图片
24 generateImage(imgbese,imgFilePath);
25 }
26 /**
27 * 将图片转换成Base64编码
28 * @param imgFile 待处理图片
29 * @return
30 */
31 public static String getImgStr(String imgFile){
32 //将图片文件转化为字节数组字符串,并对其进行Base64编码处理
33
34
35 InputStream in = null;
36 byte[] data = null;
37 //读取图片字节数组
38 try
39 {
40 in = new FileInputStream(imgFile);
41 data = new byte[in.available()];
42 in.read(data);
43 in.close();
44 }
45 catch (IOException e)
46 {
47 e.printStackTrace();
48 }
49 return new String(Base64.encodeBase64(data));
50 }
51
52 /**
53 * 对字节数组字符串进行Base64解码并生成图片
54 * @param imgStr 图片数据
55 * @param imgFilePath 保存图片全路径地址
56 * @return
57 */
58 public static boolean generateImage(String imgStr,String imgFilePath){
59 //
60 if (imgStr == null) //图像数据为空
61 return false;
62
63 try
64 {
65 //Base64解码
66 byte[] b = Base64.decodeBase64(imgStr);
67 for(int i=0;i<b.length;++i)
68 {
69 if(b[i]<0)
70 {//调整异常数据
71 b[i]+=256;
72 }
73 }
74 //生成jpeg图片
75
76 OutputStream out = new FileOutputStream(imgFilePath);
77 out.write(b);
78 out.flush();
79 out.close();
80 return true;
81 }
82 catch (Exception e)
83 {
84 return false;
85 }
86 }
87 }
最年轻的大叔
发表于2022-12-16 17:03:19
2022-12-16 17:03:19
最后回复
171