2019-7-22 seo达人
如果您想订阅本博客内容,每天自动发到您的邮箱中, 请点这里
一.为什么Bitmap三级缓存?
没有缓存的弊端 :费流量, 加载速度慢
加入缓存的优点: 省流量,支持离线浏览
二.原理
从内存获取图片, 如果存在, 则显示; 如果不存在, 则从SD卡中获取图片
从SD卡中获取图片, 如果文件中存在, 显示, 并且添加到内存中; 否则开启网络下载图片
从网络下载图片, 如果下载成功, 则添加到缓存中, 存入SD卡, 显示图片
三.代码
(1)添加读写SD卡的权限和网络权限
// //Lrucache存储工具类
public class LruUtils {
private LruCache<String,Bitmap> lruCache;
private long max=Runtime.getRuntime().maxMemory();
public LruUtils(){
lruCache=new LruCache<String,Bitmap>((int)max/8){
@Override
protected int sizeOf(String key, Bitmap value) {
return value.getByteCount();
}
};
}
public Bitmap getBitmap(String key){
return lruCache.get(key);
}
public void setBitmap(String key,Bitmap bitmap){
lruCache.put(key,bitmap);
}
1
2
3
4
5
6
7
8
9
10
11
12
}
//SD卡工具类
public class SDUtils {
public static void setBitmap(String name, Bitmap bitmap) {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File file1 = new File(file, name);
try {
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(file1));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
public static Bitmap getBitmap(String name){
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
File file=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File file1=new File(file,name);
return BitmapFactory.decodeFile(file1.getAbsolutePath());
}
return null;
}
}
//网络
import android.app.AlertDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutionException;
public class NewUtils {
public static Bitmap getBitmap(String url) throws ExecutionException, InterruptedException {
return new MyTask().execute(url).get();
}
static class MyTask extends AsyncTask<String,Void,Bitmap>{
@Override
protected Bitmap doInBackground(String… strings) {
String imageUrl = strings[0];
HttpURLConnection conn = null;
try {
URL url = new URL(imageUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(5000);
conn.setConnectTimeout(5000);
conn.setRequestMethod(“GET”);
if (conn.getResponseCode() == 200) {
InputStream is = conn.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(is);
return bitmap;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
}
}
return null;
}
}
}
//使用三个工具类完成Bitmap的三级缓存
package com.example.administrator.myapplication;
import android.graphics.Bitmap;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import java.util.concurrent.ExecutionException;
public class MainActivity extends AppCompatActivity {
private ImageView imageView;
Button button;
private LruUtils lruUtils= new LruUtils();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=findViewById(R.id.button);
imageView=findViewById(R.id.imageview);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Bitmap bitmap=lruUtils.getBitmap(“czn”);
if (bitmap!=null){
imageView.setImageBitmap(bitmap);
Toast.makeText(MainActivity.this, “图片存内存”, Toast.LENGTH_SHORT).show();
}else{
bitmap=SDUtils.getBitmap(“czn.jpg”);
if (bitmap!=null){
imageView.setImageBitmap(bitmap);
Toast.makeText(MainActivity.this, “图片存SD卡”, Toast.LENGTH_SHORT).show();
lruUtils.setBitmap(“czn”,bitmap);
}else{
try {
bitmap=NewUtils.getBitmap(“http://pic1.win4000.com/wallpaper/e/50d80458e1373.jpg”);
if (bitmap!=null){
imageView.setImageBitmap(bitmap);
Toast.makeText(MainActivity.this, “图片存网络”, Toast.LENGTH_SHORT).show();
SDUtils.setBitmap(“czn.jpg”,bitmap);
lruUtils.setBitmap(“czn”,bitmap);
}else{
Toast.makeText(MainActivity.this, “没有找到”, Toast.LENGTH_SHORT).show();
}
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
});
}
}
Bitmap二次采样
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.ExecutionException;
public class Main2Activity extends AppCompatActivity {
Button bt;
ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
bt=findViewById(R.id.bt);
imageView=findViewById(R.id.mimage);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
Bitmap bitmap = new MyTask().execute(“https://cdn.duitang.com/uploads/item/201211/24/20121124230042_Bfhim.jpeg”).get();
imageView.setImageBitmap(bitmap);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
});
}
class MyTask extends AsyncTask<String,Object,Bitmap>{
@Override
protected Bitmap doInBackground(String... strings) {
try {
URL url = new URL(strings[0]);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
if(urlConnection.getResponseCode()==200){
InputStream inputStream = urlConnection.getInputStream();
//将inputStream流存储起来
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] bytes = new byte[1024];
int len=0;
while((len=inputStream.read(bytes))!=-1){
byteArrayOutputStream.write(bytes,0,len);
}
//桶:网络的图片都放在数组里面了
byte[] data = byteArrayOutputStream.toByteArray();
//TODO 1:第一次采样:只采边框 计算压缩比例
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds=true;//设置只采边框
BitmapFactory.decodeByteArray(data,0,data.length,options);//采样
int outWidth = options.outWidth;//获得原图的宽
int outHeight = options.outHeight;//获得原图的高
//计算缩放比例
int size=1;
while(outWidth/size>100||outHeight/size>100){
size*=2;
}
//TODO 2:第二次采样:按照比例才像素
options.inJustDecodeBounds=false;//设置只采边框为fasle
options.inSampleSize=size;//设置缩放比例
Bitmap bitmap= BitmapFactory.decodeByteArray(data,0,data.length,options);//采样
return bitmap;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
蓝蓝设计( www.lanlanwork.com )是一家专注而深入的界面设计公司,为期望卓越的国内外企业提供卓越的UI界面设计、BS界面设计 、 cs界面设计 、 ipad界面设计 、 包装设计 、 图标定制 、 用户体验 、交互设计、网站建设 、平面设计服务。