【Android】实现下载网络图片并保存到SD卡中

转载 2015年06月30日 16:10:42

转载出处:http://blog.csdn.net/wstarx/article/details/6176902


在微信朋友圈中,我们点击图片会打开全图,再长按会有保存到本地的功能,那么如何实现网络图片的下载以及保存呢?

从网络上取得的图片,生成Bitmap时有两种方法,一种是先转换为byte[],再生成bitmap;一种是直接用InputStream生成bitmap。

①ICS4.0及更高版本中的实现

4.0中不允许在主线程,即UI线程中操作网络,所以必须新开一个线程,在子线程中执行网络连接;然后在主线程中显示图片。

public class IcsTestActivity extends Activity {

    private final static String TAG = "IcsTestActivity";
    private final static String ALBUM_PATH
            = Environment.getExternalStorageDirectory() + "/download_test/";
    private ImageView mImageView;
    private Button mBtnSave;
    private ProgressDialog mSaveDialog = null;
    private Bitmap mBitmap;
    private String mFileName;
    private String mSaveMessage;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mImageView = (ImageView)findViewById(R.id.imgSource);
        mBtnSave = (Button)findViewById(R.id.btnSave);

        new Thread(connectNet).start();

        // 下载图片
        mBtnSave.setOnClickListener(new Button.OnClickListener(){
            public void onClick(View v) {
                mSaveDialog = ProgressDialog.show(IcsTestActivity.this, "保存图片", "图片正在保存中,请稍等...", true);
                new Thread(saveFileRunnable).start();
        }
        });
    }

    /**
     * Get image from newwork
     * @param path The path of image
     * @return byte[]
     * @throws Exception
     */
    public byte[] getImage(String path) throws Exception{
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(5 * 1000);
        conn.setRequestMethod("GET");
        InputStream inStream = conn.getInputStream();
        if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){
            return readStream(inStream);
        }
        return null;
    }

    /**
     * Get image from newwork
     * @param path The path of image
     * @return InputStream
     * @throws Exception
     */
    public InputStream getImageStream(String path) throws Exception{
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(5 * 1000);
        conn.setRequestMethod("GET");
        if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){
            return conn.getInputStream();
        }
        return null;
    }
    /**
     * Get data from stream
     * @param inStream
     * @return byte[]
     * @throws Exception
     */
    public static byte[] readStream(InputStream inStream) throws Exception{
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while( (len=inStream.read(buffer)) != -1){
            outStream.write(buffer, 0, len);
        }
        outStream.close();
        inStream.close();
        return outStream.toByteArray();
    }

    /**
     * 保存文件
     * @param bm
     * @param fileName
     * @throws IOException
     */
    public void saveFile(Bitmap bm, String fileName) throws IOException {
        File dirFile = new File(ALBUM_PATH);
        if(!dirFile.exists()){
            dirFile.mkdir();
        }
        File myCaptureFile = new File(ALBUM_PATH + fileName);
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
        bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
        bos.flush();
        bos.close();
    }

    private Runnable saveFileRunnable = new Runnable(){
        @Override
        public void run() {
            try {
                saveFile(mBitmap, mFileName);
                mSaveMessage = "图片保存成功!";
            } catch (IOException e) {
                mSaveMessage = "图片保存失败!";
                e.printStackTrace();
            }
            messageHandler.sendMessage(messageHandler.obtainMessage());
        }

    };

    private Handler messageHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            mSaveDialog.dismiss();
            Log.d(TAG, mSaveMessage);
            Toast.makeText(IcsTestActivity.this, mSaveMessage, Toast.LENGTH_SHORT).show();
        }
    };

    /*
     * 连接网络
     * 由于在4.0中不允许在主线程中访问网络,所以需要在子线程中访问
     */
    private Runnable connectNet = new Runnable(){
        @Override
        public void run() {
            try {
                String filePath = "http://img.my.csdn.net/uploads/201402/24/1393242467_3999.jpg";
                mFileName = "test.jpg";

                //以下是取得图片的两种方法
                //////////////// 方法1:取得的是byte数组, 从byte数组生成bitmap
                byte[] data = getImage(filePath);
                if(data!=null){
                    mBitmap = BitmapFactory.decodeByteArray(data, 0, data.length);// bitmap
                }else{
                    Toast.makeText(IcsTestActivity.this, "Image error!", 1).show();
                }
                ////////////////////////////////////////////////////////

                //******** 方法2:取得的是InputStream,直接从InputStream生成bitmap ***********/
                mBitmap = BitmapFactory.decodeStream(getImageStream(filePath));
                //********************************************************************/

                // 发送消息,通知handler在主线程中更新UI
                connectHanlder.sendEmptyMessage(0);
                Log.d(TAG, "set image ...");
            } catch (Exception e) {
                Toast.makeText(IcsTestActivity.this,"无法链接网络!", 1).show();
                e.printStackTrace();
            }

        }

    };

    private Handler connectHanlder = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            Log.d(TAG, "display image");
            // 更新UI,显示图片
            if (mBitmap != null) {
                mImageView.setImageBitmap(mBitmap);// display image
            }
        }
    };

}
②2.3以及以下版本可以在主线程中操作网络连接,但最好不要这样做,因为连接网络是阻塞的,如果5秒钟还没有连接上,就会引起ANR。
public class AndroidTest2_3_3 extends Activity {
	private final static String TAG = "AndroidTest2_3_3";
    private final static String ALBUM_PATH 
    		= Environment.getExternalStorageDirectory() + "/download_test/";
    private ImageView imageView;
    private Button btnSave;
    private ProgressDialog myDialog = null;
    private Bitmap bitmap;
    private String fileName;
    private String message;
    
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        imageView = (ImageView)findViewById(R.id.imgSource);
        btnSave = (Button)findViewById(R.id.btnSave);
        
