将下载的图像转换为位图

时间:2015-10-06 18:25:49

标签: android bitmap

我正在尝试从url异步下载图像,然后将其转换为位图,我可以异步下载图像而不会出现任何错误,但我发现很难将其转换为位图。 / p>

这是我的代码

public class MainActivity extends Activity {

    @Override
     protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

            // This is my image link
            String url="www.myimagelink.com";

            // This downloads the image from the servers
            new DownloadImage(ImageView).execute(url);

            //this is suppose to convert my bitmap into a byteArray, but I cant seem to convert my image downloaded to a bitmap

             final byte[] byteArray;
             ByteArrayOutputStream stream = new ByteArrayOutputStream();
             bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
             byteArray = stream.toByteArray();

        }



    private class  DownloadImage extends AsyncTask<String, Void, Bitmap> {
        ImageView bmImage;

        public DownloadImage(ImageView bmImage) {
            this.bmImage = bmImage;
        }

        protected Bitmap doInBackground(String... urls) {
            String urldisplay = urls[0];
            Bitmap mIcon11 = null;
            try {
                InputStream in = new java.net.URL(urldisplay).openStream();
                mIcon11 = BitmapFactory.decodeStream(in);
            } catch (Exception e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return mIcon11;
        }

        protected void onPostExecute(Bitmap result) {
            bmImage.setImageBitmap(result);

        }
    }

}

请问如何将下载的图像转换为位图?感谢

2 个答案:

答案 0 :(得分:1)

将您的in stream转换为字符串,然后将其解码为位图,如下所示:

String str = IOUtils.toString(in, encoding); 
byte[] decodedString = Base64.decode(str, Base64.NO_WRAP);
Bitmap mIcon11 = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);

在try块中使用此代码...希望这对您有帮助。

答案 1 :(得分:1)

mIcon11 = BitmapFactory.decodeStream(in);

mIcon11是一个位图。

此外,

  1. 不要使用主线程进行长时间运行。关于async android;
  2. ,这是很好的article
  3. 我更喜欢使用Picasso;
  4. 下载图片