Bitmap Not set to Imageview - android

Below is the code :
db.execSQL("CREATE TABLE IF NOT EXISTS SaveRetriveDB (IMG_ID INTEGER PRIMARY KEY,ImgTxt VARCHAR,StoreImg BLOB);");
db.execSQL("INSERT INTO SaveRetriveDB(ImgTxt,StoreImg)VALUES('txt','" + imageInByte + "')");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
yourImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
imageInByte = stream.toByteArray();
Cursor c = db.rawQuery("SELECT StoreImg FROM SaveRetriveDB where IMG_ID=2", null);
if (c.moveToNext()){
byte InByte[] = c.getBlob(c.getColumnIndex("StoreImg"));
Bitmap b1 = BitmapFactory.decodeByteArray(InByte, 0, InByte.length);
ImageView imageView1=(ImageView)findViewById(R.id.imageView_image);
imageView1.setImageBitmap(b1);
Toast.makeText(getApplicationContext(),InByte.toString(),Toast.LENGTH_SHORT).show();
}
I am getting byte array from DB, when trying to convert byte array into image, its not working.

Replace your code with
Cursor c = db.rawQuery("SELECT StoreImg FROM SaveRetriveDB where IMG_ID=2", null);
if (c != null && c.getCount() > 0 && c.moveToFirst())
byte InByte[] = c.getBlob(c.getColumnIndex("StoreImg"));
Bitmap b1 = BitmapFactory.decodeByteArray(InByte, 0, InByte.length);
ImageView imageView1 = (ImageView) findViewById(R.id.imageView_image);
imageView1.setImageBitmap(b1);
Toast.makeText(getApplicationContext(), InByte.toString(), Toast.LENGTH_SHORT).show();
}
it will work
Happy coding!!

Related

Android: How to pass byte array to blob (storing camera image into sqlite)

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

URL image to imageview to drawable

ImageView img1;
img1 = (ImageView) findViewById (R.id.img1);
URL newurl = new URL("http://10.0.2.2:80/Gallardo/Practice/files/images/donut.jpg");
Bitmap mIcon_val = BitmapFactory.decodeStream(newurl.openConnection() .getInputStream());
img1.setImageBitmap(mIcon_val);
I get image from url but I want to store it to my drawable, how?
Everything in the apk will be read only.
So you can't write to drawable.
you have to use "blob" to store image.
ex: to store a image in to db
public void insertImg(int id , Bitmap img ) {
byte[] data = getBitmapAsByteArray(img); // this is a function
insertStatement_logo.bindLong(1, id);
insertStatement_logo.bindBlob(2, data);
insertStatement_logo.executeInsert();
insertStatement_logo.clearBindings() ;
}
public static byte[] getBitmapAsByteArray(Bitmap bitmap) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0, outputStream);
return outputStream.toByteArray();
}
to retrieve a image from db
public Bitmap getImage(int i){
String qu = "select img from table where feedid=" + i ;
Cursor cur = db.rawQuery(qu, null);
if (cur.moveToFirst()){
byte[] imgByte = cur.getBlob(0);
cur.close();
return BitmapFactory.decodeByteArray(imgByte, 0, imgByte.length);
}
if (cur != null && !cur.isClosed()) {
cur.close();
}
return null ;
}
You can also check this saving image to database
You can construct Drawable by using this constructor:
Drawable drawable = new BitmapDrawable(getResources(), mIcon_val);
You can set it to the ImageView like so:
img1.setImageDrawable(drawable);
Its not possible to place image in drawable folder while running the apk.. Saving an image to SDcard is possible..

How to retrieve an image from a SQLite database?

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

I can't add photo to a contact when the contact was got (synchronized) from a google service

