How to Insert Image in Sqlite Database? - android

here I want to send my image in database.. but i Can't assign imgPro to values.put.. Please help me..
else if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
imgPro.setImageBitmap(thumbnail);
}

You can do like below.
public class ImageConverter {
public static String imageToStringConverter(Bitmap image){
ByteArrayOutputStream stream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
String imageToString = Base64.encodeToString(byteArray, Base64.NO_WRAP);
return imageToString;
}
public static Bitmap stringToimageConverter(String imageString){
byte[] stringTobyte = Base64.decode(imageString, Base64.NO_WRAP);
Bitmap bmp = BitmapFactory.decodeByteArray(stringTobyte, 0, stringTobyte.length);
return bmp;
}
}
You will call this two function to convert the image into string and then save in the database.Like below
String statusImage = ImageConverter.imageToStringConverter(selectedImage);
selectedImage is the bitmap you have selected from file. and if u want show the image then just again convert the string back to image.
Now why Base64??
When you have some binary data that you want to ship across a network,
you generally don't do it by just streaming the bits and bytes over
the wire in a raw format. Why? because some media are made for
streaming text. You never know -- some protocols may interpret your
binary data as control characters (like a modem), or your binary data
could be screwed up because the underlying protocol might think that
you've entered a special character combination (like how FTP
translates line endings).
So to get around this, people encode the binary data into characters.
Base64 is one of these types of encodings. Why 64? Because you can
generally rely on the same 64 characters being present in many
character sets, and you can be reasonably confident that your data's
going to end up on the other side of the wire uncorrupted.

Related

how to store an image path for an image loaded in imageview android

the user will select an image that will later be uploaded on his command without selecting the image themselves. I have tried some of the option on SO but the option i used seems to be replicating a black image and storing its own path. I need the same image to be used and uploaded please help.
the code for the saving is as follows:
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
public String getRealPathFromURI(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
and the code i am using to then get this image later is:
Bitmap bitmap = BitmapFactory.decodeFile(submissions.getLinkToDoc());
documents.setImageBitmap(bitmap);
where submissions.getLinkToDoc() is the path stored by the code above.

Decode Base 64 string to bitmap Failed

I am in middle of a project .I want to upload an image from my app to server.I encoded the image from imageview and upload to server as Base64 string and decoded it back to display in imageview.But I face issue with decoding Base64 string back into bitmap.I am getting
Caused by: java.lang.IllegalArgumentException: bad base-64
The code I used for encoding and decoding is given below:
For encoding:
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
System.out.println("PicturePath:"+picturePath);
imgImage.setImageBitmap(BitmapFactory.decodeFile(picturePath));
Bitmap bitmapOrg = BitmapFactory.decodeFile(picturePath);
System.out.println("15102015 bitmap:" + bitmapOrg.toString());
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 100, bao);
byte [] ba = bao.toByteArray();
ba1= Base64.encode(ba, Base64.DEFAULT).toString();
For decoding:
byte [] encodeByte=Base64.decode(model.getmImage().toString(), Base64.DEFAULT);
System.out.println("15102015 encodeByte:" + encodeByte.toString());
Bitmap bitmap;
try{
bitmap=BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
imgImage.setImageBitmap(bitmap);
}catch(Exception e){
System.out.println("15102015 Exception e:" + e.toString());
}
where model.getmImage().toString() has the Base64 string value.
Please help me as I am behind this isssue for past few days.I will definitely verify your answer .
Thanks in advance....

Bitmap - compare contact picture with picture on sd card

I want to check, if the current user picture of a contact is the same as the one on the sd card...
I set the user picture like following:
byte[] photo = ImageFunctions.convertImageToByteArray(bitmap);
ContentValues values = new ContentValues();
....
values.put(ContactsContract.CommonDataKinds.Photo.PHOTO, photo);
...
And I read the image like following:
InputStream inputStream = ContactsContract.Contacts.openContactPhotoInputStream(
contentResolver,
ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, mId),
fullsize);
if (inputStream != null)
return BitmapFactory.decodeStream(inputStream);
And my convert function is following:
public static byte[] convertImageToByteArray(Bitmap bitmap)
{
ByteArrayOutputStream streamy = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 100, streamy);
return streamy.toByteArray();
}
And I use a md5 hash on the byte array of the bitmap to find changes... Actually, the images are not exactly the same.
What can I do, so that I compare the hash codes? It seems, like compression or whatever is not exactly the same, so the md5 hash check fails...

Image Uri to File

I've got an Image Uri, retrieved using the following:
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
This works just amazing for Intents that require an Image URI, etc (so I know for sure the URI is valid).
But now I want to save this Image URI to a file on the SDCARD. This is more difficult because the URI does not really point at a file on the SDCARD or the app.
Will I have to create a bitmap from the URI first, and then save the Bitmap on the SDCARD or is there a quicker way (preferable one that does not require the conversion to a bitmap first).
(I've had a look at this answer, but it returns file not found - https://stackoverflow.com/a/13133974/1683141)
The problem is that the Uri you've been given by Images.Media.insertImage() isn't to an image file, per se. It is to a database entry in the Gallery. So what you need to do is read the data from that Uri and write it out to a new file in the external storage using this answer https://stackoverflow.com/a/8664605/772095
This doesn't require creating a Bitmap, just duplicating the data linked to the Uri into a new file.
You can get the data using an InputStream using code like:
InputStream in = getContentResolver().openInputStream(imgUri);
Update
This is completely untested code, but you should be able to do something like this:
Uri imgUri = getImageUri(this, bitmap); // I'll assume this is a Context and bitmap is a Bitmap
final int chunkSize = 1024; // We'll read in one kB at a time
byte[] imageData = new byte[chunkSize];
try {
InputStream in = getContentResolver().openInputStream(imgUri);
OutputStream out = new FileOutputStream(file); // I'm assuming you already have the File object for where you're writing to
int bytesRead;
while ((bytesRead = in.read(imageData)) > 0) {
out.write(Arrays.copyOfRange(imageData, 0, Math.max(0, bytesRead)));
}
} catch (Exception ex) {
Log.e("Something went wrong.", ex);
} finally {
in.close();
out.close();
}

How to display image from blob data in android sqlite?

I have been trying to store image form android sdcard to the sqlite database. And it worked fine. The image is getting stored into the database as blob. This is the rough code I have been using for that.
Bitmap bitmap = BitmapFactory.decodeFile(filePath);
imgView.setImageBitmap(bitmap);
int size = bitmap.getWidth() * bitmap.getHeight();
ByteArrayOutputStream out = new ByteArrayOutputStream(size);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
try {
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();}
byte[] x = out.toByteArray();
In the database side, the code is like this
ContentValues values = new ContentValues();
byte[] bytes = null;
bytes = img_bytes.getBytes();
values.put("IMAGE", bytes);
And for displaying I have used the code as below.
ImageView image = new ImageView(this);
byte[] img_bytes = result.get("IMAGE").getBytes();
Bitmap bMap = BitmapFactory.decodeByteArray(img_bytes, 0, img_bytes.length);
image.setImageBitmap(bMap);
When I printed the string value of the byate array, it was getting like [B#44da2db0. But the byte array is not getting displayed into image.
Somebody please help me with this.
Thanks
I have found a solution. Thanks to all.
I have used base64 encoding method.
ie; For displaying the image, I have been using a hash map to get the result first of all from the database table.
So before saving into the map, I have encoded the bytes to string using base 64 method.
Then On the Activity side for displaying the image, I have decoded back the string using base 64 again and then converted to bytes and the image got displayed.

Categories

Resources