Android实现下载图片并保存到SD卡中

在文件里设置一个点击方法已进行点击下载:

download.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        String filePath = imageInfo.get(currentItem).getBigImageUrl();
        ImgDonwload.donwloadImg(ImageActivity.this,filePath);
    }
});

下面是ImgDonwload.java图片下载工具类:

package com.vimi8.app.utils.imagesUtils;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.UUID;

/**
 * Created by vimi8 on 2017/6/9.
 */

public class ImgDonwload {

    private static String filePath;
    private static Bitmap mBitmap;
    private static String mFileName="为米老乡";
    private static String mSaveMessage;
    private final static String TAG = "ImageActivity";
    private static Context context;

    private static ProgressDialog mSaveDialog = null;

    public static void donwloadImg(Context contexts,String filePaths){
        context = contexts;
        filePath = filePaths;
        mSaveDialog = ProgressDialog.show(context, "保存图片", "图片正在保存中,请稍等...", true);

        new Thread(saveFileRunnable).start();
    }

    private static Runnable saveFileRunnable = new Runnable(){
        @Override
        public void run() {
            try {
                byte[] data = getImage(filePath);
                if(data!=null){
                    mBitmap = BitmapFactory.decodeByteArray(data, 0, data.length);// bitmap
                }else{
                    Toast.makeText(context, "Image error!", Toast.LENGTH_LONG).show();
                }



                saveFile(mBitmap, mFileName);
                mSaveMessage = "图片保存成功!";
            } catch (IOException e) {
                mSaveMessage = "图片保存失败!";
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
            messageHandler.sendMessage(messageHandler.obtainMessage());
        }

    };

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


    /**
     * Get image from newwork
     * @param path The path of image
     * @return byte[]
     * @throws Exception
     */
    public static 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 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 static void saveFile(Bitmap bm, String fileName) throws IOException {
        File dirFile = new File(Environment.getExternalStorageDirectory().getPath());
        if(!dirFile.exists()){
            dirFile.mkdir();
        }
        fileName = UUID.randomUUID().toString()+".jpg";
        File jia=new File(Environment.getExternalStorageDirectory().getPath() +"/DCIM/VIMI8");
        if(!jia.exists()){   //判断文件夹是否存在,不存在则创建
            jia.mkdirs();
        }
        File myCaptureFile = new File(jia +"/"+ fileName);
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
        bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
        bos.flush();
        bos.close();

        //把图片保存后声明这个广播事件通知系统相册有新图片到来
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri uri = Uri.fromFile(myCaptureFile);
        intent.setData(uri);
        context.sendBroadcast(intent);
    }
}

以上是取得的是byte数组, 从byte数组生成bitmap



以下是取得的是InputStream,直接从InputStream生成bitmap

package com.vimi8.app.utils.imagesUtils;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.UUID;

/**
 * Created by vimi8 on 2017/6/9.
 */

public class ImgDonwloads {

    private static String filePath;
    private static Bitmap mBitmap;
    private static String mFileName="为米老乡";
    private static String mSaveMessage;
    private final static String TAG = "ImageActivity";
    private static Context context;

    private static ProgressDialog mSaveDialog = null;

    public static void donwloadImg(Context contexts,String filePaths){
        context = contexts;
        filePath = filePaths;
        mSaveDialog = ProgressDialog.show(context, "保存图片", "图片正在保存中,请稍等...", true);

        new Thread(saveFileRunnable).start();
    }

    private static Runnable saveFileRunnable = new Runnable(){
        @Override
        public void run() {
            try {
                mBitmap = BitmapFactory.decodeStream(getImageStream(filePath));

                saveFile(mBitmap, mFileName);
                mSaveMessage = "图片保存成功!";
            } catch (IOException e) {
                mSaveMessage = "图片保存失败!";
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
            messageHandler.sendMessage(messageHandler.obtainMessage());
        }

    };

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


    /**
     * Get image from newwork
     * @param path The path of image
     * @return InputStream
     * @throws Exception
     */
    public static 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;
    }





    /**
     * 保存文件
     * @param bm
     * @param fileName
     * @throws IOException
     */
    public static void saveFile(Bitmap bm, String fileName) throws IOException {
        File dirFile = new File(Environment.getExternalStorageDirectory().getPath());
        if(!dirFile.exists()){
            dirFile.mkdir();
        }
        fileName = UUID.randomUUID().toString()+".jpg";
        File myCaptureFile = new File(Environment.getExternalStorageDirectory().getPath() +"/DCIM/Camera/"+ fileName);
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
        bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
        bos.flush();
        bos.close();

        //把图片保存后声明这个广播事件通知系统相册有新图片到来
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri uri = Uri.fromFile(myCaptureFile);
        intent.setData(uri);
        context.sendBroadcast(intent);
    }
}




发布了39 篇原创文章 · 获赞 10 · 访问量 5万+
展开阅读全文

android异步获取图片并且本地存储的后续问题

11-26

我已经实现了头像图片的异步加载以及头像图片的下载及本地保存。 实现方法及源代码请见我的博文:[图片的异步加载及图片本地缓存][1] [1]: http://blog.csdn.net/jkingcl/article/details/8141646 现在出现了一个后续的问题由于是头像,所以我使用了用户的ID作为头像的名称,例如现在我有3个好友分别是user1,user2,user3,以及我自己myUser. 那么第一次读取过后我本地的头像就为user1.jpg,user2.jpg,user3.jpg,myUser.jpg. 好了问题来了,当我的好友们的头像发生变化的时候,我去读取的时候首先检查的是本地是否有这样图片,那么本地是有图片的,则不会去服务器下载了,但是就没有办法获取到最新的头像了。 当然在我的app里面有清除本地缓存的功能,但是不可能因为一个人头像变化就把所有的头像图片资源全部清除了吧。 不知道有没有什么好的建议和方法呢? 我现在的思路有如下: 1.定时从服务器获取一次头像,比如1天2天或者一周什么的,虽然即时性不高,但是头像更改的频率一般的用户也不会太高。 2.服务器端加头像有更改的状态字段,那么当头像有更改的时候将该状态设置一下,但是因为头像都是跟着其他数据已XML的方式发送过来的,许多涉及到头像的地方那么都要加这一个统一的字段。同时我的方法里面也需要添加代码进行这个字段的判断检查,然后对应的重现下载图片。这样会在服务器和客户端都进行修改比较麻烦一点。 以上就是我的一些思路,不过感觉都还不是很好一样,请有经验的朋友如果好的建议和方法的请支点招,谢谢,说说解决方案就都行!欢迎交流~ 问答

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览