ImageView(图片缓存内存中+图片二次采样)
2017-08-16 15:17
246 查看
import java.security.MessageDigest;
public class EncoderUtils {
/**
* Md5Encoder
*
* @param string
* @return
* @throws Exception
*/
public static String encode(String string) throws Exception {
byte[] hash = MessageDigest.getInstance("MD5").digest(
string.getBytes("UTF-8"));
StringBuilder hex = new StringBuilder(hash.length * 2);
for (byte b : hash) {
if ((b & 0xFF) < 0x10) {
hex.append("0");
}
hex.append(Integer.toHexString(b & 0xFF));
}
return hex.toString();
}
}
================================
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.util.LruCache;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ImagesUtils {
Handler handler;
private File cacheDir;
private ExecutorService newFixedThreadPool;
private LruCache<String, Bitmap> lruCache;
public ImagesUtils(Context context, Handler handler) {
//获得你手机上的最大内存
long maxMemory = Runtime.getRuntime().maxMemory();
int maxSize = (int) (maxMemory/10);
this.handler = handler;
lruCache = new LruCache<String, Bitmap>(maxSize){
@Override
protected int sizeOf(String key, Bitmap value) {
return value.getRowBytes()*value.getHeight();
}
};
//得到sd文件夹
cacheDir = context.getCacheDir();
//
newFixedThreadPool = Executors.newFixedThreadPool(5);
}
public Bitmap getBitMap(String path){
Bitmap bitmap = lruCache.get(path);
if(bitmap!=null){
System.out.println("我走了内存");
return bitmap;
}
//从本直去取,sd卡去取bitmap
bitmap = getBitMapFromLocal(path);
if(bitmap!=null){
System.out.println("我走了本地缓存");
return bitmap;
}
// 从网络去取
getBitmapFromNet(path);
return null;
}
/**
* 从网络
*
* @param path
*/
private void getBitmapFromNet(final String path) {
newFixedThreadPool.execute(new Runnable() {
@Override
public void run() {
try {
URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
int responseCode = connection.getResponseCode();
if (responseCode == 200) {
InputStream inputStream = connection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
Message msg = new Message();
msg.what = 111;
msg.obj = bitmap;
Bundle data = new Bundle();
data.putString("tag", path);
msg.setData(data);
handler.sendMessage(msg);
//缓存到本地
saveBitmapToLocal(bitmap, path);
//缓存到内存
lruCache.put(path, bitmap);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
protected void saveBitmapToLocal(Bitmap bitmap, String path) {
try {
String encode = EncoderUtils.encode(path);
FileOutputStream fileOutputStream = new FileOutputStream(cacheDir
+ "/" + encode);
//图片二次裁剪
bitmap.compress(CompressFormat.JPEG, 80, fileOutputStream);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 从本地取 Md5 a.jpg b.jpg
* aafdgsgsgsggg.jpg
* @param path
*/
private Bitmap getBitMapFromLocal(String path) {
try {
String encode = EncoderUtils.encode(path);
FileInputStream fileInputStream = new FileInputStream(cacheDir
+ "/" + encode);
Bitmap bitmap = BitmapFactory.decodeStream(fileInputStream);
//存到内存
lruCache.put(path, bitmap);
return bitmap;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
================================
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
private GridView gv;
ImagesUtils imags;
String[] imageUrls = new String[] {
"http://img.my.csdn.net/uploads/201407/26/1406383299_1976.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383291_6518.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383291_8239.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383290_9329.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383290_1042.jpg",
"http://img.my.csdn.net/uploads/201407
4000
/26/1406383275_3977.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383265_8550.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383264_3954.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383264_4787.jpg",
};
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what == 0) {
Bitmap bitmap = (Bitmap) msg.obj;
// 设置给imageView
String tag = msg.getData().getString("tag");
// 根据标记取出imageView
ImageView imageView = (ImageView) gv.findViewWithTag(tag);
if (imageView != null && bitmap != null) {
// 从网络获取图片
imageView.setImageBitmap(bitmap);
Log.i("tag", "从网络中获取图片");
}
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imags = new ImagesUtils(this,handler);
gv = (GridView) findViewById(R.id.gv);
gv.setAdapter(new MyAdapter());
}
class MyAdapter extends BaseAdapter {
@Override
public int getCount() {
// TODO Auto-generated method stub
return imageUrls.length;
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView iv = new ImageView(MainActivity.this);
iv.setTag(imageUrls[position]);
Bitmap bitmap = imags.getBitMap(imageUrls[position]);
// 从内存中或者缓存中
if (bitmap != null) {
iv.setImageBitmap(bitmap);
}
// 获取图片
return iv;
}
}
}
public class EncoderUtils {
/**
* Md5Encoder
*
* @param string
* @return
* @throws Exception
*/
public static String encode(String string) throws Exception {
byte[] hash = MessageDigest.getInstance("MD5").digest(
string.getBytes("UTF-8"));
StringBuilder hex = new StringBuilder(hash.length * 2);
for (byte b : hash) {
if ((b & 0xFF) < 0x10) {
hex.append("0");
}
hex.append(Integer.toHexString(b & 0xFF));
}
return hex.toString();
}
}
================================
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.util.LruCache;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ImagesUtils {
Handler handler;
private File cacheDir;
private ExecutorService newFixedThreadPool;
private LruCache<String, Bitmap> lruCache;
public ImagesUtils(Context context, Handler handler) {
//获得你手机上的最大内存
long maxMemory = Runtime.getRuntime().maxMemory();
int maxSize = (int) (maxMemory/10);
this.handler = handler;
lruCache = new LruCache<String, Bitmap>(maxSize){
@Override
protected int sizeOf(String key, Bitmap value) {
return value.getRowBytes()*value.getHeight();
}
};
//得到sd文件夹
cacheDir = context.getCacheDir();
//
newFixedThreadPool = Executors.newFixedThreadPool(5);
}
public Bitmap getBitMap(String path){
Bitmap bitmap = lruCache.get(path);
if(bitmap!=null){
System.out.println("我走了内存");
return bitmap;
}
//从本直去取,sd卡去取bitmap
bitmap = getBitMapFromLocal(path);
if(bitmap!=null){
System.out.println("我走了本地缓存");
return bitmap;
}
// 从网络去取
getBitmapFromNet(path);
return null;
}
/**
* 从网络
*
* @param path
*/
private void getBitmapFromNet(final String path) {
newFixedThreadPool.execute(new Runnable() {
@Override
public void run() {
try {
URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
int responseCode = connection.getResponseCode();
if (responseCode == 200) {
InputStream inputStream = connection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
Message msg = new Message();
msg.what = 111;
msg.obj = bitmap;
Bundle data = new Bundle();
data.putString("tag", path);
msg.setData(data);
handler.sendMessage(msg);
//缓存到本地
saveBitmapToLocal(bitmap, path);
//缓存到内存
lruCache.put(path, bitmap);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
protected void saveBitmapToLocal(Bitmap bitmap, String path) {
try {
String encode = EncoderUtils.encode(path);
FileOutputStream fileOutputStream = new FileOutputStream(cacheDir
+ "/" + encode);
//图片二次裁剪
bitmap.compress(CompressFormat.JPEG, 80, fileOutputStream);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 从本地取 Md5 a.jpg b.jpg
* aafdgsgsgsggg.jpg
* @param path
*/
private Bitmap getBitMapFromLocal(String path) {
try {
String encode = EncoderUtils.encode(path);
FileInputStream fileInputStream = new FileInputStream(cacheDir
+ "/" + encode);
Bitmap bitmap = BitmapFactory.decodeStream(fileInputStream);
//存到内存
lruCache.put(path, bitmap);
return bitmap;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
================================
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
private GridView gv;
ImagesUtils imags;
String[] imageUrls = new String[] {
"http://img.my.csdn.net/uploads/201407/26/1406383299_1976.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383291_6518.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383291_8239.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383290_9329.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383290_1042.jpg",
"http://img.my.csdn.net/uploads/201407
4000
/26/1406383275_3977.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383265_8550.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383264_3954.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383264_4787.jpg",
};
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what == 0) {
Bitmap bitmap = (Bitmap) msg.obj;
// 设置给imageView
String tag = msg.getData().getString("tag");
// 根据标记取出imageView
ImageView imageView = (ImageView) gv.findViewWithTag(tag);
if (imageView != null && bitmap != null) {
// 从网络获取图片
imageView.setImageBitmap(bitmap);
Log.i("tag", "从网络中获取图片");
}
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imags = new ImagesUtils(this,handler);
gv = (GridView) findViewById(R.id.gv);
gv.setAdapter(new MyAdapter());
}
class MyAdapter extends BaseAdapter {
@Override
public int getCount() {
// TODO Auto-generated method stub
return imageUrls.length;
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView iv = new ImageView(MainActivity.this);
iv.setTag(imageUrls[position]);
Bitmap bitmap = imags.getBitMap(imageUrls[position]);
// 从内存中或者缓存中
if (bitmap != null) {
iv.setImageBitmap(bitmap);
}
// 获取图片
return iv;
}
}
}
相关文章推荐
- 加载一张很大的图片 的时候可能会出现内存溢出,,,处理这张大图片...二次采样
- 图片的二次采样,防止图片加载导致内存不足
- 图片(Bitmap)二次采样、图片内存计算
- 内存缓存图片及原理
- android 网络加载图片,对图片资源进行优化,并且实现内存双缓存 + 磁盘缓存
- Android 图片三级缓存之内存缓存(告别软引用(SoftRefrerence)和弱引用(WeakReference))
- Android 通过软引用实现图片缓存,防止内存溢出
- 图片二次采样
- 网络地址图片的二次采样
- universal image loader源码分析——图片内存缓存
- android中图片的三级cache策略(内存、文件、网络)之三:文件缓存策略
- android中图片的三级cache策略(内存、文件、网络)之二:内存缓存策略
- Android 应用开发 之使用LruCache和DiskLruCache来在内存和SD卡中缓存图片
- 三次缓存,imgloder配置,二次采样
- Android 图片三级缓存之内存缓存(告别软引用(SoftRefrerence)和弱引用(WeakReference))
- 高效显示Bitmap+listview冲突解决+图片内存缓存+硬盘缓存
- android 图片二次采样,质量压缩,LruCache缓存
- android 网络加载图片,对图片资源进行优化,并且实现内存双缓存 + 磁盘缓存
- Android 图片三级缓存之内存缓存(告别软引用(SoftRefrerence)和弱引用(WeakReference))
- 图片的二次采样