开发者

Display image in Android's ImageViewer widget using byte array created on .NET

I have a bunch of images stored in my server's database as byte arrays that I'd like to consume in my Android app.

The byte arrays were created from images in a Windows Phone 7 app, so using .NET's WriteableBitmap (wbmp) to save to an IsolatedStorageFileStream (isfs):

     wbmp.SaveJpeg(isfs, newWidth, newHeight, 0, 90);

In the Android app, I have an ImageView widget that I'm trying to use to display one of the images. I've tried using BitmapFactory to decode the byte array (payload):

    Bitmap bmp = BitmapFactory.decodeByteArray(payload, 0, payload.length);
    img1.setImageBitmap(bmp); 

But that doesn't work - no image displays and bmp is null when I step through the debugger. This seems to indicate that BitmapFactory could not properly decode the byte array.

For Windows Phone 7, I just load the byte[] (reality) into a MemoryStream (mstream), then call the Bitmap (bmp)'s SetSource method with that MemoryStream:

    mstream = new MemoryStream(reality);
    bmp.SetSource(mstream);

So then on Android I tried reading the byte array into a MemoryFile then loading the MemoryFile's InputStream using BitmapFactory:

    Me开发者_StackOverflowmoryFile mf;
        try {
            mf = new MemoryFile("myFile", payload.length);
            mf.writeBytes(payload, 0, 0, payload.length);
            InputStream is = mf.getInputStream();
            Bitmap bmp = BitmapFactory.decodeStream(is);
            img1.setImageBitmap(bmp); 
        } catch (IOException e) {               
            e.printStackTrace();
        }

But this still doesn't work.

How can I successfully load a byte array in this format in Android to display the image?


According to Bing and here, this error probably indicates an invalid image. I would carefully double-check that you are downloading the right URL. If so, then try printing the contents of that byte[] to the log (or check it in the debugger); see if it's an html message of some sort.

Bingo! Based on your extra information, this is Base64-encoded data. What you posted looked too much like plain text, so I tried running it through both uudecode and base64 -d on my Linux machine. The latter worked, generating a file that was recognized as JPEG.

Decoding this should be quite simple. Change this:

Bitmap bmp = BitmapFactory.decodeByteArray(payload, 0, payload.length);
img1.setImageBitmap(bmp); 

to this:

import android.util.Base64;
...
payload = Base64.decode(payload, Base64.Default);
Bitmap bmp = BitmapFactory.decodeByteArray(payload, 0, payload.length);
img1.setImageBitmap(bmp); 

Let me know!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