1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > Base64对图片进行编码解码

Base64对图片进行编码解码

时间:2020-05-09 03:55:11

相关推荐

Base64对图片进行编码解码

图片编码得到字符串:

package com.zhbr.util;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 Decoder.BASE64Decoder;import Decoder.BASE64Encoder;public class Base64Utils {/*** 图片转化成base64字符串* @param imgPath* @return*/public static String GetImageStr(String imgPath) {// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理String imgFile = imgPath;// 待处理的图片InputStream in = null;byte[] data = null;String encode = null; // 返回Base64编码过的字节数组字符串// 对字节数组Base64编码BASE64Encoder encoder = new BASE64Encoder();try {// 读取图片字节数组in = new FileInputStream(imgFile);data = new byte[in.available()];in.read(data);encode = encoder.encode(data);} catch (IOException e) {e.printStackTrace();} finally {try {in.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}return encode;}/*** base64字符串转化成图片** @param imgData* 图片编码* @param imgFilePath* 存放到本地路径* @return* @throws IOException*/@SuppressWarnings("finally")public static boolean GenerateImage(String imgData, String imgFilePath) throws IOException { // 对字节数组字符串进行Base64解码并生成图片if (imgData == null) // 图像数据为空return false;BASE64Decoder decoder = new BASE64Decoder();OutputStream out = null;try {out = new FileOutputStream(imgFilePath);// Base64解码byte[] b = decoder.decodeBuffer(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 blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} finally {out.flush();out.close();return true;}}public static void main(String[] args) throws IOException {String imageStr = Base64Utils.GetImageStr("C:\\Users\\yanni\\Pictures\\27.jpg");System.out.println(imageStr);}}

读取经过编码的字符串,解码成图片:

/*** 读取txt文件的内容* @param file 想要读取的文件对象* @return 返回文件内容*/public static String txt2String(File file){String result = "";try{BufferedReader br = new BufferedReader(new FileReader(file));//构造一个BufferedReader类来读取文件String s = null;while((s = br.readLine())!=null){//使用readLine方法,一次读一行result = result + s;}br.close();}catch(Exception e){e.printStackTrace();}return result;}public static void main(String[] args) throws IOException, SQLException {File file = new File("C:\\Users\\yanni\\Desktop\\1.txt");String s = txt2String(file);Base64Utils.GenerateImage(s, "C:\\Users\\yanni\\Desktop\\29.jpg");}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。