        String filePath = "http://hi.csdn.net/attachment/201105/21/134671_13059532779c5u.jpg";
        fileName = "test.jpg";
        
        try {
        	//////////////// 取得的是byte数组, 从byte数组生成bitmap
        	byte[] data = getImage(filePath);      
            if(data!=null){      
                bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);// bitmap      
                imageView.setImageBitmap(bitmap);// display image      
            }else{      
                Toast.makeText(AndroidTest2_3_3.this, "Image error!", 1).show();      
            }
            ////////////////////////////////////////////////////////

            //******** 取得的是InputStream,直接从InputStream生成bitmap ***********/
        	bitmap = BitmapFactory.decodeStream(getImageStream(filePath));
            if (bitmap != null) {
            	imageView.setImageBitmap(bitmap);// display image
            }
            //********************************************************************/
            Log.d(TAG, "set image ...");
        } catch (Exception e) {   
            Toast.makeText(AndroidTest2_3_3.this,"Newwork error!", 1).show();   
            e.printStackTrace();   
        }   

        
        // 下载图片
        btnSave.setOnClickListener(new Button.OnClickListener(){
            public void onClick(View v) {
                myDialog = ProgressDialog.show(AndroidTest2_3_3.this, "保存图片", "图片正在保存中,请稍等...", true);
                new Thread(saveFileRunnable).start();
        }
        });
    }

    /**  
     * Get image from newwork  
     * @param path The path of image  
     * @return byte[]
     * @throws Exception  
     */  
    public byte[] getImage(String path) throws Exception{   
        URL url = new URL(path);   
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();   
        conn.setConnectTimeout(5 * 1000);   
        conn.setRequestMethod("GET");   
        InputStream inStream = conn.getInputStream();   
        if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){   
            return readStream(inStream);   
        }   
        return null;   
    }   
  
    /**  
     * Get image from newwork  
     * @param path The path of image  
     * @return InputStream
     * @throws Exception  
     */
    public InputStream getImageStream(String path) throws Exception{   
        URL url = new URL(path);   
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();   
        conn.setConnectTimeout(5 * 1000);   
        conn.setRequestMethod("GET");
        if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){   
        	return conn.getInputStream();      
        }   
        return null; 
    }
    /**  
     * Get data from stream 
     * @param inStream  
     * @return byte[]
     * @throws Exception  
     */  
    public static byte[] readStream(InputStream inStream) throws Exception{   
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();   
        byte[] buffer = new byte[1024];   
        int len = 0;   
        while( (len=inStream.read(buffer)) != -1){   
            outStream.write(buffer, 0, len);   
        }   
        outStream.close();   
        inStream.close();   
        return outStream.toByteArray();   
    } 

    /**
     * 保存文件
     * @param bm
     * @param fileName
     * @throws IOException
     */
    public void saveFile(Bitmap bm, String fileName) throws IOException {
        File dirFile = new File(ALBUM_PATH);
        if(!dirFile.exists()){
            dirFile.mkdir();
        }
        File myCaptureFile = new File(ALBUM_PATH + fileName);
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
        bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
        bos.flush();
        bos.close();
    }
    
    private Runnable saveFileRunnable = new Runnable(){
        @Override
        public void run() {
            try {
                saveFile(bitmap, fileName);
                message = "图片保存成功!";
            } catch (IOException e) {
                message = "图片保存失败!";
                e.printStackTrace();
            }
            messageHandler.sendMessage(messageHandler.obtainMessage());
        }
            
    };
    
    private Handler messageHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            myDialog.dismiss();
            Log.d(TAG, message);
            Toast.makeText(AndroidTest2_3_3.this, message, Toast.LENGTH_SHORT).show();
        }
    };
}
main.xml文件,只有一个button和一个ImageView

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <Button
		android:id="@+id/btnSave"
	  	android:layout_width="wrap_content" 
	    android:layout_height="wrap_content"
		android:text="保存图片"
	    />
	<ImageView
		android:id="@+id/imgSource"
	  	android:layout_width="wrap_content" 
	    android:layout_height="wrap_content" 
	    android:adjustViewBounds="true"
	    />
