Obtain the image from the network. The data is an inputstream Stream object. Then, call the decodestream () method of bitmapfactory to decode and obtain the image.CodeAs follows:
Private Bitmap geturlbitmap (string URL)
{
Bitmap bm;
Try {
URL imageurl = New URL (URL );
Httpurlconnection Conn = (Httpurlconnection) imageurl. openconnection ();
Conn. Connect ();
Inputstream is = Conn. getinputstream ();
// Byte [] bt = getbytes (is ); // The comments are decoded in another way.
// Bm = bitmapfactory. decodebytearray (BT, 0, BT. Length );
BM = Bitmapfactory. decodestream (is ); // If this decoding method is used, the decoding problem may occur on the API of earlier versions.
Is. Close ();
Conn. Disconnect ();
Return BM;
}
Catch (Malformedurlexception E)
{
E. printstacktrace ();
}
Catch (Ioexception E)
{
E. printstacktrace ();
}
Return Null ;
}
When the result is running, the compiler prompts:Debug/Skia(Xxx): ---Decoder->Decode returnedFalse
It has been confirmed that there is no problem with the data stream obtained from the network, but an error occurs during image decoding. I found a lot of information online and did not come up with the exact reason. However, there are several comments worth noting.
One way is that there are a lot of internal errors in APIs of earlier Android versions. This problem occurs when I select 2.1api level 7 and 2.2api Level 8 During code running, after 2.3 API level 9 is selected, the image can be decoded normally.
My other method is to use another decoding method to decode the image. For details, see the two lines commented in the Code. The decodebytearray () method can also be used to decode the image in earlier versions of APIs, solved this problem.
Getbytes (inputstream is) is a method to convert an inputstream object to a byte []. The Code is as follows:
Private Byte [] Getbytes (inputstream is) Throws Ioexception {
Bytearrayoutputstream baos = New Bytearrayoutputstream ();
Byte [] B = New Byte [ 1024 ];
Int Len = 0 ;
While (Len = Is. Read (B, 0 , 1024 )) ! = - 1 )
{
Baos. Write (B, 0 , Len );
Baos. Flush ();
}
Byte [] Bytes = Baos. tobytearray ();
Return Bytes;
}