Not able to convert Bitmap to perfect Base64 String in Android?

后端 未结 3 917
南笙
南笙 2021-02-13 21:59

I am working on an application in which I need to capture an Image from camera. After capture, I have to convert the Bitmap to Base64. After converting to Base6

3条回答
  •  走了就别回头了
    2021-02-13 22:49

    When I convert that Base64 to image, I am getting INCOMPLETE IMAGE

    Try to do this with your image Bitmap and check if something is not as expected:

    Bitmap originalBitmap = (Bitmap) data.getExtras().get("data"); //or whatever image you want
    Log.d(TAG, "original bitmap byte count: " + originalBitmap.getByteCount());
    
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    originalBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
    Log.d(TAG, "byte array output stream size: " + baos.size());
    
    byte[] outputByteArray = baos.toByteArray();
    Log.d(TAG, "output byte array length: " + outputByteArray.length);
    
    String base64EncodedString = Base64.encodeToString(outputByteArray, Base64.DEFAULT);
    Log.d(TAG, "base64 encoded string length: " + base64EncodedString.length());
    
    byte[] inputByteArray = Base64.decode(base64EncodedString, Base64.DEFAULT);
    Log.d(TAG, "input byte array length: " + inputByteArray.length);
    
    ByteArrayInputStream bais = new ByteArrayInputStream(inputByteArray);
    Log.d(TAG, "byte array input stream size: " + bais.available());
    
    Bitmap decodedBitmap = BitmapFactory.decodeStream(bais);
    Log.d(TAG, "decoded bitmap byte count: " + decodedBitmap.getByteCount());
    
    Log.d(TAG, "decoded bitmap same as original bitmap? " + decodedBitmap.sameAs(originalBitmap));
    

    If all is ok then the problem is not the base64 encoding. Let me know!

提交回复
热议问题