Showing posts with label Camera. Show all posts
Showing posts with label Camera. Show all posts

Tuesday, March 8, 2016

Select Image from Gallery or Capture through Camera and Store it in shared preferences and use it inside application in Android

First you need to convert image to Base64 String representation and then store it in shared 
preference as follows :

Bitmap realImage = BitmapFactory.decodeStream(stream);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
realImage.compress(Bitmap.CompressFormat.JPEG, 100, baos);   
byte[] b = baos.toByteArray(); 

String encodedImage = Base64.encodeToString(b, Base64.DEFAULT);

textEncode.setText(encodedImage);

SharedPreferences shre = PreferenceManager.getDefaultSharedPreferences(this);

Editor edit=shre.edit();
edit.putString("image_data",encodedImage);
edit.commit();

and you can retrieve the image using Bitmap as :


SharedPreferences shre = PreferenceManager.getDefaultSharedPreferences(this);
String previouslyEncodedImage = shre.getString("image_data", "");

if( !previouslyEncodedImage.equalsIgnoreCase("") ){

    byte[] b = Base64.decode(previouslyEncodedImage, Base64.DEFAULT);
    Bitmap bitmap = BitmapFactory.decodeByteArray(b, 0, b.length);
    imageView.setImageBitmap(bitmap);
}

if You are using capturing image with camera or picking up from galleryin both way you can use this methods as :

private static final int CAPTURE_IMAGE = 0;
private static final int SELECT_PICTURE = 1;

and then implement this method :


public void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == CAPTURE_IMAGE) {
        Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
        storeImage(thumbnail);
    } else if (requestCode == SELECT_PICTURE) {
        Uri mImageUri = data.getData();
        Bitmap thumbnail = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), mImageUri);
        storeImage(thumbnail);
    }
}

and store Image method is as follows :

private void storeImage(Bitmap thumbnail) {

    // Removing image saved earlier in shared prefernces
    shre = PreferenceManager.getDefaultSharedPreferences(getActivity());
    SharedPreferences.Editor edit=shre.edit();
    edit.remove("image_data");
    edit.commit();

    ByteArrayOutputStream bytes = new ByteArrayOutputStream();

    thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
    File destination = new File(Environment.getExternalStorageDirectory(),
            System.currentTimeMillis() + ".jpg");
    FileOutputStream fo;
    try {
        destination.createNewFile();
        fo = new FileOutputStream(destination);
        fo.write(bytes.toByteArray());
        fo.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    imageview.setImageBitmap(thumbnail);
    byte[] b = bytes.toByteArray();
    String encodedImage = Base64.encodeToString(b, Base64.DEFAULT);
    //saving image to shared preferences
    edit.putString("image_data",encodedImage);
    edit.commit();
}

Wednesday, March 2, 2016

Select Image From gallery or Capture from Camera and set as Profile Pic in Android


First of all Create a dialog to select whether you need to capture image from camera or pick from gallery as :


Code :


 private static Bitmap Image = null;
 private static Bitmap rotateImage = null;
 private static final int CAPTURE_IMAGE = 0;
 private static final int SELECT_PICTURE = 1;


 
 Dialog openDialog = new Dialog(getActivity());
 openDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
 openDialog.setContentView(R.layout.contact_add_builder_upload_pic_dialog);
 Window window = openDialog.getWindow();
 WindowManager.LayoutParams wlp = window.getAttributes();
 window.setGravity(Gravity.RIGHT |Gravity.TOP);
 openDialog.getWindow().getAttributes().verticalMargin =0.09F;
 openDialog.getWindow().getAttributes().horizontalMargin =0.09F;
 wlp.flags &=~WindowManager.LayoutParams.FLAG_DIM_BEHIND;
 window.setAttributes(wlp);
 openDialog.show();

 final TextView galleryImgTv = (TextView) openDialog.findViewById
         (R.id.gallery_image);

 final TextView cameraImgTv = (TextView) openDialog.findViewById
         (R.id.camera_image);

galleryImgTv.setOnClickListener(new View.OnClickListener()
 {
     @Override     public void onClick (View v){
     Intent pickPhoto = new Intent(Intent.ACTION_PICK,
             android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
     startActivityForResult(pickPhoto, SELECT_PICTURE);
     openDialog.dismiss();
     }
 });

 cameraImgTv.setOnClickListener(new View.OnClickListener()
 {
     @Override     public void onClick (View view){
     Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
     startActivityForResult(intent, CAPTURE_IMAGE);
     openDialog.dismiss();
     }
 });

 then override onActivityResult method as :

 @Override public void onActivityResult(int requestCode, int resultCode,
                              Intent data) {
     if (requestCode == CAPTURE_IMAGE) {
         onCaptureImageResult(data);
     } else if (requestCode == SELECT_PICTURE) {
         Uri mImageUri = data.getData();
         try {
             Image = MediaStore.Images.Media.getBitmap(getApplicationContext()
                     .getContentResolver(), mImageUri);
             if (getOrientation(getApplicationContext(), mImageUri) != 0) {
                 Matrix matrix = new Matrix();
                 matrix.postRotate(getOrientation(getActivity(), mImageUri));
                 if (rotateImage != null)
                     rotateImage.recycle();
                 rotateImage = Bitmap.createBitmap(Image, 0, 0,
                         Image.getWidth(), Image.getHeight(), matrix, true);
                 profile_pic.setImageBitmap(rotateImage);
             } else                 profile_pic.setImageBitmap(Image);
         } catch (FileNotFoundException e) {
             e.printStackTrace();
         } catch (IOException e) {
             e.printStackTrace();
         }
     }
 }

 then

 public static int getOrientation(Context context, Uri photoUri) {
     Cursor cursor = context.getContentResolver().query(photoUri,
             new String[]{MediaStore.Images.ImageColumns.ORIENTATION},
             null, null, null);
     if (cursor.getCount() != 1) {
         return -1;
     }
     cursor.moveToFirst();
     return cursor.getInt(0);
 }

 and

 public void onCaptureImageResult(Intent data) {
     Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
     ByteArrayOutputStream bytes = new ByteArrayOutputStream();
     thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
     File destination = new File(Environment.getExternalStorageDirectory(),
             System.currentTimeMillis() + ".jpg");
     FileOutputStream fo;
     try {
         destination.createNewFile();
         fo = new FileOutputStream(destination);
         fo.write(bytes.toByteArray());
         fo.close();
     } catch (FileNotFoundException e) {
         e.printStackTrace();
     } catch (IOException e) {
         e.printStackTrace();
     }
     profile_pic.setImageBitmap(thumbnail);
 }