2016-11-18 85 views
0

該應用程序將base64解碼爲PNG,但是當我將文件編碼回base64以發送到服務器時,生成的base64不同並且不會生成圖像。Android編碼PNG到base64字符串產生無效結果

這裏原來的base64字符串的開頭: /9j/4AAQSkZJRgABAQAASABIAAD/4QBMRXhpZgAATU0AKgAAAAgAAgESAAMAAAABAAYAAIdp

這裏是BASE64的開始是從編碼和PNG文件後: iVBORw0KGgoAAAANSUhEUgAAD8AAAAvQCAIAAABPl1n3AAAAA3NCSVQICAjb4U/gAAAgAElEQVR4nO

這是我的代碼使用的文件進行Base64編碼:

BitmapFactory.Options options = new BitmapFactory.Options(); 
     options.inDither = true; 
     options.inScaled = false; 
     options.inPreferredConfig = Bitmap.Config.ARGB_8888; 
     options.inDither = false; 

     File file = new File(root +"/saved_images/"+note.imageLocation); 
     if(file.exists()){ 
      // TODO perform some logging or show user feedback 
      try { 
      Bitmap myBitmap = BitmapFactory.decodeFile(root +"/saved_images/"+note.imageLocation, options); 
      ByteArrayOutputStream stream = new ByteArrayOutputStream(); 


      myBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream); 
      byte[] byteArray = stream.toByteArray(); 

      JSONObject object =new JSONObject(); 
       object.put("image_type", "image/png"); 
       object.put("image_data", Base64.encodeToString(byteArray, Base64.DEFAULT)); 


       if (note.serverID == -1) { 
        toReturn.put(String.valueOf(i), object); 
       }else{ 
        toReturn.put(String.valueOf(note.serverID), object); 
       } 
      } catch (Exception e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 

      i--; 
     }else{ 
      Log.i("File Not Found", "NoteModel - "+file); 
     } 
+0

'該應用程序將base64解碼爲PNG'。您應該開始向我們顯示該代碼。而且你也沒有說出png的保存位置。你把它保存爲一個文件嗎? – greenapps

回答

1

如果您確實收到了base64字符串並將其解碼爲保存到文件而不使用中間位圖的png字節,則應該只將該png文件加載到字節緩衝區中,並將該字節緩衝區編碼爲base64字符串,將上傳。

如果您確實使用位圖來保存圖像,那麼這是一個壞主意。

請勿使用類BitmapBitmapFactory來啓動和下載文件。你將會得到不同的圖像。

0

請試試這個代碼,

public String encodeToBase64(Bitmap image) { 
    Bitmap immagex = Bitmap.createScaledBitmap(image, 350, 350, true); 
    ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
    immagex.compress(Bitmap.CompressFormat.PNG, 100, baos); 
    byte[] b = baos.toByteArray(); 
    String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT); 
    Log.e("LOOK", imageEncoded); 
    return "data:image/png;base64," + imageEncoded.replace(" ", "").replace("\n", ""); 
} 

public Bitmap encodeToBitmap(String encodedImage) { 
    encodedImage = encodedImage.substring(encodedImage.indexOf(",") + 1); 
    byte[] decodedString = Base64.decode(encodedImage, Base64.DEFAULT); 
    Bitmap bitmap = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); 
    return bitmap; 
} 
+0

感謝您的回答。這並沒有什麼區別,我很害怕:( – jampez77

+0

嘗試兩種解碼方法以及編碼,如果這可能有幫助 –

+0

仍然沒有幫助不幸:/ – jampez77

1

試試我的solution,它解釋瞭如何將位圖編碼爲base64,併成功將base64解碼爲位圖。