day06三级缓存 二次采样

SD卡操作

(1)Environment.getExternalStorageState();// 判断SD卡是否
(2)Environment.getExternalStorageDirectory(); 获取SD卡的根目录
(3)Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); 获取SD卡公开目录

//读写操作的权限
在这里插入图片描述

//写
//判断是否插入SD卡
  if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            File file = Environment.getExternalStorageDirectory();
            Toast.makeText(MainActivity.this,file.getAbsolutePath()+"",Toast.LENGTH_SHORT).show();

            File file1=new File(file,"Download");
            File file2=new File(file1,"mars.txt");
            FileOutputStream fos =null;

            try {
                fos=new FileOutputStream(file2);
                fos.write("战神刘大瑞".getBytes());
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }else {
            Toast.makeText(MainActivity.this,"没有安装SD卡",Toast.LENGTH_SHORT).show();
        }

//下载
  if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
             new MyThread().start();
        }else {
            Toast.makeText(MainActivity.this,"没有安装SD卡",Toast.LENGTH_SHORT).show();
        }
        //线程
public class MyThread extends Thread {
    @Override
    public void run() {
        super.run();

            File file = Environment.getExternalStorageDirectory();
            File file1=new File(file,"Download");
            File file2=new File(file1,"mars.jpg");
//        File file2=new File(file1,"mars.mp4");//mp4格式
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(file2);

//                URL url=new URL("http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4");//mp4格式
                URL url=new URL("https://img04.sogoucdn.com/app/a/100520024/09cc6117a797b1e6e5f758de4b967ff6");
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("GET");
                urlConnection.connect();
                if (urlConnection.getResponseCode()==200){
                    InputStream is = urlConnection.getInputStream();
                    byte[] bys = new byte[1024];
                    int len =0;
                    while((len =is.read(bys))!=-1){
                        fos.write(bys,0,len);
                    }
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    fos.close();

                } catch (IOException e) {
                    e.printStackTrace();
                }

            }



    }
}
//从sd卡读取图片
 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            imageView.setImageBitmap(BitmapFactory.decodeFile("/sdcard/Download/mars.jpg"));
        }else {
            Toast.makeText(MainActivity.this,"没有安装SD卡",Toast.LENGTH_SHORT).show();
        }    

三级缓存

//没有缓存的弊端 :费流量, 加载速度慢
//加入缓存的优点: 省流量,支持离线浏览
//读写权限
在这里插入图片描述

//从缓存中获取
public class CacheUtils {
    //获得手机的最大内存
    static long max =Runtime.getRuntime().maxMemory();
    //实例化一个内存对象
    static LruCache<String,Bitmap> lruCache=new LruCache<String,Bitmap>((int) (max/8)){
        @Override
        protected int sizeOf(String key, Bitmap value) {
            //返回每张图片的大小
            return value.getByteCount();

        }
    };

    public static Bitmap getBitmap(String key){
        Bitmap bitmap = lruCache.get(key);

        return bitmap;
    }
    // 键 图片在内存中的名字
    //值 图片bitmap对象
    public static void setBitmap(String key,Bitmap bitmap){
        lruCache.put(key,bitmap);

    }
}

//从SD卡中获取
public class SDUtils {
   // bitmap--->路径  BitmapFactory.decodeFile(文件路径)
    //根据路径获得Bitmap对象
    public static Bitmap getBitmap(String filepath){
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            Bitmap bitmap = BitmapFactory.decodeFile(filepath);
            return bitmap;
        }
        return null;
    }
    //从SD读取   根据路径---->Bitmap.compress()  压缩
    //将bitmap对象按照指定路径存储
    public  static void setBitmap(String filepath,Bitmap bitmap){
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            try {
                //参数一 图片的格式 JPG PNG  参数二 质量 0-100 参数三 输出流
                bitmap.compress(Bitmap.CompressFormat.JPEG,100,new FileOutputStream(filepath));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

        }
    }
}

//从网络获取
public class NetUtils {
    //根据网址得到Bitmap
    public static Bitmap getBitmap(String url){
        Bitmap bitmap =null;
        try {
            //直接获取异步返回的结果
            bitmap = new Myask().execute(url).get();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return bitmap;
    }
    static class Myask extends AsyncTask<String,String,Bitmap>{

        @Override
        protected Bitmap doInBackground(String... strings) {

            try {
                URL url=new URL(strings[0]);
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("GET");
                urlConnection.connect();
                if (urlConnection.getResponseCode()==200){
                    InputStream inputStream = urlConnection.getInputStream();
                    Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                    return bitmap;
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return null;
        }
    }
}
//主类
public class MainActivity extends AppCompatActivity {
    Button button;
    ImageView imageView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button=findViewById(R.id.btn);
        imageView=findViewById(R.id.iv);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bitmap bitmap = CacheUtils.getBitmap("liurui");
                if (bitmap==null){
                    bitmap = SDUtils.getBitmap("/sdcard/Pictures/liurui.jpg");
                    if (bitmap==null){
                         bitmap = NetUtils.getBitmap("https://img01.sogoucdn.com/app/a/100520024/b555532f376c51331f44c4d2c13a934c");
                         if (bitmap==null){
                             Toast.makeText(MainActivity.this,"你个死鬼,你让我上哪找图片去",Toast.LENGTH_SHORT).show();
                         }else {
                             Toast.makeText(MainActivity.this,"从网络中获取的",Toast.LENGTH_SHORT).show();
                             imageView.setImageBitmap(bitmap);
                             SDUtils.setBitmap("/sdcard/Pictures/liurui.jpg",bitmap);
                             CacheUtils.setBitmap("liurui",bitmap);
                         }
                    }else {
                        Toast.makeText(MainActivity.this,"从SD卡中获取的",Toast.LENGTH_SHORT).show();
                        imageView.setImageBitmap(bitmap);
                        CacheUtils.setBitmap("liurui",bitmap);
                    }
                }else {
                    Toast.makeText(MainActivity.this,"从内存中获取的",Toast.LENGTH_SHORT).show();
                    imageView.setImageBitmap(bitmap);
                }
            }
        });
    }
}

