圖片和字符串相互轉化
阿新 • • 發佈:2018-07-21
span class enc tst 寫入 package ring print try
功能的實現應用到了java io
以下是代碼實現:
package myProject; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.Base64; import java.util.Base64.Decoder; import java.util.Base64.Encoder;public class ImageString { public static void main(String[] args){ File file =new File("D:\\1.jpg"); File file_new=new File("D:\\images\\2.jpg"); try{ //讀圖片文件(圖片轉化成字符串) FileInputStream fileInputStream=new FileInputStream(file); BufferedInputStream bufferedInputStream=new BufferedInputStream(fileInputStream); byte[] b=new byte[bufferedInputStream.available()]; bufferedInputStream.read(b); bufferedInputStream.close(); fileInputStream.close(); // 對字節數組Base64編碼 Encoder encoder=Base64.getEncoder();// BASE64Encoder encoder = new BASE64Encoder(); // 返回Base64編碼過的字節數組字符串 // String str=encoder.encode(b); String str=encoder.encodeToString(b); System.out.println(str); //字符串轉化成圖片 //將讀的內容寫入新的文件 if(!file_new.exists()){ file_new.createNewFile(); } FileOutputStream fileOutputStream=new FileOutputStream(file_new); BufferedOutputStream bufferedOutputStream=new BufferedOutputStream(fileOutputStream); //解碼 //BASE64Decoder decoder = new BASE64Decoder(); //byte[] b2=decoder.decodeBuffer(str); Decoder decoder=Base64.getDecoder(); byte[] b2=decoder.decode(str); bufferedOutputStream.write(b2); bufferedOutputStream.flush(); bufferedOutputStream.close(); fileOutputStream.close(); }catch(Exception e){ e.printStackTrace(); } } }
這裏用到了BASE64編碼解碼
圖片和字符串相互轉化