2014-10-29 21 views
0

我想使用gzip將位圖轉換爲base64。Android - 將壓縮位圖(gzip)轉換爲Base64導致數據丟失

我試圖解決here,但我得到這個錯誤GZIP不能得到解決或無法在現場

我的解決方案如下工作,但圖像底部

enter image description here

被切斷

這是我的代碼:

 Bitmap myBitmap = BitmapFactory.decodeFile("\path\to\file.jpg"); 
     ByteArrayOutputStream stream=new ByteArrayOutputStream(); 
     GZIPOutputStream gzipOstream=null; 
     try { 
      gzipOstream=new GZIPOutputStream(stream); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     myBitmap.compress(Bitmap.CompressFormat.JPEG, 100, gzipOstream); 
     byte[] byteArry=stream.toByteArray(); 
     String encodedImage = Base64.encodeToString(byteArry, Base64.NO_WRAP); 
     try { 
      gzipOstream.close(); 
      stream.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

會這樣代碼會使圖像丟失數據,還是在服務器端?

回答

2

調用mBitmap.compress();後調用gzipOstream.flush();這保證了輸出字節流包含所有內容。然後你的toByteArray();將得到當前丟失的數據。

試試這個:

Bitmap myBitmap = BitmapFactory.decodeFile("\path\to\file.jpg"); 
ByteArrayOutputStream stream = new ByteArrayOutputStream(); 
try { 
    GZIPOutputStream gzipOstream = null; 
    try { 
     gzipOstream = new GZIPOutputStream(stream); 
     myBitmap.compress(Bitmap.CompressFormat.JPEG, 100, gzipOstream); 
     gzipOstream.flush(); 
    } finally { 
     gzipOstream.close(); 
     stream.close(); 
    } 
} catch (IOException e) { 
    e.printStackTrace(); 
    stream = null; 
} 
if(stream != null) { 
    byte[] byteArry=stream.toByteArray(); 
    String encodedImage = Base64.encodeToString(byteArry, Base64.NO_WRAP); 
    // do something with encodedImage 
} 
+0

,對我沒有工作。仍然在圖像上灰色 – 2014-10-29 20:09:04

+0

已更新的示例。 – Simon 2014-10-29 20:26:06

+0

你是我的英雄:)完美的工作。非常感謝你。 – 2014-10-29 20:30:10