生活随笔
收集整理的這篇文章主要介紹了
Java之Base64实现文件和字符串之间的转换
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
摘要:Java通過Base64加密解密實現文件和字符串之間的轉換!
Base64.java
package com.qdexam.util;import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;public class Base64 {// 圖片轉化成base64字符串public static String GetImageStr(String imgFile) {// 將圖片文件轉化為字節數組字符串,并對其進行Base64編碼處理InputStream in = null;byte[] data = null;// 讀取圖片字節數組try {if(imgFile==null||"".equals(imgFile)){imgFile="uploaddir/file/default.png";}in = new FileInputStream(imgFile);data = new byte[in.available()];in.read(data);in.close();} catch (IOException e) {e.printStackTrace();}// 對字節數組Base64編碼BASE64Encoder encoder = new BASE64Encoder();return encoder.encode(data);// 返回Base64編碼過的字節數組字符串}// base64字符串轉化成圖片public static boolean GenerateImage(String imgStr) { // 對字節數組字符串進行Base64解碼并生成圖片if (imgStr == null) // 圖像數據為空return false;BASE64Decoder decoder = new BASE64Decoder();try {// Base64解碼byte[] b = decoder.decodeBuffer(imgStr);for (int i = 0; i < b.length; ++i) {if (b[i] < 0) {// 調整異常數據b[i] += 256;}}// 生成jpeg圖片String imgFilePath = "d://222.jpg";// 新生成的圖片OutputStream out = new FileOutputStream(imgFilePath);out.write(b);out.flush();out.close();return true;} catch (Exception e) {return false;}}}
總結
以上是生活随笔為你收集整理的Java之Base64实现文件和字符串之间的转换的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。