Saving png image in database through android app

感情迁移 提交于 2021-02-08 12:10:13

问题


I want to save image using my developed app into mobile what is the best way to it.

I was trying to save via sqlite but is there any other options?


回答1:


The recommended way is to store the image as a file not in the database and then store the path or enough of the path to uniquely identify the image in the database.

To store an image you have to store it as a BLOB based upon a byte[] (byte array); However, using the Android SDK, there is a limitation that only images less than 2MB can be retrieved even though they can be saved.

  • Technically you could store the image as a hex, binary, octal string but that would be more complex, less efficient and even more restrictive.. So really you have to store it as a BLOB is not completely factual.

It's also actually pretty useless storing images (or any large files) with SQLite or most structured databases as there is little that you can do with the data query wise.

You actually save a BLOB via SQL using something like :-

INSERT INTO your_table VALUES(x'00FF01EF');
  • i.e. 00 (0) is the first byte, FF (255) the 2nd, 01 (01) the 3rd .........
  • note the above would only work for a table with a single column

However, the SQLiteDatabase insert convenience method does the conversion from the byte[] to the correct SQL (hex string) on your behalf.

So you'd typically use :-

ContentValues cv = new ContentValues();
cv.put("your_column",your_image_as_a_byte_array);
your_sqlitedatabase_object.insert("your_table",null,cv);

You retrieve the byte array from a Cursor (result of a query) using something along the lines of

your_retrieved_image_byte_array = your_cursor.getBlob(your_column_offset_as_an_int); //<<<<<<<<< CursorWindow full error if the row cannot fit into the CursorWindow which has 2MB limit

You may wish to have a look at How can I insert image in a sqlite database, as this goes into more detail and has code that stores both images and paths (either one is stored based upon the image size, less then 100k, then the image is stored, else the path is stored) and additionally retrieves the images into a ListView. Additionally, although not recommended this is a way of getting around the 2Mb limit How to use images in Android SQLite that are larger than the limitations of a CursorWindow?



来源:https://stackoverflow.com/questions/55503019/saving-png-image-in-database-through-android-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!