简体   繁体   中英

How do I decode base64 blob to bitmap Android?

I have a Sqlite database in which a base64 code string is stored as a BLOB. I want to fetch this BLOB from the db and decode the base64 and show the image in an ImageView. I have read about encoding and decoding base64 and this is what I am using now.

        String[] image = new String[100000];
        if (cursor.moveToFirst()){ 
            int i = 0; 

        do {image[i] = cursor.getString(1);
         i++;} 

        while (cursor.moveToNext()); 
String imagebyte = image[0];
    byte[] decodedString = Base64.decode(imagebyte, Base64.DEFAULT);
    Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
    mImage.setImageBitmap(decodedByte);

But nothing shows up and I don't get any error messages. In order to pinpoint the problem I tried encoding and decoding an image, and then the bitmap showed. Is this the right way to decode it? I am here using cursor.getString(1), I have tried with using getBlob(1) also, but still nothing shows. Should I use getString or getBlob? Is there an easy way to check validity of the base64 code? THanks!

I have a Sqlite database in which a base64 code string is stored as a BLOB.

Why? Why not just put the image in the BLOB? What are you gaining by Base64-encoding it? It is costing you CPU time, garbage collection time, and storage space.

String[] image = new String[100000];

Why do you think you need 100,000 String objects?

do {image[i] = cursor.getString(1);
         i++;} 

        while (cursor.moveToNext());

Why are you retrieving this column for all rows in your result set, when you are only using one of them? Particularly considering you are obviously doing all of this on the main application thread, and therefore you will eventually crash with an application-not-responding (ANR) error?

Also, if this column is declared in your database a BLOB, are you sure that getString() will work as you expect?

Is this the right way to decode it?

That would depend upon how you encoded it.

Should I use getString or getBlob?

That depends on how you put the data in the table and what data type the column has. They should all match.

But I would just get rid of all the Base64 stuff and store the image byte array in the BLOB column, if you want an image in a table.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM