android 运用AsyncTask 获取图片并显示

为什么BitmapFactory.decodeByteArray()返回null问题

activity_main.xml布局里面一个按钮跟一个imageView

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="从网络上下载一张图片" />

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="fitXY"/>

</LinearLayout>

MainActivity.java代码如下

import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.util.StringBuilderPrinter;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {
    private Button bt;
    private ImageView img;
    private ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bt = (Button) findViewById(R.id.button);
        img = (ImageView) findViewById(R.id.imageView);
        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setTitle("提示信息");
        progressDialog.setMessage("正在下载");
        progressDialog.setCancelable(false);
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new MyAscyTask().execute();
            }
        });
    }

    public class MyAscyTask extends AsyncTask<String, Integer, byte[]> {

        @Override
        protected byte[] doInBackground(String... params) {
            InputStream ism = null;
            HttpURLConnection con = null;
            BufferedReader read = null;
            try {
                URL url = new URL("http://ww2.sinaimg.cn/mw690/69c7e018jw1e6hd0vm3pej20fa0a674c.jpg");
                con = (HttpURLConnection) url.openConnection();
                con.setRequestMethod("GET");
                con.setReadTimeout(10000);
                con.setConnectTimeout(100000);
                ism = con.getInputStream();
                read = new BufferedReader(new InputStreamReader(ism));
                StringBuffer sb = new StringBuffer();
                String line = null;
                while ((line = read.readLine()) != null) {
                    sb.append(line);
                }
                return sb.toString().getBytes();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (ism != null) {
                        ism.close();
                        ism = null;
                    }
                    if (read != null) {
                        read.close();
                        read = null;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressDialog.show();
        }

        @Override
        protected void onPostExecute(byte[] bytes) {
            super.onPostExecute(bytes);
            Log.i("TAG", "onPostExecute: "+bytes.length+"==="+bytes[0]);
            Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
            img.setImageBitmap(bitmap);
            progressDialog.dismiss();
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
        }
}
}

运行结果: 记得运行时加权限,因为访问网络,不会从网络得到图片,因为BitmapFactory.decodeByteArray方法返回空

修改MainActivity.java

import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.util.StringBuilderPrinter;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {
    private Button bt;
    private ImageView img;
    private ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bt = (Button) findViewById(R.id.button);
        img = (ImageView) findViewById(R.id.imageView);
        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setTitle("提示信息");
        progressDialog.setMessage("正在下载");
        progressDialog.setCancelable(false);
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new MyAscyTask().execute();
            }
        });
    }

    public class MyAscyTask extends AsyncTask<String, Integer, byte[]> {

        @Override
        protected byte[] doInBackground(String... params) {
            InputStream ism = null;
            HttpURLConnection con = null;
            ByteArrayOutputStream out=new ByteArrayOutputStream();
            try {
                URL url = new URL("http://ww2.sinaimg.cn/mw690/69c7e018jw1e6hd0vm3pej20fa0a674c.jpg");
                con = (HttpURLConnection) url.openConnection();
                con.setRequestMethod("GET");
                con.setReadTimeout(10000);
                con.setConnectTimeout(100000);
                ism = con.getInputStream();
                int size;
                while ((size=ism.read())!=-1) {
                    out.write(size);
                }
                return out.toByteArray();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (ism != null) {
                        ism.close();
                        ism = null;
                    }
                    if (out!= null) {
                        out.close();
                        out=null;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressDialog.show();
        }

        @Override
        protected void onPostExecute(byte[] bytes) {
            super.onPostExecute(bytes);
            Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
            img.setImageBitmap(bitmap);
            progressDialog.dismiss();
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
        }
}
}

运行结果:

总结:源码decodeByteArray方法的参数的说明

/**
     * Decode an immutable bitmap from the specified byte array.
     *
     * @param data byte array of compressed image data
     * @param offset offset into imageData for where the decoder should begin
     *               parsing.
     * @param length the number of bytes, beginning at offset, to parse
     * @return The decoded bitmap, or null if the image could not be decoded.
     */
    public static Bitmap decodeByteArray(byte[] data, int offset, int length) {
        return decodeByteArray(data, offset, length, null);
    }

再次修改MainActivity,实现边下载有进度条显示

import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.util.StringBuilderPrinter;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {
    private Button bt;
    private ImageView img;
    private ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bt = (Button) findViewById(R.id.button);
        img = (ImageView) findViewById(R.id.imageView);
        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setTitle("提示信息");
        progressDialog.setMessage("正在下载");
        progressDialog.setCancelable(false);
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new MyAscyTask().execute();
            }
        });
    }

    public class MyAscyTask extends AsyncTask<String, Integer, byte[]> {

        @Override
        protected byte[] doInBackground(String... params) {
            InputStream ism = null;
            HttpURLConnection con = null;
            ByteArrayOutputStream out=new ByteArrayOutputStream();
            try {
                URL url = new URL("http://ww2.sinaimg.cn/mw690/69c7e018jw1e6hd0vm3pej20fa0a674c.jpg");
                con = (HttpURLConnection) url.openConnection();
                con.setRequestMethod("GET");
                con.setReadTimeout(10000);
                con.setConnectTimeout(10000);
                ism = con.getInputStream();
                byte[] data = new byte[1024];
                int size;
                long file_length=con.getContentLength();
                long total_length=0;
                int i=0;
                while ((size=ism.read(data))!=-1) {
                    out.write(data,0,size);
                    total_length+=size;
                    int progress=(int)((total_length/(float)file_length) * 100);
                    Log.i("TAG", "doInBackground: "+total_length+"==="+file_length+
                            "==="+progress);
                    Thread.sleep(500);
                    publishProgress(progress);
                }
                return out.toByteArray();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (ism != null) {
                        ism.close();
                        ism = null;
                    }
                    if (out!= null) {
                        out.close();
                        out=null;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressDialog.show();
        }

        @Override
        protected void onPostExecute(byte[] bytes) {
            super.onPostExecute(bytes);
            Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
            img.setImageBitmap(bitmap);
            progressDialog.dismiss();
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            Log.i("TAG", "onProgressUpdate:....... "+values[0]);
            progressDialog.setProgress(values[0]);
        }
    }
}
时间: 2024-11-06 18:15:05

android 运用AsyncTask 获取图片并显示的相关文章

Android调用gallery获取图片

从gallery中获取图片 步骤: 步骤一: // 激活系统图库应用,选择一张图片 Intent intent = new Intent(); // 活动操作:选择一个项目从数据,返回被选中 intent.setAction(Intent.ACTION_PICK); // 设置意图的类型 intent.setType("image/*"); // 设置开启意图 // 设置的是有返回值的意图开启需要重写onActivityResult startActivityForResult(int

根据url路径获取图片并显示到ListView中

项目开发中我们需要从网络获取图片显示到控件中,很多开源框架如Picasso可以实现图片下载和缓存功能.这里介绍的是一种简易的网络图片获取方式并把它显示到ListView中. 本案例实现的效果如下: 项目结构: 根据部分开源代码,我修改并封装了一个网络图片加载的工具类GetImageByUrl,通过调用其中的setImage方法,传入待显示图片的ImageView控件和该图片的url路径这两个参数即可实现获取网络图片的功能. GetImageByUrl.java package com.leo.i

android从网络获取图片

http://blog.csdn.net/wangjinyu501/article/details/8219317 http://www.cnblogs.com/JerryWang1991/archive/2012/03/09/2388312.html http://blog.csdn.net/liuhe688/article/details/6532519 http://blog.csdn.net/abc5382334/article/details/17097633 http://www.t

Android 通过网络获取图片的源码

将开发过程中经常用到的内容做个备份,如下的资料是关于Android 通过网络获取图片的的内容. package com.netimg; import android.app.Activity;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.os.Bundle;import android.view.View;import android.view.View.OnClickLis

Android从相册获取图片

应用中经常会有去相册获取图片的需求,每次总是会忘,现在这做个记录,以便以后查阅. 从应用去相册获取图片主要有以下几个步骤: 1.设置intent调用系统相册 2.进入相册选取图片,如果相册没有满意的图片,可以使用相机照相获取,最后返回数据到应用 3.应用获取图片后,调用裁剪程序对图片进行裁剪 4.返回裁剪的图片并显示出来 一.设置intent调用系统相册,并进入相册选取图片 /** * 调用相册 */ private void goAlbums() { Intent intent = new I

android 从相册获取图片

从相册获取图片 在android应用中是运用得很多的一项技术了 其实很简单 使用intent就可以了 刚敲了一个dome  睡觉之前还是分享一下把 1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 xmlns:tools="http://schemas.android.com/tools" 3 android:layout_width="match

关于调用Android照相功能获取图片

最近在项目中调用相机,使用了别人写好的文件,但发现获取的照片没真正使用系统照相拍照再查看那么清晰,于是研究了一下,发现通常调用照相功能获取的图片都是被压缩的,如果要获取原照,那得保存后在获取.在网上找到一个博主写了两篇文章就此问题进行详细讲解,可看起文章学习: Android开发之获取相册照片和获取拍照照片 Android开发之获取相册照片和获取拍照照片二

Android之Glide获取图片Path和Glide获取图片Bitmap

今天主要研究了Glide获取图片Path.Bitmap用法,相信也困扰了大家很久,我在网上也找了很久,基本没有,后来研究了下,也参考了下api文档,总结了以下几个方式: 1. 获取Bitmap: 1)在图片下载缓存好之后获取 Glide.with(mContext).load(url).asBitmap().into(new SimpleTarget<Bitmap>() { @Override public void onResourceReady(Bitmap resource, Glide

[android] 从gallery获取图片

效果就是点击按钮,打开系统图库应用,可以选择一张里面的图片展示出来 设置隐式意图 获取Intent对象,通过new出来 调用Intent对象的setAction()方法,设置动作,参数:Intent.ACTION_PICK 调用Intent对象的setType()方法,设置类型,参数 :”image/*”还可以弄视频 调用startActivityForResult()方法,开启带返回值的 查看系统的gallery源码可以知道,返回了一个Intent对象,里面隐式传递的数据,额外数据 重写方法o