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; }