二级采样

//Bitmap.compress(CompressFormat format, int quality, OutputStream stream)
Bitmap被压缩成的图片格式
压缩的质量控制,范围0~100
输出流

//主类
public class MainActivity extends AppCompatActivity {
    GridView gridView;
    ArrayList<String> arrayList=new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        gridView=findViewById(R.id.gri);
        for (int i = 0; i < 9; i++) {
            arrayList.add("/sdcard/Download/mars.jpg");
        }

        Myad myad=new Myad(MainActivity.this);
        myad.notifyDataSetChanged();
        gridView.setAdapter(myad);
    }
}
// 适配器类
public class Myad extends BaseAdapter {
    MainActivity activity;

    public Myad(MainActivity activity) {
        this.activity = activity;
    }

    @Override
    public int getCount() {
        return activity.arrayList.size();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewh;
        if (convertView==null){
            viewh=new ViewHolder();
            convertView=View.inflate(activity,R.layout.item_layout,null);
            viewh.imageView=convertView.findViewById(R.id.iv);
            convertView.setTag(viewh);
        }else {
            viewh = (ViewHolder)convertView.getTag();
        }
        String s = activity.arrayList.get(position);
        BitmapFactory.Options options=new BitmapFactory.Options();
        options.inJustDecodeBounds=true;
        

        int outWidth = options.outWidth;
        int outHeight = options.outHeight;

        int size = 1;
        while(outWidth/size>200||outHeight/size>200){
            size=size*2;
        }

        options.inJustDecodeBounds=false;
        options.inSampleSize=size;

        Bitmap bitmap = BitmapFactory.decodeFile(s, options);
        viewh.imageView.setImageBitmap(bitmap);

        return convertView;
    }
    class ViewHolder{
        ImageView imageView;
    }
}
//按钮一按照100%质量压缩到SD卡中,按钮二按照50%质量压缩到SD卡
//主类
public class MainActivity extends AppCompatActivity {
    Button button1,button2;
    ImageView imageView1,imageView2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button1=findViewById(R.id.btn1);
        button2=findViewById(R.id.btn2);
        imageView1=findViewById(R.id.iv1);
        imageView2=findViewById(R.id.iv2);
        //https://img03.sogoucdn.com/app/a/100520024/f9237f51fa52b174dab2fb1601820a85
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                File f = Environment.getExternalStorageDirectory();
                File file=new File(f,"Pictures");
                File file1=new File(file,"mars1.jpg");

                Bitmap bitmap = NetUtils.getBitmap("https://img03.sogoucdn.com/app/a/100520024/f9237f51fa52b174dab2fb1601820a85");
                try {
                    //参数一 图片的格式 参数二 图片质量 0-100  参数三:输出流
                    bitmap.compress(Bitmap.CompressFormat.JPEG,100,new FileOutputStream(file1));
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }

                Bitmap bitmap1 = SDUtils.getBitmap("/sdcard/Pictures/mars1.jpg");
                imageView1.setImageBitmap(bitmap1);

            }
        });
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                File f = Environment.getExternalStorageDirectory();
                File file=new File(f,"Pictures");
                File file1=new File(file,"mars2.jpg");

                Bitmap bitmap = NetUtils.getBitmap("https://img03.sogoucdn.com/app/a/100520024/f9237f51fa52b174dab2fb1601820a85");

                try {
                    //参数一 图片的格式 参数二 图片质量 0-100  参数三:输出流
                    bitmap.compress(Bitmap.CompressFormat.JPEG,50,new FileOutputStream(file1));
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }

                Bitmap bitmap2 = SDUtils.getBitmap("/sdcard/Pictures/mars2.jpg");
                imageView2.setImageBitmap(bitmap2);
            }
        });
    }
}
//sd卡工具类
public class SDUtils {
   // bitmap--->路径  BitmapFactory.decodeFile(文件路径)
    //根据路径获得Bitmap对象
    public static Bitmap getBitmap(String filepath){
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            Bitmap bitmap = BitmapFactory.decodeFile(filepath);
            return bitmap;
        }
        return null;
    }
    //从SD读取   根据路径---->Bitmap.compress()  压缩
    //将bitmap对象按照指定路径存储
    public  static void setBitmap(String filepath,Bitmap bitmap){
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            try {
                //参数一 图片的格式 JPG PNG  参数二 质量 0-100 参数三 输出流
                bitmap.compress(Bitmap.CompressFormat.JPEG,100,new FileOutputStream(filepath));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

        }
    }
}
//网络工具类
public class NetUtils {
    //根据网址得到Bitmap
    public static Bitmap getBitmap(String url){
        Bitmap bitmap =null;
        try {
            //直接获取异步返回的结果
            bitmap = new Myask().execute(url).get();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return bitmap;
    }
    static class Myask extends AsyncTask<String,String,Bitmap>{

        @Override
        protected Bitmap doInBackground(String... strings) {

            try {
                URL url=new URL(strings[0]);
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("GET");
                urlConnection.connect();
                if (urlConnection.getResponseCode()==200){
                    InputStream inputStream = urlConnection.getInputStream();
                    Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                    return bitmap;
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return null;
        }
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值