</LinearLayout>


注意:在mainfest文件中增加互联网权限和写sd卡的权限

	<uses-permission android:name="android.permission.INTERNET" /> 
	<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>

文章转载以供学习。


android 网络获取图片并在SD卡上保存与读取

  • 2015年06月04日 01:33
  • 1.59MB
  • 下载

Android数据存储:获取网络图片把图片保存到SD卡中并从SDk卡中读取(通过Bitmap方法)

1、把从布局中获得的图片保存到SD卡中,并把图片在从SD卡中读取出来 2、从网络上获取一张图片的地址,把图片保存到SD卡中,并把网络图片读取出来   程序代码: package com.exa...
  • liusslove
  • liusslove
  • 2016-08-16 22:05:24
  • 2925

android从网络,SD卡获取图片,压缩后显示到界面,可以保存到本地

  • 2013年10月25日 17:14
  • 1.45MB
  • 下载

android网络获取图片并在ViewPager中显示

  • 2015年06月25日 15:25
  • 1.39MB
  • 下载

Android自定义照相机实现(拍照、保存到SD卡,利用Bundle在Acitivity交换数据)

Android自定义照相机实现 近期小巫在学校有一个创新项目,也不是最近,是一个拖了很久的项目,之前一直没有去搞,最近因为要中期检查,搞得我跟小组成员一阵忙活,其实开发一款照相机软件并不太难,下面就...
  • cstarbl
  • cstarbl
  • 2014-03-05 18:45:00
  • 4730

android网络编程--从网络下载图片,并保存到内存卡

功能1:从网络上取得的图片,生成Bitmap时有两种方法,一种是先转换为byte[],再生成bitmap;一种是直接用InputStream生成bitmap。...
  • lanhuzi9999
  • lanhuzi9999
  • 2014-06-16 23:35:21
  • 7620

Android 从网络上获取图片保存到SD卡中

  • 2015年08月07日 19:10
  • 1.5MB
  • 下载

Android调用系统相机拍照并保存到SD卡的两种实现方式

1.调用照相机时通过putExtra的方式直接指定存储路径 Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);// 定义调用相机并...
  • u013127097
  • u013127097
  • 2013-12-12 14:51:30
  • 2324

Android网络获取图片保存到本地,并在ViewPager中显示图片

本文章提供的技术有:网络获取图片并保存到SD卡、网络或本地图片展示到ViewPager中、判断网络状态(是否联网)。 自己写了一个demo,提供demo下载 点击打开链接    效果如图     ...
  • l631768226
  • l631768226
  • 2015-06-25 15:28:46
  • 3928

将项目中图片文件保存到SD卡中

得到SD卡的路径: Environment.getExternalStorageDirectory() findViewById(R.id.write_btn).setOnClickL...
  • u011430511
  • u011430511
  • 2013-07-17 12:57:30
  • 1697
收藏助手
不良信息举报
您举报文章:【Android】实现下载网络图片并保存到SD卡中
举报原因:
原因补充:

(最多只允许输入30个字)