本篇文章主要介绍了"Android Sqlite存取图片及转换缩略图",主要涉及到方面的内容,对于SQLite感兴趣的同学可以参考一下:
本来打算用数据库sqlite存取图片(图片都是相机拍摄的原图),结果导致存入和读取的时候会消耗巨大内存,尤其是从数据库取图片时。所以准备存SDCard代替,...
本来打算用数据库sqlite存取图片(图片都是相机拍摄的原图),结果导致存入和读取的时候会消耗巨大内存,尤其是从数据库取图片时。所以准备存SDCard代替,但还是记录下如何用数据库存取图片以及转换成缩略图。
表结构一个String和一个Blob。bitmap不能直接存数据库,用BLOB (binary large object)二进制大对象。
String sql = "create table team (name varchar(20) primary key, image blob);";
bitmap先要转换成二进制数组。
publicbyte[] img(Bitmap bitmap) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
return baos.toByteArray();
}
插入数据库。(person.getImage()就是一个bitmap)
publicvoid insert(Person person) {
SQLiteDatabase db = openHelper.getWritableDatabase();
if (db.isOpen()) {
db.execSQL("insert into team(name,image) values (?, ?);",
new Object[]{person.getName(), img(person.getImage())});
db.close();
}
}
接下来取图片和转换成缩略图。
BitmapFactory.decodeByteArray(in, 0, in.length)可以把取出来的二进制数组in转换成bitmap。
BitmapFactory.Options options = new BitmapFactory.Options(); //解析位图的附加条件
options.inJustDecodeBounds = true; //inJustDecodeBounds设为true,不去解析真实的位图,读取头文件获取基本信息
options.inSampleSize //位图缩放比例,好像实际取值只能是2的幂次方(15取8,17取16,未考证)
最后inJustDecodeBounds = false,接下来就加载缩略图。
public ArrayList queryAll() {
SQLiteDatabase db = openHelper.getReadableDatabase();
if (db.isOpen()) {
Cursor cursor = db.rawQuery("select * from team;", null);
if (cursor != null && cursor.getCount() > 0) {
ArrayList teamList = new ArrayList();
String name;
Bitmap image;
while (cursor.moveToNext()) {
name = cursor.getString(0);
byte[] in = cursor.getBlob(1);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
image = BitmapFactory.decodeByteArray(in, 0, in.length, options);
int bitmapWidth = options.outWidth;
int bitmapHeight = options.outHeight;
int x = 180;
int dx = bitmapWidth / x;
int dy = bitmapHeight / x;
if (dx > dy && dy > 1) {
options.inSampleSize = dx;
}
if (dy > dx && dx > 1) {
options.inSampleSize = dy;
}
options.inJustDecodeBounds = false;
image = BitmapFactory.decodeByteArray(in, 0, in.length, options);
teamList.add(new Person(name, image));
}
db.close();
return teamList;
}
db.close();
returnnull;
}
returnnull;
}
以上就介绍了Android Sqlite存取图片及转换缩略图,包括了方面的内容,希望对SQLite有兴趣的朋友有所帮助。
本文网址链接:http://www.codes51.com/article/detail_132134.html