Storing images in SQLite android - 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);
}

Related

Bitmap Not set to Imageview

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!!

Android Database Storing & Retrieving

Hi I am a New to Android. Can Some One Describe the way if any of storing a Image to Android database & retrieve it ?
Look at this tutorial...
http://www.tutorialforandroid.com/2009/10/how-to-insert-image-data-to-sqlite.html
and you can use this code :
for storing image :
Map<String, byte[]> hh = new HashMap<String, byte[]>();
String hi = "http://i.stack.imgur.com/TLjuP.jpg";
byte[] logoImagedata = getLogoImage(hi);
hh.put("img",logoImagedata);
for retriving :
byte[] imageByteArray = hh.get("img");
ByteArrayInputStream imageStream = new ByteArrayInputStream(imageByteArray);
Bitmap theImage= BitmapFactory.decodeStream(imageStream);
and getLogoImage:
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;
}
}
I hope this help you .

cant load the image from sqlite database in android

I tried to load an image from an database but the image is not loading,the logcat shows null
is it simethinf with the way i programmed..
imgdisplay = (ImageView) findViewById(R.id.imgIcon);
myDB = this.openOrCreateDatabase("hello", MODE_PRIVATE, null);
Cursor c = myDB.rawQuery(
"SELECT image FROM employee_details WHERE name= 'vv'", null);
if (c.getCount() > 0) {
c.moveToFirst();
do {
byte[] blob = c.getBlob(c.getColumnIndex("image"));
ImageView iv = (ImageView) findViewById(R.id.imgIcon);
iv.setImageBitmap(BitmapFactory.decodeByteArray(blob, 0,blob.length));
} while (c.moveToNext());
}
c.close();
myDB.close();
Logcat error is...
08-02 04:51:25.471: D/skia(8433): --- SkImageDecoder::Factory returned null
try below code..
byte[] Image_bytes = cursor.getBlob(cursor.getColumnIndex("image"));
ImageView iv = (ImageView) findViewById(R.id.imgIcon);
iv.setImageBitmap(new ImageConversation().convertArrayToBmp(Image_bytes));
...
public Bitmap convertArrayToBmp(byte[] array) {
Bitmap bitmap = BitmapFactory.decodeByteArray(array, 0, array.length);
return bitmap ;
}
use following loop
c.moveToFirst();
while(!c.isAfterLast()) {
byte[] blob = c.getBlob(c.getColumnIndex("image"));
ImageView iv = (ImageView) findViewById(R.id.imgIcon);
iv.setImageBitmap(BitmapFactory.decodeByteArray(blob, 0,blob.length));
c.moveToNext()
}
Try doing something like this -
If you are storing your image as String in database
if(image.isEmpty())
{
System.out.println("is empty image");
}
else
{
byte[] decodedByte = Base64.decode(image, 0);
Bitmap bm = BitmapFactory.decodeByteArray(decodedByte, 0,
decodedByte.length);
iv.setImageBitmap(bm);
}
I didn't find a method to save the image to the database so I started to save the image directly to the internal memory,this is not the answer for the question but may give some ideas to others who also don't have any idea to do...
To save into internal memory...
File fileWithinMyDir = getApplicationContext().getFilesDir();
try
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
URL url = new URL("http://t2.gstatic.com /images?q=tbn:ANd9GcQjZgUffqqe2mKKb5VOrDNd-ZxD7sJOU7WAHlFAy6PLbtXpyQZYdw");
File file = new File( fileWithinMyDir.getAbsolutePath() + "/" +"sun.jpg");
URLConnection ucon = url.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1)
{
baf.append((byte) current);
}
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.close();
}
catch (IOException e)
{
Log.e("download", e.getMessage());
}
To load image from internal memory..
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
mImgView1 = (ImageView) findViewById(R.id.mImgView1);
Bitmap bitmap = BitmapFactory.decodeFile(fileWithinMyDir.getAbsolutePath() + "/" +"sunn"+".file extension");
mImgView1.setImageBitmap(bitmap);
This is for newer android's that show error due to " android.os.networkonmainthreadexception"
u can also use AsyncTask if u want to solve the problem...

display images using URL from Sqlite DB

I want to save images from a particular URL into the sqlite db and
then display it from the database..Can anyone tell me as how i could
do that.
Thanks in advance.
Regards,
Raghav Rajagopalan
try this code.
URL url = new URL("your image url");
URLConnection ucon = url.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is,128);
ByteArrayBuffer barb= new ByteArrayBuffer(128);
//read the bytes one by one and append it into the ByteArrayBuffer barb
int current = 0;
while ((current = bis.read()) != -1) {
barb.append((byte) current);
}
ContentValues filedata= new ContentValues();
//TABLE_FIELD = a field in the database table of type text
filedata.put(TABLE_FIELD,barb.toByteArray());
//TABLE_NAME = a table in the database with a field TABLE_FIELD
db.insert(TABLE_NAME, null, filedata);
//Retriving Data from DB:
//select the data
Cursor cursor = db.query(TABLE_STATIONLIST, new String[] {TABLE_FIELD},null, null, null, null, null);
//get it as a ByteArray
//reading as Binary large object(BLOB)
byte[] imageByteArray=cursor.getBlob(1);
//the cursor is not needed anymore so release it
cursor.close();
Bitmap image=getbyteAsBitmap(imageByteArray);
//use this method to convert byte[] to bitmap
private Bitmap getbyteAsBitmap(byte[] bytedata){
if(bytedata!=null){
ByteArrayInputStream imageStream = new ByteArrayInputStream(bytedata);
Bitmap theImage = BitmapFactory.decodeStream(imageStream);
//theImage=MediaProcesser.getRoundedCornerBitmap(theImage, 5);
return theImage;
}else{
return null;
}
}

how to store Image as blob in Sqlite & how to retrieve it?

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

Categories

Resources