Get the App
SLTechnology News&Howtos  ›  Database  › 

How to access pictures in Android database

Shulou Source: shulou.com Published: 2022-05-31 19:33:59 09月18日 Update

In order to solve the problem of how to access pictures in Android database, this article introduces the corresponding analysis and answer in detail, hoping to help more partners who want to solve this problem to find a simpler and easier way.

1. Database creation and access methods:

When the database is created, the data type of the picture field is stored as a BLOB database insert operation

Public void onCreate (SQLiteDatabase db) {String sql = "create table" + TB_NAME + "(" + ID + "integer primary key," + IMAGE + "BLOB)"; db.execSQL (sql);}

Store the picture in one-byte form for database read operation

Public long insert (byte [] img) {SQLiteDatabase db = getWritableDatabase (); ContentValues cv = new ContentValues (); cv.put (IMAGE, img); long result = db.insert (TB_NAME, null, cv); return result;}

The resulting picture is of Bitmap type. Click on the position of the picture in ListView, GridView, etc., parameter position, and you can write code 2 as needed.

Public Bitmap getBmp (int position) {SQLiteDatabase db = getReadableDatabase (); Cursor cursor = select (TB_NAME); cursor.moveToPosition (position); byte [] in = cursor.getBlob (cursor.getColumnIndex (IMAGE)); Bitmap bmpout = BitmapFactory.decodeByteArray (in, 0, in.length); return bmpout;}

2. Convert pictures to byte [] / / Parameter id to image resources (R.drawable.img)

Public byte [] img (int id) {ByteArrayOutputStream baos = new ByteArrayOutputStream (); Bitmap bitmap = ((BitmapDrawable) getResources (). GetDrawable (id)). GetBitmap (); bitmap.compress (Bitmap.CompressFormat.PNG, 100, baos); return baos.toByteArray () } this is the answer to the question about how to access pictures in the Android database. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel for more related knowledge.

Tags: Pictures data databases access questions parameters methods more types Storage help answers easy easy Code location content Picture Resources Fields bytes Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Technology MySQL Huawei Docker Microsoft