I am storing an image taken from camera into sqlite database can anybody help me to retrieve the same image and i want to show that image in a image view.
Here is my Database handler class method for saving the image
public long insert(Bitmap img ) {
SQLiteDatabase base=this.getWritableDatabase();
byte[] data = getBitmapAsByteArray(img); // this is a function
ContentValues value=new ContentValues();
value.put("image",data);
long a= base.insert("Mypic", null, value);
System.out.println("check1" + a);
return a;
}
public static byte[] getBitmapAsByteArray(Bitmap bitmap)
{
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0, outputStream);
return outputStream.toByteArray();
}
Please help me for writing the method how i can get the image and display the image in an imageview.
To insert Image on database:
Bitmap bitmap = ((BitmapDrawable) image_imgv.getDrawable()).getBitmap();
ByteArrayOutputStream bos4 = new ByteArrayOutputStream();
bitmap4.compress(Bitmap.CompressFormat.PNG, 100, bos4);
image = bos4.toByteArray();
database = new BBDD(this, "BBDD", null, 1);
SQLiteDatabase db = database.getWritableDatabase();
ContentValues reg = new ContentValues();
reg.put("img", image);
To retrieve:
database2 = new BBDD(Activity.this, "BBDD", null, 1);
SQLiteDatabase db2 = database2.getReadableDatabase();
if (db2 != null)
{
Cursor cursor = db2.rawQuery("SELECT img FROM database2, null);
if (cursor.moveToFirst())
{
img=cursor.getBlob(cursor.getColumnIndex("img"));
Bitmap b1=BitmapFactory.decodeByteArray(image, 0, image.length);
image_imageview.setImageBitmap(b1);
}
else
Toast.makeText(Activity.this, "Error.", Toast.LENGTH_LONG).show();
db2.close();
}
else
Toast.makeText(sActivity.this, "Error db.", Toast.LENGTH_LONG).show();
}
});
Related
How can I properly change this byte[] photo = getBytes(imageBitmap); to be stored in a database Blob?
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
//ImageView imageview = findViewById(R.id.imageView);
//imageview.setImageBitmap(imageBitmap);
//Bitmap to bytes for database
byte[] photo = getBytes(imageBitmap);
Bitmap bmp = BitmapFactory.decodeByteArray(photo, 0, photo.length);
ImageView image = (ImageView) findViewById(R.id.imageView);
image.setImageBitmap(Bitmap.createScaledBitmap(bmp, image.getWidth(), image.getHeight(), false));
// DatabaseHandler mydb = new DatabaseHandler(getApplicationContext());
// Walk walk = new Walk(photo);
// mydb.addWalk(walk);
}
Have you tried to use the ByteArrayOutputStream?
You can check at the documentation https://developer.android.com/reference/java/io/ByteArrayOutputStream.html
Or to make it ease you can do like this guy did
converting Java bitmap to byte array
`
Bitmap bmp = intent.getExtras().get("data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
bmp.recycle();
`
First of all, what's the exact problem? Saving the image or storing it into the db?
CREATE TABLE t1 (id INTEGER PRIMARY KEY, data BLOB);
Comes down to this:
InputStream is = context.getResources().open(R.drawable.MyImageFile);
try {
byte[] buffer = new byte[CHUNK_SIZE];
int size = CHUNK_SIZE;
while(size == CHUNK_SIZE) {
size = is.read(buffer); //read chunks from file
if (size == -1) break;
ContentValues cv = new ContentValues();
cv.put(CHUNK, buffer); //CHUNK blob type field of your table
long rawId = database.insert(TABLE, null, cv); //TABLE table name
}
} catch (Exception e) {
Log.e(TAG, "Error saving raw image to: "+rawId, e);
}
I created a simple app in which the image store from the ImageView to the database.
But when click on the retrive button is show that index 1 requested with size of 3.
I don't know what thing is going wrong.
database class:
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_IMAGE_TABLE = "CREATE TABLE " +TABLE_NAME + "("
+ IMAGE_KEY + " BLOB )";
db.execSQL(CREATE_IMAGE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
public boolean insertData(byte[]image )throws SQLiteException
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv=new ContentValues();
cv.put(IMAGE_KEY,image);
long result= db.insert(TABLE_NAME,null,cv);
if(result==-1)
return false;
else
return true;
}
public Cursor getAllData()
{
SQLiteDatabase db=this.getReadableDatabase();
Cursor res=db.rawQuery("select * from "+TABLE_NAME,null);
byte[]img=res.getBlob(0);
return res;
}
And this is the activity class:
public void button2(View view)
{
try {
Cursor res = myDb.getAllData();
if (res ==null) {
showMessage("error", "no data found");
} else {
StringBuffer buffer = new StringBuffer();
while (res.moveToNext()) {
buffer.append("id:" + res.getBlob(0) + "\n");
byte[] image = res.getBlob(0);
Bitmap bmp = BitmapFactory.decodeByteArray(image, 0,
image.length);
imagee.setImageBitmap(bmp);
}
// showMessage("DATA", buffer.toString());
}
}
catch (Exception e)
{
Toast.makeText(getBaseContext(),e.getMessage(),
Toast.LENGTH_LONG).show();
}}
public void buttonn(View view)
{
Bitmap bitmap = ((BitmapDrawable) imagee.getDrawable()).getBitmap();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 0, outputStream);
byte[] data = outputStream.toByteArray();
boolean isInserted = myDb.insertData(data);
if (isInserted == true)
Toast.makeText(getBaseContext(), "Registration Succes!",
Toast.LENGTH_SHORT).show();
else
Toast.makeText(getBaseContext(), "No Record Registered!",
Toast.LENGTH_SHORT).show();
}
}
I tried most but couldn't do not thing.I change it from res.movetoNext but show the same error and use res.movetoFirst it also show the same error
Android sqlite CursorWindow has a fixed size buffer that is 2MB on most configurations. You cannot move around rows any larger than that.
Don't store large binary data such as images in Android sqlite. Use external storage instead and just save the path in your database.
Check this code about how to save an image in android:
private String saveToInternalStorage(Bitmap bitmapImage){
ContextWrapper cw = new ContextWrapper(getApplicationContext());
// path to /data/data/yourapp/app_data/imageDir
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
// Create imageDir
File mypath=new File(directory,"profile.jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
// Use the compress method on the BitMap object to write image to the OutputStream
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
} catch (Exception e) {
e.printStackTrace();
} finally {
fos.close();
}
return directory.getAbsolutePath();
}
You need just to add the path of your image into your database instead of the blob image.
Reference: Saving and Reading Bitmaps/Images from Internal memory in Android
I'm trying to save a photo as a blob in the SQLite (not just reference it). mCurrentMediaPath is the current path where the photo will be stored. Now, I need to save it to the database after the picture is taken and save button pressed (I guess after the intent).
public Uri insert(byte[] image) {
return getContentResolver().insert(MyContentProvider.CONTENT_URI7, createContentValues(image));
}
private ContentValues createContentValues(byte[] image) {
ContentValues docsInsert = new ContentValues();
docsInsert.put(Db.COLUMN_FILETYPE, "PHOTO");
docsInsert.put(Db.COLUMN_NAME, mCurrentMediaPath);
docsInsert.put(Db.COLUMN_FILE, image);
return docsInsert;
}
// convert from bitmap to byte array
public byte[] getBytesFromBitmap(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 70, stream);
return stream.toByteArray();
}
private void dispatchMediaIntent(int actionCode) {
switch(actionCode) {
case ACTION_TAKE_PHOTO:
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = null;
try {
f = setUpPhotoFile(ACTION_TAKE_PHOTO);
mCurrentMediaPath = f.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
} catch (IOException e) {
e.printStackTrace();
f = null;
mCurrentMediaPath = null;
}
startActivityForResult(takePictureIntent, actionCode);
break;
case ACTION_TAKE_VIDEO:
Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
startActivityForResult(takeVideoIntent, actionCode);
break;
default:
break;
}
}
Where should I implement the insertion?
//SAVING TO DATABASE
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(mCurrentMediaPath, bmOptions);
Bitmap bitmap = BitmapFactory.decodeFile(mCurrentMediaPath, bmOptions);
insert(getBytesFromBitmap(bitmap));
Create bitmap of your image then
Bitmap bmp = BitmapFactory.decodeStream(new FileInputStream(f), null, null);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] byteArray = stream.toByteArray();
dba.open();
dba.insertPhoto(byteArray);
where dba is object of database class.
create table in database class like:
private static final String CREATETABLE_PHOTO = "create table eqpphoto("EImage BLOB " + ");";
public static final String TABLE_PHOTO = "eqpphoto";
public long insertPhoto(byte[] EImage) {
try {
System.out.println("Function call : ");
ContentValues values = new ContentValues();
values.put(EIMAGE, EImage);
return db.insert(TABLE_PHOTO, null, values);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
I'm currently creating thumbnails by using the ThumbnailUtils.createVideoThumbnail() method; which returns a bitmap. However, I want to store that thumbnail in a database so I can access it later and I don't have to keep recreating the thumbnails. My questions is how should I store this thumbnail in the database? Do thumbnails have filepaths? Or should I create the thumbnails and just retrieve them using the Mediastore every time I need to use it? If so how would I go about saving/storing the thumbnail so I can use the Mediastore to query it?
Thanks for your help.
If you're getting a Thumbnail object from video, you need to save it in either storage or database.
To save in database :
Bitmap thumbnailBitmap; // Get it with your approach
SQLiteDatabase writableDb; // Get it with your approach
if (thumbnailBitmap != null) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
thumbnailBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] thumbnailBitmapBytes = stream.toByteArray();
ContentValues values = new ContentValues();
values.put("IMAGEID", "your_image_id");
values.put("BYTES", thumbnailBitmapBytes);
writableDb.insert("TABLE_NAME", null, values);
}
To get it back from database :
public static synchronized Bitmap getImage(String imageID, Context context) {
SQLiteDatabase writableDb; // Get it with your approach
Bitmap bitmap = null;
Cursor cs = null;
try {
String sql = "SELECT BYTES FROM TABLE_NAME WHERE IMAGEID = ?;";
cs = writableDb.rawQuery(sql, new String[]{imageID});
if (cs != null && cs.moveToFirst()) {
do {
byte[] bytes = cs.getBlob(0);
if (bytes != null) {
try {
bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
} catch (Exception e) {
Log.e("TAG", "Exception", e);
}
} else {
Log.e("TAG", "IMAGE NOT FOUND");
}
} while (cs.moveToNext());
}
} catch (Exception e) {
Log.e("TAG", "Exception", e);
} finally {
if (cs != null) {
cs.close();
}
}
return bitmap;
}
The database structure:
String imageTable = "CREATE TABLE TABLE_NAME("
+ "IMAGEID TEXT PRIMARY KEY, "
+ "BYTES BLOB)";
I want to store an image(from url) into a sqlite database.
For that I use:
db = new DataBase(getApplicationContext());
URL url = new URL("http://sree.cc/wp-content/uploads/schogini_team.png");
URLConnection ucon = url.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is,128);
ByteArrayBuffer barb= new ByteArrayBuffer(128);
int current = 0;
while ((current = bis.read()) != -1) {
barb.append((byte) current);
}
ContentValues filedata= new ContentValues();
filedata.put(DataBase.IMG_SRC,barb.toByteArray());
db.insert(DataBase.Table_Img, null, filedata);
In the Insert():
public void insert(String tableImg, Object object,
ContentValues dataToInsert) {
// TODO Auto-generated method stub
String sql = "INSERT INTO "+tableImg+" ("+ID+","+IMG_SRC+") " +
"VALUES ('"+1+"','"+dataToInsert+"')";
db.execSQL(sql);
}
For the retrieval of image:
Cursor cursor = db.selectDataToShow(DataBase.Table_Img, DataBase.IMG_SRC);
byte[] imageByteArray=cursor.getBlob(cursor.getColumnIndex(DataBase.IMG_SRC));
cursor.close();
ByteArrayInputStream imageStream = new ByteArrayInputStream(imageByteArray);
Bitmap theImage = BitmapFactory.decodeStream(imageStream);
System.out.println(">>>>>>>>>>>>>>>>>>>>>> "+theImage);
So here I got null.
And in my database the value of image stored as: Image=[B#43e5ac48]
Here the code i used for my app
This code will take a image from url and convert is to a byte array
byte[] logoImage = getLogoImage(IMAGEURL);
private byte[] getLogoImage(String url){
try {
URL imageUrl = new URL(url);
URLConnection ucon = imageUrl.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(500);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
return baf.toByteArray();
} catch (Exception e) {
Log.d("ImageManager", "Error: " + e.toString());
}
return null;
}
To save the image to db i used this code.
public void insertUser(){
SQLiteDatabase db = dbHelper.getWritableDatabase();
String delSql = "DELETE FROM ACCOUNTS";
SQLiteStatement delStmt = db.compileStatement(delSql);
delStmt.execute();
String sql = "INSERT INTO ACCOUNTS (account_id,account_name,account_image) VALUES(?,?,?)";
SQLiteStatement insertStmt = db.compileStatement(sql);
insertStmt.clearBindings();
insertStmt.bindString(1, Integer.toString(this.accId));
insertStmt.bindString(2,this.accName);
insertStmt.bindBlob(3, this.accImage);
insertStmt.executeInsert();
db.close();
}
To retrieve the image back this is code i used.
public Account getCurrentAccount() {
SQLiteDatabase db = dbHelper.getWritableDatabase();
String sql = "SELECT * FROM ACCOUNTS";
Cursor cursor = db.rawQuery(sql, new String[] {});
if(cursor.moveToFirst()){
this.accId = cursor.getInt(0);
this.accName = cursor.getString(1);
this.accImage = cursor.getBlob(2);
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
db.close();
if(cursor.getCount() == 0){
return null;
} else {
return this;
}
}
Finally to load this image to a imageview
logoImage.setImageBitmap(BitmapFactory.decodeByteArray( currentAccount.accImage,
0,currentAccount.accImage.length));
in the DBAdaper i.e Data Base helper class declare the table like this
private static final String USERDETAILS=
"create table userdetails(usersno integer primary key autoincrement,userid text not null ,username text not null,password text not null,photo BLOB,visibility text not null);";
insert the values like this,
first convert the images as byte[]
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Bitmap bitmap = ((BitmapDrawable)getResources().getDrawable(R.drawable.common)).getBitmap();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] photo = baos.toByteArray();
db.insertUserDetails(value1,value2, value3, photo,value2);
in DEAdaper class
public long insertUserDetails(String uname,String userid, String pass, byte[] photo,String visibility)
{
ContentValues initialValues = new ContentValues();
initialValues.put("username", uname);
initialValues.put("userid",userid);
initialValues.put("password", pass);
initialValues.put("photo",photo);
initialValues.put("visibility",visibility);
return db.insert("userdetails", null, initialValues);
}
retrieve the image as follows
Cursor cur=your query;
while(cur.moveToNext())
{
byte[] photo=cur.getBlob(index of blob cloumn);
}
convert the byte[] into image
ByteArrayInputStream imageStream = new ByteArrayInputStream(photo);
Bitmap theImage= BitmapFactory.decodeStream(imageStream);
I think this content may solve your problem
In insert()
public void insert(String tableImg, Object object,
ContentValues dataToInsert) {
db.insert(tablename, null, dataToInsert);
}
Hope it helps you.
for a ionic project
var imgURI = "";
var imgBBDD = ""; //sqllite for save into
function takepicture() {
var options = {
quality : 75,
destinationType : Camera.DestinationType.DATA_URL,
sourceType : Camera.PictureSourceType.CAMERA,
allowEdit : true,
encodingType: Camera.EncodingType.JPEG,
targetWidth: 300,
targetHeight: 300,
popoverOptions: CameraPopoverOptions,
saveToPhotoAlbum: false
};
$cordovaCamera.getPicture(options).then(function(imageData) {
imgURI = "data:image/jpeg;base64," + imageData;
imgBBDD = imageData;
}, function(err) {
// An error occured. Show a message to the user
});
}
And now we put imgBBDD into SqlLite
function saveImage = function (theId, theimage){
var insertQuery = "INSERT INTO images(id, image) VALUES("+theId+", '"+theimage+"');"
console.log('>>>>>>>');
DDBB.SelectQuery(insertQuery)
.then( function(result) {
console.log("Image saved");
})
.catch( function(err)
{
deferred.resolve(err);
return cb(err);
});
}
A server side (php)
$request = file_get_contents("php://input"); // gets the raw data
$dades = json_decode($request,true); // true for return as array
if($dades==""){
$array = array();
$array['error'] = -1;
$array['descError'] = "Error when get the file";
$array['logError'] = '';
echo json_encode($array);
exit;
}
//send the image again to the client
header('Content-Type: image/jpeg');
echo '';
byte[] byteArray = rs.getBytes("columnname");
Bitmap bm = BitmapFactory.decodeByteArray(byteArray, 0 ,byteArray.length);
you may also want to encode and decode to/from base64
function uncompress(str:String):ByteArray {
import mx.utils.Base64Decoder;
var dec:Base64Decoder = new Base64Decoder();
dec.decode(str);
var newByteArr:ByteArray=dec.toByteArray();
return newByteArr;
}
// Compress a ByteArray into a Base64 String.
function compress(bytes:ByteArray):String {
import mx.utils.Base64Decoder; //Transform String in a ByteArray.
import mx.utils.Base64Encoder; //Transform ByteArray in a readable string.
var enc:Base64Encoder = new Base64Encoder();
enc.encodeBytes(bytes);
return enc.drain().split("\n").join("");
}