1. 程式人生 > >將圖片檔案轉化為位元組陣列字串,並對其進行Base64編碼處理和 對位元組陣列字串進行Base64解碼並生成圖片

將圖片檔案轉化為位元組陣列字串,並對其進行Base64編碼處理和 對位元組陣列字串進行Base64解碼並生成圖片

public static String imageToBase64(String path) {
	    // 將圖片檔案轉化為位元組陣列字串,並對其進行Base64編碼處理
	        byte[] data = null;
	        // 讀取圖片位元組陣列
	        try {

	            InputStream in = new FileInputStream(path);

	            data = new byte[in.available()];

	            in.read(data);

	            in.close();
	        } catch (IOException e) {
	            e.printStackTrace();
	        }
	        // 對位元組陣列Base64編碼
	        BASE64Encoder encoder = new BASE64Encoder();
	            // 返回Base64編碼過的位元組陣列字串
	        return encoder.encode(data);
	    }
	//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 = "E:\\a\\m\\new.jpg";//新生成的圖片  
            OutputStream out = new FileOutputStream(imgFilePath);      
            out.write(b);  
            out.flush();  
            out.close();  
            return true;  
        }   
        catch (Exception e)   
        {  
            return false;  
        }  
    }  
		public static void main(String[] args) throws Exception {
			String str=imageToBase64("I:\\20180620154920_102036998.jpg");
			GenerateImage(str);
		}