I have to ways to add photo to contact (see below). It work only when the contact was created on my device. It not work when the contact was got (synchronized) from a google service. And I have no any errors on runtime.
My device is working on Android 4.1.1
First way (from http://developer.android.com/reference/android/provider/ContactsContract.RawContacts.DisplayPhoto.html):
public static void writeDisplayPhoto(ContentResolver c, Bitmap contactPhoto, long personId) {
// control args
if ((contactPhoto == null)||(c==null)||(personId==0l)) {
return;
}
// convert bitmap to byte
ByteArrayOutputStream bos = new ByteArrayOutputStream();
contactPhoto.compress(CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
byte[] photo = bos.toByteArray();
Log.i("CallWidgetConfig::writeDisplayPhoto()","personId: "+personId);
// set tpoto to contact
Uri rawContactPhotoUri = Uri.withAppendedPath(
ContentUris.withAppendedId(RawContacts.CONTENT_URI, personId),
RawContacts.DisplayPhoto.CONTENT_DIRECTORY);
try {
AssetFileDescriptor fd =
c.openAssetFileDescriptor(rawContactPhotoUri, "rw");
OutputStream os = fd.createOutputStream();
os.write(photo);
os.close();
fd.close();
} catch (Exception e) {
Log.i("CallWidgetConfig::writeDisplayPhoto()",e.getMessage());
}
}
Second way:
public static void setContactPhoto(ContentResolver c, Bitmap contactPhoto, long personId) {
if ((contactPhoto == null)||(c==null)||(personId==0l)) {
return;
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
contactPhoto.compress(CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
byte[] bytes = bos.toByteArray();
int photoRow = -1;
String where = Data.RAW_CONTACT_ID + " = " + personId + " AND "
+ Data.MIMETYPE + "=='" + Photo.CONTENT_ITEM_TYPE
+ "'";
Cursor cursor = null;
try {
cursor = c.query(Data.CONTENT_URI, null, where, null, null);
int idIdx = cursor.getColumnIndexOrThrow(Data._ID);
if (cursor.moveToFirst()) {
photoRow = cursor.getInt(idIdx);
Log.i("CallWidgetConfig::setContactPhoto()","photoRow: "+photoRow);
}
}
catch (Exception e) {
Log.i("CallWidgetConfig::setContactPhoto()",e.getMessage());
if (cursor!=null) {
cursor.close();
}
return;
}
ContentValues values = new ContentValues();
values.put(Data.RAW_CONTACT_ID, personId);
values.put(Data.IS_SUPER_PRIMARY, 1);
values.put(Photo.PHOTO, bytes);
values.put(Data.MIMETYPE, Photo.CONTENT_ITEM_TYPE);
if (photoRow >= 0) {
Log.i("CallWidgetConfig::setContactPhoto()","Update()");
c.update(Data.CONTENT_URI, values, Data._ID + " = " + photoRow, null);
} else {
Log.i("CallWidgetConfig::setContactPhoto()","Insert()");
c.insert(Data.CONTENT_URI, values);
}
cursor.close();
}

Storing images in SQLite android

I have an SQLite Database in which I am storing images as BLOB using this code
URL url = new URL("http://t0.gstatic.com/images?q=tbn:ANd9GcRsaLl3TGB4W2hJFN_Wh0DNVPQEYGtweNsqvTXVtwE8FXR300-Ut-npgS4");
//open the connection
URLConnection ucon = url.openConnection();
//buffer the download
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is,128);
ByteArrayBuffer baf = new ByteArrayBuffer(128);
//get the bytes one by one
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
mydb.execSQL("INSERT INTO " + TABLE + "(IMAGE) VALUES('" + baf.toByteArray() + "')");
mydb.close();
When I try to retrive the image, I am getting the following error
Factory returned null
My Select Query is this
mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
Cursor allrows = mydb.rawQuery("SELECT * FROM "+ TABLE, null);
if(allrows.getCount() > 0){
allrows.moveToNext();
System.out.println("3333");
ImageView myImage = (ImageView) findViewById(R.id.ImageView01);
byte[] bb = allrows.getBlob(1);
System.out.println("VVV " + bb);
//convert it back to an image
ByteArrayInputStream imageStream = new ByteArrayInputStream(bb);
Bitmap theImage = BitmapFactory.decodeStream(imageStream);
myImage.setImageBitmap(theImage);
//myImage.setBackgroundResource(R.drawable.icon);
System.out.println("3333");
//myImage.setImageBitmap(BitmapFactory.decodeByteArray(bb, 0, bb.length));
}
Please anyone help.
I use decodeByteArray method
byte[] userPic1Blob = cursor.getBlob(cursor.getColumnIndex(SqlConstans.USER_PIC1_BLOB));
if(userPic1Blob != null && userPic1Blob.length > 0){
Bitmap bm = BitmapFactory.decodeByteArray(userPic1Blob, 0, userPic1Blob.length);
imageView.setImageBitmap(bm);
}

Categories

Resources