Search code examples
androidbitmapandroid-image

android bitmap isn't created from base64


I have an Android application which sends an image to a web service. I want to send the same photo back from the web service to Android.

I made a test program to compare the base64 data that's sent from Android to the server and the base64 that's sent back from server to Android -- they are exactly equal.

I want to use the base 64 string to create a bitmap, so I tried this:

String image = client1.getBaseURI("restaurantFoods/OneFood/"
            + this.getID() + "/getImage");

byte[] decodedString = Base64.decode(image, Base64.DEFAULT);
        Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0,
                decodedString.length);
if(decodedByte == null){
            Log.d(this.getFoodItem().getName(), image);
            Log.d("isNull", "Yes");
        }
        else{
            Log.d("isNull", "No");}

I keep getting null because the log just prints "YES".

Can anyone please help?

If you want to know how I encode the image it is as follows:

private String getBase64(Bitmap bitmap) {
        String imgString = Base64.encodeToString(getBytesFromBitmap(bitmap),
                Base64.NO_WRAP);
        return imgString;
    }
private byte[] getBytesFromBitmap(Bitmap bitmap) {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(CompressFormat.JPEG, 70, stream);
        return stream.toByteArray();
    }
Bitmap icon = BitmapFactory.decodeResource(this.getResources(),
                    R.drawable.pizza);
String iconBase64 = this.getBase64(icon);

Solution

  • Try this to bitmap;

    public Bitmap convert(String img){
        byte[] b = Base64.decode(img, Base64.DEFAULT);
        return BitmapFactory.decodeByteArray(b, 0, b.length);
    }
    

    And this to String

        public String convert(Bitmap bm, int quality){
        ByteArrayOutputStream baos = new ByteArrayOutputStream();  
        bm.compress(Bitmap.CompressFormat.JPEG, quality, baos); 
    
        byte[] byt = baos.toByteArray(); 
        bm.recycle();
        return Base64.encodeToString(byt, Base64.DEFAULT);
    }
    

    Really I don't see any real problems with your code, but these have worked for me so I suggest that you try them and see if that is actually your problem.