【问题标题】:Convert image downloaded into a bitmap将下载的图像转换为位图
【发布时间】:2016-04-03 02:52:18
【问题描述】:

我正在尝试从 url 异步下载图像,然后将其转换为位图,我能够异步下载图像而没有任何错误,但我发现很难将其转换为位图。

这是我的代码

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);

        }
    }

}

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

【问题讨论】:

  • 但我发现很难将其转换为位图。您能详细说明一下吗?
  • 您将位图转换为 byteArray 的尝试必须在 onPostExecute 中进行,而不是在 onCreate 中,因为 asynctask 不是阻塞调用,它将异步发生...
  • '请问如何将下载的图像转换为位图?'。您已经在 doInBackground 中这样做了。然后你让 doInBackgroud 返回那个位图,然后由 onPostExcetute 设置 - 我认为是一个 ImageView。

标签: android bitmap


【解决方案1】:
mIcon11 = BitmapFactory.decodeStream(in);

mIcon11 是一个位图。

此外,

  1. 不要将主线程用于长时间运行的操作。这是关于异步 android 的好 article
  2. 我更喜欢用Picasso下载图片;

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

    • 我不明白你的代码,你能简单解释一下吗,谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-24
    • 1970-01-01
    • 2016-02-05
    • 2012-10-24
    • 1970-01-01
    相关资源
    最近更新 更多