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

1、把从布局中获得的图片保存到SD卡中,并把图片在从SD卡中读取出来

2、从网络上获取一张图片的地址,把图片保存到SD卡中,并把网络图片读取出来

 

程序代码:

package com.example.administrator.jreduch08;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class SaveImageViewToSdActivity extends AppCompatActivity {
    private ImageView img;
    private ImageView showImg;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_save_image_view_to_sd);
        img = (ImageView) findViewById(R.id.img);
        showImg = (ImageView) findViewById(R.id.showImg);


    }
//从网络获取图片
    public void getUrlImg(View view) {
        new GetImg().execute("http://www.ichong123.com/files/2016/8/11/44/7.jpg");
    }
    //保存网络图片(边读边写,同时进行)
    public void saveUrlImg(View view){
        new SaveHttpImg().execute("http://www.ichong123.com/files/2016/8/11/134/8.jpg");
    }

    public class SaveHttpImg extends AsyncTask<String,Void,String>{
        @Override
        protected String doInBackground(String... strings) {
            HttpURLConnection con = null;//访问网络
            InputStream is = null;
            try {
                URL url = new URL(strings[0]);
                con = (HttpURLConnection) url.openConnection();
                con.setConnectTimeout(5 * 1000);
                con.setReadTimeout(5 * 1000);
                File root=Environment.getExternalStorageDirectory();
                FileOutputStream fos=new FileOutputStream(root+"/http.jpg");
                /*http 响应吗
                 * 200:成功
                 * 404:未找到
                 * 500:发生错误
                 */
                if (con.getResponseCode() == 200) {
                    is = con.getInputStream();
                   int next=0;
                    byte[] bytes=new byte[1024];
                    while((next=is.read(bytes))>0){
                        fos.write(bytes,0,next);
                    }
                    fos.flush();
                    fos.close();
                    return root+"/http.jpg";

                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if(is!=null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (con != null) {
                    con.disconnect();
                }
            }
            return "";
        }

        // onPostExecute在UI线程中执行命令
        @Override
        protected void onPostExecute(String  s) {
            super.onPostExecute(s);
            if(!s.equals("")){
                Toast.makeText(SaveImageViewToSdActivity.this,"保存路径",Toast.LENGTH_SHORT).show();
            }else{
                Toast.makeText(SaveImageViewToSdActivity.this,"保存路径失败",Toast.LENGTH_SHORT).show();
            }

        }
        }





 
//读取图片
    public void readImg(View view) {
        String path = Environment.getExternalStorageDirectory() + "/img.png";
        //方法一:根据URI加载图片
        // showImg.setImageURI(Uri.parse(path));
        //方法二:通过BitmapFactory的静态方法decodeFile()参数为图片路径
        Bitmap bitmap = BitmapFactory.decodeFile(path);
        showImg.setImageBitmap(bitmap);
        /*//方法三:通过BitmapFactory的静态方法decodeFile()参数为输入流 Inputstream
        try {
            BitmapFactory.decodeStream(new FileInputStream(path));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }*/

    }
//保存图片
    public void saveImg(View view) {
        BitmapDrawable bitmapDrawable = (BitmapDrawable) img.getDrawable();
        //得到图片
        Bitmap bitmap = bitmapDrawable.getBitmap();
        /*通过Bitmap(位图)压缩的方法(compress)保存图片到SD卡
       参数1:图片格式( PNG JPEG WEBP)
       参数2:图片质量(1-100)
       参数3:输出流
        * */
        String statu = Environment.getExternalStorageState();
        if (!statu.equals(Environment.MEDIA_MOUNTED)) {
            Toast.makeText(getBaseContext(), "SD卡未就绪", Toast.LENGTH_SHORT).show();
            return;
        }
        File file = Environment.getExternalStorageDirectory();
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file.getCanonicalPath() + "/img.png");
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
            Toast.makeText(getBaseContext(), "保存成功", Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                    fos.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }

    public class GetImg extends AsyncTask<String, Void, Bitmap> {

        @Override
        protected Bitmap doInBackground(String... strings) {
            HttpURLConnection con = null;//访问网络
            InputStream is = null;
            Bitmap bitmap = null;
            try {
                URL url = new URL(strings[0]);
                con = (HttpURLConnection) url.openConnection();
                con.setConnectTimeout(5 * 1000);
                con.setReadTimeout(5 * 1000);
                /*http 响应吗
                 * 200:成功
                 * 404:未找到
                 * 500:发生错误
                 */
                if (con.getResponseCode() == 200) {
                    is = con.getInputStream();
                    bitmap = BitmapFactory.decodeStream(is);
                    return bitmap;

                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (con != null) {
                    con.disconnect();
                }
            }
            return null;
        }

        // onPostExecute在UI线程中执行命令
        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            showImg.setImageBitmap(bitmap);
        }
    }
}



 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值