`
bell0901
  • 浏览: 27694 次
社区版块
存档分类
最新评论

Android数据库存取图片以及转换成缩略图

阅读更多

  本来打算用数据库sqlite存取图片(图片都是相机拍摄的原图),结果导致存入和读取的时候会消耗巨大内存,尤其是从数据库取图片时。所以准备存SDCard代替,但还是记录下如何用数据库存取图片以及转换成缩略图。

  表结构一个String和一个Blob。bitmap不能直接存数据库,用BLOB (binary large object)二进制大对象。

String sql = "create table team (name varchar(20) primary key, image blob);";

  bitmap先要转换成二进制数组。

public byte[] img(Bitmap bitmap) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }

  插入数据库。(person.getImage()就是一个bitmap)

public void 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<Person> queryAll() {
        SQLiteDatabase db = openHelper.getReadableDatabase();
        if (db.isOpen()) {
            Cursor cursor = db.rawQuery("select * from team;", null);
            if (cursor != null && cursor.getCount() > 0) {
                ArrayList<Person> teamList = new ArrayList<Person>();
                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();
            return null;
        }
        return null;
    }
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics