我的Android之旅(十八)---数据存储--向SD卡保存网络上的图片

加载图片的方法:
方法1:根据URI加载图片
showImge.setImageURI(Uri.parse(path));
方法2:通过BitmapFactory的静态方法decodeFile()
参数为图片路径

方法3:通过BitmapFactory的静态方法decodeStream()
参数为 输入流 InputStream
注意:凡是将数据或是图片或者是其他资源的文件向SD卡中存或取。一定要先判断SD卡的状态,并获取根目录,我觉得这是个非常有必要的。
<pre class="java" name="code"><span style="font-size:14px;">String statu= Environment.getExternalStorageState();
        if (!statu.equals(Environment.MEDIA_MOUNTED)){
            Toast.makeText(this, "SD卡未就绪", Toast.LENGTH_SHORT).show();
        }

        File root=Environment.getExternalStorageDirectory();</span>

 
随后再根据要求来存取数据:在这里要特别注意的是 从网络上获取图片是个非常耗时的操作,所以我们要使用异步任务类来实现图片的加载。在获取图片的代码中有一些不同之处,那就是异步任务类的第三个参数发生了变化,变为了Bitmap                   
 并且用到了该方法,可以使图片转化为字符流来读取                             
 bitmap=BitmapFactory.decodeStream(is);
<span style="font-size:12px;">.xml文件中代码:</span>
<pre class="java" name="code">package com.jerehedu.jereduch10;

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.FileNotFoundException;
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 SavePictureActivity extends AppCompatActivity {
    private ImageView img,showImge;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_save_picture);
        img= (ImageView) findViewById(R.id.img);
        showImge= (ImageView) findViewById(R.id.showImg);
    }
    public void readImg(View v){
        String path=Environment.getExternalStorageDirectory()+"/1.png";
        //方法1:根据URI加载图片
        // showImge.setImageURI(Uri.parse(path));
        //方法2:通过BitmapFactory的静态方法decodeFile()
        //参数为图片路径
        ///
        Bitmap bitmap= BitmapFactory.decodeFile(path);
        showImge.setImageBitmap(bitmap);
        //方法3:通过BitmapFactory的静态方法decodeStream()
        //参数为 输入流 InputStream
        /*   try {
            BitmapFactory.decodeStream(new FileInputStream(path));
        } catch (FileNotFoundException e) {
           e.printStackTrace();
      }
     */

    }
    //获取ImageView中的图片
    public  void saveImg(View v){
        BitmapDrawable bitmapDrawable= (BitmapDrawable) img.getDrawable();
        Bitmap bitmap=bitmapDrawable.getBitmap();
        FileOutputStream fos=null;
        String statu= Environment.getExternalStorageState();
        if (!statu.equals(Environment.MEDIA_MOUNTED)){
            Toast.makeText(this, "SD卡未就绪", Toast.LENGTH_SHORT).show();
        }

        File root=Environment.getExternalStorageDirectory();
        try {
            fos=new FileOutputStream(root+"/1.png");

            bitmap.compress(Bitmap.CompressFormat.PNG,100,fos);

            Toast.makeText(this,"保存成功",Toast.LENGTH_SHORT).show();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }finally {
            if (fos!=null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        /*通过Bitmap(位图)压缩的方法(compress)保存图片到SD卡
        参数1:图片格式:PNJ,JPEG,WEBP
        参数2:图片质量(0-100)
        参数3:输出流
        */
    }
    public void getUirImg(View v){
   String im="http://img01.sogoucdn.com/app/a/100520093/13b5d0f" +
           "75b18a3b6-02474231a63be6b9-016d6a42d84077f891379fbbc64aa6e7.jpg";
        new HttpPicture().execute(im);
  }
    public  class HttpPicture extends AsyncTask<String,Void,Bitmap>{
        int a=5;
        @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);
                if (con.getResponseCode()==200){
                    a=100;
                    is=con.getInputStream();
                    //将图片转化为字节流
                    bitmap=BitmapFactory.decodeStream(is);
                    return bitmap;
                }
            } 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 null;
        }
        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
          showImge.setImageBitmap(bitmap);
            Toast.makeText(SavePictureActivity.this,a+"",Toast.LENGTH_SHORT).show();
        }
    }

     public void saveUirImg(View view){
         String im="http://img01.sogoucdn.com/app/a/100520093/13b5d0f" +
                 "75b18a3b6-02474231a63be6b9-016d6a42d84077f891379fbbc64aa6e7.jpg";
    new saveUirImgs().execute(im);
}
    public class saveUirImgs 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");
                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 "";

        }
        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            if (!s.equals("")){

                Toast.makeText(SavePictureActivity.this,"保存路径"+s,Toast.LENGTH_SHORT).show();
            }else {
                Toast.makeText(SavePictureActivity.this,"保存失败",Toast.LENGTH_SHORT).show();

            }
        }
    }

}

布局文件中:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    tools:context="com.jerehedu.jereduch10.SavePictureActivity">
    <ImageView
        android:layout_width="match_parent"
        android:layout_height="180dp"
        android:id="@+id/img"
        android:src="@mipmap/a1"
        android:layout_below="@+id/picture"
        android:layout_alignParentStart="true" />
<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/picture"
    android:text="保存图片"
    android:onClick="saveImg"
    />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/read"
        android:text="读取图片"
        android:onClick="readImg"
        android:layout_alignParentTop="true"
        android:layout_toEndOf="@+id/picture" />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="获取网络图片"
        android:onClick="getUirImg"
        android:id="@+id/intent"
        android:layout_alignParentBottom="true"
        android:layout_alignEnd="@+id/read" />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="保存网络图片"
        android:onClick="saveUirImg"
        android:id="@+id/save"
        android:layout_alignParentBottom="true"
        android:layout_alignParentEnd="true"
        android:layout_marginEnd="43dp" />
    <ImageView
        android:layout_width="match_parent"
        android:layout_height="180dp"
        android:id="@+id/showImg"
        android:layout_below="@+id/img"
        android:layout_alignParentStart="true" />

</RelativeLayout>

结果如下:
 
<span style="background-color: rgb(240, 240, 240);">
</span>
<span style="background-color: rgb(240, 240, 240);"></span>

点击保存图片:
 
点击读取图片:
 
点击获取网络图片:
 
点击保存网络图片:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值