How to save a photo in android database as a blob - 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;
}
}

Related

Unable to retrieve image from SQLite. SKImageDecoder::Factory returned null

Currently I'm developing an app which involves capture, save and retrieve image from SQLite. I managed to capture and save image into SQLite. However, I cannot retrieve the image back. I have converted the image into byte array before saved it inside SQLite. This is my coding:
Database.java
public String displayImageBendaOne(String rowId){
SQLiteDatabase db=helper.getReadableDatabase();
Cursor cursor = db.query(true, BacaHelper.TABLE_NAME_BENDA, new String[] {BacaHelper.UID,
BacaHelper.BENDA, BacaHelper.BENDA_IMAGE, BacaHelper.BENDA_ID}, BacaHelper.BENDA_ID + "==" + rowId, null,
null, null, null, null);
StringBuffer buffer= new StringBuffer();
if (cursor.moveToFirst()) {
{
//byte[] bImageOne=cursor.getBlob(cursor.getColumnIndex(BacaHelper.BENDA_IMAGE));
byte[] bImageOne = cursor.getBlob(1);
buffer.append(bImageOne);
}
}
db.close();
return buffer.toString();
}
Baca.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.benda_read);
bacaHelper= new BacaDatabaseAdapter(this);
bIOne = (ImageView) findViewById(R.id.imageOne);
passVar = getIntent().getStringExtra(benda.ID_EXTRA);
String bendaIOne = bacaHelper.displayImageBendaOne(passVar);
Log.e("Byte[] ", bendaIOne);
ByteArrayInputStream imageStream = new ByteArrayInputStream(bendaIOne.getBytes());
theImage = BitmapFactory.decodeStream(imageStream);
imageStream.reset();
bIOne.setImageBitmap(theImage);
}
There are no syntax error at the moment but when I run my apps, the image does not appear. In LogCat showed SKImageDecoder:: Factory returned null. What is the meaning of this statement? There is something about above coding I cannot figure out. I have decided to convert from image to byte array to string to byte array to image. Which is a long process because I don't know how to directly retrieve value of byte array from database. Can anyone point out what I should do? Thanks in advanced.
Updated.
This is the class where I converted image into byte array and save inside database.
protected void onActivityResult (int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK)
return;
switch (requestCode) {
case CAMERA_REQUEST:
Bundle extras = data.getExtras();
String bendaTambah=benda.getText().toString();
if (extras != null) {
Bitmap yourImage = extras.getParcelable("data");
// convert bitmap to byte
ByteArrayOutputStream stream = new ByteArrayOutputStream();
yourImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte imageInByte[] = stream.toByteArray();
Log.e("output before conversion", imageInByte.toString());
// Inserting Contacts
Log.d("Insert: ", "Inserting ..");
bacaHelper.addContact(new BendaCall(bendaTambah, imageInByte, passVar));
Intent i = new Intent(benda.this,
benda.class);
startActivity(i);
finish();
}
break;
case PICK_FROM_GALLERY:
Bundle extras2 = data.getExtras();
String bendaTambah2=benda.getText().toString();
if (extras2 != null) {
Bitmap yourImage = extras2.getParcelable("data");
// convert bitmap to byte
ByteArrayOutputStream stream = new ByteArrayOutputStream();
yourImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte imageInByte[] = stream.toByteArray();
Log.e("output before conversion", imageInByte.toString());
// Inserting Contacts
Log.d("Insert: ", "Inserting ..");
bacaHelper.addContact(new BendaCall(bendaTambah2, imageInByte, passVar));
Intent i = new Intent(benda.this,
benda.class);
startActivity(i);
finish();
} else{
Message.message(this, "Tidak berjaya menambah gambar ");
}
break;
}
}
Try out this code
Modify your displayImageBendaOne method like
public Bitmap displayImageBendaOne(String rowId){
SQLiteDatabase db=helper.getReadableDatabase();
Cursor cursor = db.query(true, BacaHelper.TABLE_NAME_BENDA, new String[] {BacaHelper.UID,
BacaHelper.BENDA, BacaHelper.BENDA_IMAGE, BacaHelper.BENDA_ID}, BacaHelper.BENDA_ID + "==" + rowId, null,
null, null, null, null);
//StringBuffer buffer= new StringBuffer();
Bitmap bm=null;
if (cursor.moveToFirst()) {
{
//byte[] bImageOne=cursor.getBlob(cursor.getColumnIndex(BacaHelper.BENDA_IMAGE));
byte[] bImageOne = cursor.getBlob(1);
bm=BitmapFactory.decodeByteArray(bImageOne , 0, bImageOne.length);
// buffer.append(bImageOne);
}
}
db.close();
return bm;
}
In your onCreate method instead of
String bendaIOne = bacaHelper.displayImageBendaOne(passVar);
Log.e("Byte[] ", bendaIOne);
ByteArrayInputStream imageStream = new ByteArrayInputStream(bendaIOne.getBytes());
theImage = BitmapFactory.decodeStream(imageStream);
imageStream.reset();
bIOne.setImageBitmap(theImage);
Use this
Bitmap image=bacaHelper.displayImageBendaOne(passVar);
bIOne.setImageBitmap(image);
code to open camera
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
{
// String s=sharedPreferences.getString("source", "");
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
File file = new File(Environment.getExternalStorageDirectory()+File.separator + "image.jpg");
path1=Environment.getExternalStorageDirectory()+File.separator + "image.jpg";
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
startActivityForResult(intent, CAPTURE_IMAGE_FULLSIZE_ACTIVITY_REQUEST_CODE);
}
else
{
ContextWrapper contextWrapper = new ContextWrapper(AddItem.this);
File file =new File(contextWrapper.getDir("Inventory", Context.MODE_PRIVATE)+File.separator + "image.jpg");
path1=contextWrapper.getDir("Inventory", Context.MODE_PRIVATE)+File.separator + "image.jpg";
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
// File file = new File(Environment.getExternalStorageDirectory()+File.separator + "image.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
startActivityForResult(intent, CAPTURE_IMAGE_FULLSIZE_ACTIVITY_REQUEST_CODE);
}
code to get image from camera
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == AddItem.this.RESULT_OK)
{
if (requestCode == CAPTURE_IMAGE_FULLSIZE_ACTIVITY_REQUEST_CODE)
{//if image is captured from camera
// count++;
Bitmap bitmap;
String fname;
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
{
File file = new File(Environment.getExternalStorageDirectory()+File.separator + "image.jpg");
BitmapFactory.Options btmapOptions = new BitmapFactory.Options();
Bitmap bm = BitmapFactory.decodeFile(file.getAbsolutePath(),btmapOptions);
bitmap = decodeSampledBitmapFromFile(file.getAbsolutePath(), 500, 500);
fname="image.jpg";
try {
ExifInterface exif = new ExifInterface(file.getAbsolutePath());
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
int rotate = 0;
switch(orientation) {
case ExifInterface.ORIENTATION_ROTATE_270:
rotate-=90;break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotate-=90;break;
case ExifInterface.ORIENTATION_ROTATE_90:
rotate-=90;break;
}
// Log.d("Fragment", "EXIF info for file " + name1 + ": " + rotate);
} catch (IOException e) {
// Log.d("Fragment", "Could not get EXIF info for file " + name1 + ": " + e);
}
// viewImage.setImageBitmap(bitmap);
}
else
{
ContextWrapper contextWrapper = new ContextWrapper(AddItem.this);
File file =new File(contextWrapper.getDir("Inventory", Context.MODE_PRIVATE)+File.separator + "image.jpg");
// File file = new File(Environment.getExternalStorageDirectory()+File.separator + "image.jpg");
BitmapFactory.Options btmapOptions = new BitmapFactory.Options();
Bitmap bm = BitmapFactory.decodeFile(file.getAbsolutePath(),btmapOptions);
bitmap = decodeSampledBitmapFromFile(file.getAbsolutePath(), 500, 500);
fname="image.jpg";
// viewImage.setImageBitmap(bitmap);
}
//add to database
addlabel.setVisibility(View.VISIBLE);
Inventory inv= new Inventory(bitmap,fname,name,date);
DbHelper.open();
long count=DbHelper.insertInvDetails(inv);
//Toast.makeText(AddItem.this, count+"", Toast.LENGTH_LONG).show();
DbHelper.close();
}
}
}
code to obtain a full size image
public static Bitmap decodeSampledBitmapFromFile(String path, int reqWidth, int reqHeight)
{ // BEST QUALITY MATCH
//First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize, Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
options.inPreferredConfig = Bitmap.Config.RGB_565;
int inSampleSize = 1;
if (height > reqHeight)
{
inSampleSize = Math.round((float)height / (float)reqHeight);
}
int expectedWidth = width / inSampleSize;
if (expectedWidth > reqWidth)
{
//if(Math.round((float)width / (float)reqWidth) > inSampleSize) // If bigger SampSize..
inSampleSize = Math.round((float)width / (float)reqWidth);
}
options.inSampleSize = inSampleSize;
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(path, options);
}
Utility class use to converting image to byte array and decoding it back to bimap
import java.io.ByteArrayOutputStream;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.util.Log;
public class Utility {
// convert from bitmap to byte array
public static byte[] getBytes(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0, stream);
return stream.toByteArray();
}
// convert from byte array to bitmap
public static Bitmap getPhoto(byte[] image) {
Log.i("", image.toString());
return BitmapFactory.decodeByteArray(image, 0, image.length);
}
}
Database code to insert data
public long insertInvDetails(Inventory invent) {
mDb = mDbHelper.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(EMP_PHOTO, Utility.getBytes(invent.getBitmap()));
cv.put(EMP_NAME, invent.getName());
cv.put(EMP_PNAME, invent.getPersonName());
cv.put(EMP_Date, invent.getDate());
cv.put("IsDeleted", 0);
long count=mDb.insert(INVENTORY_TABLE, null, cv);
return count;
}
UPDATE
code to retrieve data
public List<Inventory> getSelectedContacts() {
List<Inventory> invlist = new ArrayList<Inventory>();
// Select All Query
mDb = mDbHelper.getWritableDatabase();
Cursor cursor = mDb.query(true, INVENTORY_TABLE, new String[] {EMP_ID, EMP_PHOTO,
EMP_NAME, EMP_PNAME,EMP_Date }, "IsDeleted=1", null, null, null, null, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Inventory inv = new Inventory();
inv.setID(cursor.getInt(0));
byte[] blob = cursor.getBlob(cursor.getColumnIndex(EMP_PHOTO));
inv.setBitmap(Utility.getPhoto(blob));
inv.setName(cursor.getString(2));
inv.setPersonName(cursor.getString(3));
inv.setDate(cursor.getString(4));
// Adding contact to list
invlist.add(inv);
} while (cursor.moveToNext());
}
mDb.close();
// return contact list
return invlist;
}
Code to call getSelectedContactsand display image in linearlayout
List<Inventory> select_contacts = db.getSelectedContacts();
LinearLayout newll=new LinearLayout(MainPage.this);
newll.setOrientation(LinearLayout.VERTICAL);
for (Inventory cn : select_contacts) {
ImageView myImage = new ImageView(MainPage.this);
myImage.setImageBitmap(cn.getBitmap());
newll.addView(myImage);
}
//add newll to your parent view
Here is my inventory class for holding values
package com.graficali.inventorysystem;
import android.graphics.Bitmap;
public class Inventory {
private Bitmap bmp;
private String filename;
private String personname;
String created_at;
private int id;
public Inventory()
{
}
public Inventory(Bitmap b, String n, String pn, String created_at) {
bmp = b;
filename = n;
personname = pn;
this.created_at=created_at;
}
public Bitmap getBitmap() {
return bmp;
}
public String getName() {
return filename;
}
public String getDate() {
return this.created_at;
}
public int getID() {
return this.id;
}
public String getPersonName() {
return personname;
}
public void setBitmap(Bitmap bmp) {
this.bmp=bmp;
}
public void setName(String filename) {
this.filename=filename;
}
public void setID(int id) {
this.id=id;
}
public void setPersonName(String personname)
{
this.personname=personname;
}
public void setDate(String created_at) {
this.created_at = created_at;
}
}

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

