开发者

How to load image from url

开发者 https://www.devze.com 2023-01-28 11:56 出处:网络
I am writing a little picture frame app for android that is using opengl for part of the UI.This portion needs to get images from flickr and load them into a texture.The code I have below is functiona

I am writing a little picture frame app for android that is using opengl for part of the UI. This portion needs to get images from flickr and load them into a texture. The code I have below is functional most of the time, but it has a Thread.sleep() kludge in between getting the input stream from the connection and the bitmap factory decoding the stream:

            URL url = new URL("http://farm5.static.flickr.com/4132/5168797476_7a85deb2be_b.jpg");
            URLConnection con = url.openConnection();
            InputStream is = con.getInputStream();
            Thread.sleep(250); //What am I actually waiting for?
            sourc开发者_开发知识库eBitmap = BitmapFactory.decodeStream(is);

How do I get around using the sleep() method in favor of something that makes logical sense?

I am testing on a samsung galaxy tab not in the emulator


I think you should implement AsyncTask. Refer this: http://developer.android.com/resources/articles/painless-threading.html

public void onClick(View v) {
  new DownloadImageTask().execute("http://example.com/image.png");
}

private class DownloadImageTask extends AsyncTask<string, void,="" bitmap=""> {
     protected Bitmap doInBackground(String... urls) {
         return loadImageFromNetwork(urls[0]);
     }

     protected void onPostExecute(Bitmap result) {
         mImageView.setImageBitmap(result);
     }
 }

I hope it helps you !!


This seems less than ideal, but if you read the stream byte by byte into a buffer and then pass the byte array to the BitmapFactory it works correctly.

            URL url = new URL("http://farm5.static.flickr.com/4132/5168797476_7a85deb2be_b.jpg");
            URLConnection con = url.openConnection();
            con.connect();
            int fileLength = con.getContentLength();
            InputStream is = con.getInputStream();
            byte[] bytes = new byte[fileLength];
            for(int i=0;i<fileLength;i++) {
                bytes[i] = (byte)is.read();
            }
            sourceBitmap = BitmapFactory.decodeByteArray(bytes, 0, fileLength);

I tried reading the bytes into the buffer all at once with is.read(bytes, 0, fileLength) but it did not reliably fill the buffer completely unless I waited a moment before calling the read. Is it possible that android implementation of InputStream's read method is flawed causing the BitmapFactory's decodeStream method to fail due to incomplete data?

0

精彩评论

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