Base64到底是什么東西呢?
Base64是網絡上常見的用於傳輸8bit字節碼的編碼方式之一 ,是用來將非ASCII字符的數據轉換成ASCII字符的一種方法, 有些人和書本會將編碼寫成加密算法,這其實是欠妥的。因為任何人拿到編碼后的數據都能轉化成原始數據,算法是透明的,也不存在秘鑰的概念。
為什么要將圖片轉為base64格式
便於網絡傳輸:由於某些系統中只能使用ASCII字符,Base64就可以將非ASCII字符的數據轉換成ASCII字符。舉個簡單的例子,你使用SMTP協議 (Simple Mail Transfer Protocol 簡單郵件傳輸協議)來發送郵件。因為這個協議是基於文本的協議,所以如果郵件中包含一幅圖片,我們知道圖片的存儲格式是二進制數據(binary data),而非文本格式,我們必須將二進制的數據編碼成文本格式,這時候Base 64 Encoding就派上用場了
不可見性:我們知道在計算機中任何數據都是按ascii碼存儲的,而ascii碼的128~255之間的值是不可見字符。而在網絡上交換數據時,比如說從A地傳到B地,往往要經過多個路由設備,由於不同的設備對字符的處理方式有一些不同,這樣那些不可見字符就有可能被處理錯誤,這是不利於傳輸的。所以就先把數據先做一個Base64編碼,統統變成可見字符,這樣出錯的可能性就大降低了。
轉換過程:
文件轉Base64字符串:讀取文件的輸入流,因為文件流是字節流,所以要放到byte數組(字節數組,byte取值范圍-128~127)里,
然后對byte數組做Base64編碼,返回字符串。
Base64字符串轉文件:對Base64編碼的字符串進行Base64解碼,得到byte數組,利用文件輸出流將byte數據寫入到文件。
File轉Base64
public static String file2Base64(File file) { if(file==null) { return null; } String base64 = null; FileInputStream fin = null; try { fin = new FileInputStream(file); byte[] buff = new byte[fin.available()]; fin.read(buff); base64 = Base64.encode(buff); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (fin != null) { try { fin.close(); } catch (IOException e) { e.printStackTrace(); } } } return base64; }
Base64轉File
public static File base64ToFile(String base64) { if(base64==null||"".equals(base64)) { return null; } byte[] buff=Base64.decode(base64); File file=null; FileOutputStream fout=null; try { file = File.createTempFile("tmp", null); fout=new FileOutputStream(file); fout.write(buff); } catch (IOException e) { e.printStackTrace(); }finally { if(fout!=null) { try { fout.close(); } catch (IOException e) { e.printStackTrace(); } } } return file; }
文件流轉Base64字符串
public static String getBase64FromInputStream(InputStream in) { // 將圖片文件轉化為字節數組字符串,並對其進行Base64編碼處理 byte[] data = null; // 讀取圖片字節數組 try { ByteArrayOutputStream swapStream = new ByteArrayOutputStream(); byte[] buff = new byte[100]; int rc = 0; while ((rc = in.read(buff, 0, 100)) > 0) { swapStream.write(buff, 0, rc); } data = swapStream.toByteArray(); } catch (IOException e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } return new String(Base64.encodeBase64(data)); }