The captured image from camera is not storing in full size

I know this question has been asked so many times in this forum. But still I couldn't get the solution.
Basically in my application, I am calling an inbuilt camera intent, capturing image and displaying a bitmap in imageview and storing it in sd card. Now the image what i get in my folder is of small size like a thumbnail.
My code is
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(Intent.createChooser(cameraIntent, "Select picture"), CAMERA_REQUEST);
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
try {
if (requestCode == CAMERA_REQUEST) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
if (photo != null) {
imageView.setImageBitmap(photo);
}
// Image name
final ContentResolver cr = getContentResolver();
final String[] p1 = new String[] { MediaStore.Images.ImageColumns._ID,
MediaStore.Images.ImageColumns.DATE_TAKEN };
Cursor c1 = cr.query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, p1, null,
null, p1[1] + " DESC");
if (c1.moveToFirst()) {
String uristringpic = "content://media/external/images/media/" + c1.getInt(0);
Uri newuri = Uri.parse(uristringpic);
String snapName = getRealPathFromURI(newuri);
Uri u = Uri.parse(snapName);
File f = new File("" + u);
String fileName = f.getName();
editTextPhoto.setText(fileName);
checkSelectedItem = true;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
photo.compress(CompressFormat.PNG, 0 /* ignored for PNG */, bos);
byte[] bitmapdata = bos.toByteArray();
// Storing Image in new folder
StoreByteImage(mContext, bitmapdata, 100, fileName);
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://" + Environment.getExternalStorageDirectory())));
// Delete the image from the Gallery
getContentResolver().delete(newuri, null, null);
}
c1.close();
}
} catch (NullPointerException e) {
System.out.println("Error in creating Image." + e);
} catch (Exception e) {
System.out.println("Error in creating Image." + e);
}
System.out.println("*** End of onActivityResult() ***");
}
public String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
public boolean StoreByteImage(Context pContext, byte[] pImageData,
int pQuality, String pExpName) {
String nameFile = pExpName;
// File mediaFile = null;
File sdImageMainDirectory = new File(
Environment.getExternalStorageDirectory() + "/pix/images");
FileOutputStream fileOutputStream = null;
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 0;
Bitmap myImage = BitmapFactory.decodeByteArray(pImageData, 0,
pImageData.length, options);
if (!sdImageMainDirectory.exists()) {
sdImageMainDirectory.mkdirs();
}
sdImageMainDirectory = new File(sdImageMainDirectory, nameFile);
sdImageMainDirectory.createNewFile();
fileOutputStream = new FileOutputStream(
sdImageMainDirectory.toString());
BufferedOutputStream bos = new BufferedOutputStream(
fileOutputStream);
myImage.compress(CompressFormat.JPEG, pQuality, bos);
bos.flush();
bos.close();
} catch (FileNotFoundException e) {
Toast.makeText(pContext, e.getMessage(), Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (IOException e) {
Toast.makeText(pContext, e.getMessage(), Toast.LENGTH_LONG).show();
e.printStackTrace();
}
and ImageView in main.xml is
<ImageView
android:id="#+id/test_image"
android:src="#drawable/gray_pic"
android:layout_width="180dp"
android:layout_height="140dp"
android:layout_below="#id/edit2"
android:layout_toRightOf="#id/edit3"
android:layout_alignParentRight="true"
android:layout_marginTop="7dp"
android:layout_marginBottom="5dp"
android:layout_marginLeft="7dp"
android:layout_marginRight="7dp"
/>
With this code i get an Imageview and the image stores in my folder with small size.
If I add intent.putExtra then neither image captured displays in ImageView nor image creates in new folder.
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
String path = Environment.getExternalStorageDirectory().getAbsolutePath();
path += "/myFolder/myPicture.jpg";
File file = new File(path);
Uri outputFileUri = Uri.fromFile(file);
cameraIntent.putExtra("output", outputFileUri);
startActivityForResult(Intent.createChooser(cameraIntent, "Select Picture"), CAMERA_REQUEST);
}
Don't know where I am struck..
Any help on this would be appreciated.
Use Camera intent as:
Intent photoPickerIntent= new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
photoPickerIntent.putExtra(MediaStore.EXTRA_OUTPUT, getTempFile());
photoPickerIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
photoPickerIntent.putExtra("return-data", true);
startActivityForResult(Intent.createChooser(photoPickerIntent,"Select Picture"),TAKE_PICTURE);
//getTempFile()
private Uri getTempFile() {
// if (isSDCARDMounted()) {
File root = new File(Environment.getExternalStorageDirectory(), "My Equip");
if (!root.exists()) {
root.mkdirs();
}
Log.d("filename",filename);
File file = new File(root,filename+".jpeg" );
muri = Uri.fromFile(file);
photopath=muri.getPath();
Item1.photopaths=muri.getPath();
Log.e("getpath",muri.getPath());
return muri;
// } else {
// return null;
}
//}
private boolean isSDCARDMounted(){
String status = Environment.getExternalStorageState();
if (status.equals(Environment.MEDIA_MOUNTED))
return true;
else
return false;
}
And Check in your Folder, click on thumbnail it will show actual image

Taking a pic with tha camera but the image size is 0 KB

I have made a demo to make a pic with the cam, save the image, and then, in other activity show the last pic made it. This is OK with the emulator, but when I install my demo in a real phone, I can make the pic, but the file size saved is O KB.
//This is the method where I make the photo
private boolean makePhoto(){
try{
ImageCaptureCallback camDemo = null;
SimpleDateFormat timeStampFormat = new SimpleDateFormat("yyyyMMddHHmmssSS");
String filenameTimeStamp = timeStampFormat.format(new Date());
ContentValues values = new ContentValues();
values.put(MediaColumns.TITLE, String.format("%s.jpg", filenameTimeStamp));
values.put(ImageColumns.DESCRIPTION, "Imagen desde Android Emulator");
Uri uri = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, values);
Log.d("titulo: ", values.get(MediaColumns.TITLE).toString());
camDemo = new ImageCaptureCallback(getContentResolver().openOutputStream(uri));
this.camera.takePicture(this.mShutterCallback, this.mPictureCallback, camDemo);
Log.d("makePhoto", "Foto hecha");
return true;
}catch(Exception ex){
ex.printStackTrace();
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, ex.toString(), duration);
toast.show();
}
return false;
}
//This is the object where the pic taken is saved
public class ImageCaptureCallback implements PictureCallback {
private OutputStream fileoutputStream;
public ImageCaptureCallback(OutputStream fileoutputStream){
this.fileoutputStream = fileoutputStream;
}
public void onPictureTaken(byte[] data, Camera camera){
try{
BitmapFactory.Options options=new BitmapFactory.Options();
options.inSampleSize = 1;
Bitmap myImage = BitmapFactory.decodeByteArray(data, 0, data.length,options);
BufferedOutputStream bos = new BufferedOutputStream(this.fileoutputStream);
myImage.compress(CompressFormat.JPEG, 75, bos);
bos.flush();
bos.close();
}catch (Exception ex){
ex.printStackTrace();
}
}
}
What happened?
I am sending you the code for taking picture and take the picture into your application.
First of all add the below intend:
File imageFile = new File(imageFilePath);
Uri imageFileUri = Uri.fromFile(imageFile);
Intent i = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
i.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageFileUri);
startActivityForResult(i, CAMERA_PIC_REQUEST);
And then add the below startActivityForResule in your code
protected void onActivityResult(int requestCode, int resultCode,
Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode)
{
case SELECT_PICTURE:
Uri selectedImage = imageReturnedIntent.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
// file path of selected image
String filePath = cursor.getString(columnIndex);
cursor.close();
Bitmap yourSelectedImage = BitmapFactory.decodeFile(filePath);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
yourSelectedImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
encode = Base64.encodeBytes(byteArray);
try {
byte[] decode = Base64.decode(encode);
Bitmap bmp = BitmapFactory.decodeByteArray(decode, 0,
decode.length);
imgview_photo.setImageBitmap(bmp);
btn_getphoto.setVisibility(View.INVISIBLE);
btn_cancel.setVisibility(View.VISIBLE);
btn_upload.setVisibility(View.VISIBLE);
}
catch (IOException e) {
e.printStackTrace();
}
break;
case CAMERA_PIC_REQUEST:
Bitmap bmp = BitmapFactory.decodeFile(imageFilePath);
int width = bmp.getWidth();
int height = bmp.getHeight();
float scaleWidth = ((float) 300) / width;
float scaleHeight = ((float) 300) / height;
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
Bitmap resizedBitmap = Bitmap.createBitmap(bmp, 0, 0, width,
height, matrix, true);
ByteArrayOutputStream baostream = new ByteArrayOutputStream();
resizedBitmap.compress(Bitmap.CompressFormat.PNG, 100, baostream);
byte[] byteArrays = baostream.toByteArray();
encode = Base64.encodeBytes(byteArrays);
try {
byte[] decode = Base64.decode(encode);
Bitmap bitmp = BitmapFactory.decodeByteArray(decode, 0,
decode.length);
imgview_photo.setImageBitmap(bitmp);
btn_getphoto.setVisibility(View.INVISIBLE);
btn_cancel.setVisibility(View.VISIBLE);
btn_upload.setVisibility(View.VISIBLE);
} catch (IOException e) {
e.printStackTrace();
}
}
}

