1. 程式人生 > >圖片(路徑)轉換為陣列字串 及字串轉換為圖片並存儲至指定目錄

圖片(路徑)轉換為陣列字串 及字串轉換為圖片並存儲至指定目錄

package diiwon;  
import java.io.File;  
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 imagebean {   

 

    public static String GetImageStr(String imgFilePath) {// 將圖片檔案轉化為位元組陣列字串,並對其進行Base64編碼處理  
        if(imgFilePath == null || imgFilePath == ""){  
            return "";  
        }  
        File file = new File(imgFilePath);  
        if(!file.exists()){  
            return "";  
        }  
        byte[] data = null;  
        // 讀取圖片位元組陣列  
        try {  
            InputStream in = new FileInputStream(imgFilePath);  
            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, String imgFilePath) {  
        if (imgStr == null || imgStr == "") // 影象資料為空  
            return false;  
        BASE64Decoder decoder = new BASE64Decoder();  
        try {  
            // Base64解碼  
            byte[] bytes = decoder.decodeBuffer(imgStr);  
            for (int i = 0; i < bytes.length; ++i) {  
                if (bytes[i] < 0) {// 調整異常資料  
                    bytes[i] += 256;  
                }  
            } 
 
            // 生成jpeg圖片  
            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(bytes);  
            out.flush();  
            out.close();  
            return true;  
        }catch (Exception e){  
            return false;  
        }  
    }  
    








    public static void main(String[] args) {    
        // 測試從圖片檔案轉換為Base64編碼    
        String strImg = GetImageStr("C:\\bg.jpg");  
        System.out.println(strImg);  
        // 測試從Base64編碼轉換為圖片檔案   
        GenerateImage(strImg, "C:\\bd.jpg");  
    }