Android:Problem in getting image from specified path

I have an app from which i have to capture an image from camera activity and using content resolver i have insert that image to media.EXTERNAL_CONTENT_URI and i have getString() the path of that image and passed it to bundle in other activity.
from there,I have get that path and put it in Bitmap bitmap = BitmapFactory.decodeFile(filepath);
but it's showing FILENOTFOUNDEXCEPTION and NULLPOINTEREXCEPTION.How to resolve that?
so I am also trying another approach such that the image i got in first activity should first be set to a file and then i decode that file easily?
please suggest me the way to do that.
UPDATES-->
CODE: `//pass image path to other activity`
case PICK_FROM_CAMERA : if (resultCode == RESULT_OK)
{
ContentValues values = new ContentValues();
values.put(Images.Media.TITLE, "title");
values.put(Images.Media.BUCKET_ID, "test");
values.put(Images.Media.DESCRIPTION, "test Image taken");
values.put(Images.Media.MIME_TYPE,"image/jpeg");
Uri uri = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, values);
filepath = uri.getPath();
Bitmap photo = (Bitmap) data.getExtras().get("data");
//((ImageView)findViewById(R.id.selectedimage)).setImageBitmap(photo);
OutputStream outstream;
try
{
outstream = getContentResolver().openOutputStream(uri);
photo.compress(Bitmap.CompressFormat.JPEG,100,outstream);
outstream.close();
}
catch (FileNotFoundException e) {}
catch (IOException e) {}
Intent intent = new Intent(this.getApplicationContext(),AnimationActivity.class);
Bundle bundle = new Bundle();
bundle.putInt("flag", 0);
bundle.putString("filepath", filepath);
intent.putExtras(bundle);
startActivity(intent);
}
Code: //show that image
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView img = (ImageView)findViewById(R.id.background);
Bitmap border = BitmapFactory.decodeResource(getResources(),R.drawable.border1);
Bundle extra = getIntent().getExtras();
mfilepath = extra.getString("filepath");
int flag = extra.getInt("flag");
if(flag==1)
{
bgr= BitmapFactory.decodeFile(mfilepath);
}
if(flag==0)
{
bgr=BitmapFactory.decodeFile(mfilepath);
OutputStream outstream;
try
{
outstream = getContentResolver().openOutputStream(Uri.fromFile(new File(mfilepath)));
//bgr.compress(Bitmap.CompressFormat.JPEG,100,outstream);
outstream.close();
}
catch (FileNotFoundException e) {}
catch (IOException e) {}
}
bmOverlay = Bitmap.createBitmap(border.getWidth(),border.getHeight(),bgr.getConfig());
canvas = new Canvas(bmOverlay);
canvas.drawBitmap(bmOverlay, 0, 0, null);
canvas.drawBitmap(bgr, 0, 0, null);
canvas.drawBitmap(border,0,0, null);
canvas.save();
img.setImageBitmap(bmOverlay);
Try this simple method, I think it should solve your problem.
private void savePicture(String filename, Bitmap b, Context ctx) {
try {
FileOutputStream out;
out = ctx.openFileOutput(filename, Context.MODE_WORLD_READABLE);
b.compress(Bitmap.CompressFormat.JPEG, 40, out);
if (b.compress(Bitmap.CompressFormat.JPEG, 40, out) == true)
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Edit 1: Although I am not sure exactly what you are asking, I think you might be looking for this method:
private void takePicture() {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
File photo = new File(Environment.getExternalStorageDirectory(),
"Pic.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
imageUri = Uri.fromFile(photo);
startActivityForResult(intent, 0);
}
Use of FileOutputStream instead of OutputStream solved ma problem.
case PICK_FROM_CAMERA : if (resultCode == RESULT_OK)
{
ContentValues values = new ContentValues();
values.put(Images.Media.TITLE, "title");
values.put(Images.Media.BUCKET_ID, "test");
values.put(Images.Media.DESCRIPTION, "test Image taken");
values.put(Images.Media.MIME_TYPE,"image/jpeg");
Uri uri = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, values);
filepath = uri.getPath();
Bitmap photo = (Bitmap) data.getExtras().get("data");
try
{
FileOutputStream outstream; =new FileOutputStream(filepath);
photo.compress(Bitmap.CompressFormat.JPEG,100,outstream);
outstream.close();
}
catch (FileNotFoundException e) {}
catch (IOException e) {}
Intent intent = new Intent(this.getApplicationContext(),AnimationActivity.class);
Bundle bundle = new Bundle();
bundle.putInt("flag", 0);
bundle.putString("filepath", filepath);
intent.putExtras(bundle);
startActivity(intent);
}
Code: //show that image
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView img = (ImageView)findViewById(R.id.background);
Bitmap border = BitmapFactory.decodeResource(getResources(),R.drawable.border1);
Bundle extra = getIntent().getExtras();
mfilepath = extra.getString("filepath");
bgr= BitmapFactory.decodeFile(mfilepath);
bmOverlay = Bitmap.createBitmap(border.getWidth(),border.getHeight(),bgr.getConfig());
canvas = new Canvas(bmOverlay);
canvas.drawBitmap(bmOverlay, 0, 0, null);
canvas.drawBitmap(bgr, 0, 0, null);
canvas.drawBitmap(border,0,0, null);
canvas.save();
img.setImageBitmap(bmOverlay);

Categories

Resources