unable to add image to imageview from camera capture - android

I am developing one application in which I have to capture image from camera and add to ImageView. Here I have a problem while showing image on ImageView. If I click save button the image is not showing on ImageView for the first time,but for second time it is showing,please solve my problem, I am unable to find solution for this.
Code Snippet:
fromCamera.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
/* Log.e("OPEN", "CAMERA");
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment
.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, RESUL_CameraT_LOAD_IMAGE);*/
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
File file = new File(Environment.getExternalStorageDirectory()+File.separator +
"fav.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
startActivityForResult(intent, RESUL_CameraT_LOAD_IMAGE);
uploadalertDialog.dismiss();
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Uri selectedImage = null;
Bitmap bitmap;
try {
switch (requestCode) {
case RESUL_CameraT_LOAD_IMAGE:
if (resultCode == Activity.RESULT_OK) {
// imageView.setImageResource(android.R.color.transparent);
Log.e("GET IMAGE", "PATH");
try{
File file = new File(Environment.getExternalStorageDirectory()+File.separator
+ "fav.jpg");
bitmap = decodeSampledBitmapFromFile(file.getAbsolutePath(), 300, 300);
uloadImgView.setImageBitmap(bitmap);
ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 90,
byteArray);
byte[] byte_arr = byteArray.toByteArray();
base64 = Base64.encodeToString(byte_arr, Base64.DEFAULT);
}
catch(Exception e){
e.printStackTrace();
}
}
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);
}

First of all add the following permission in you app's manifest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Then check the following code which I used in my application to set s user's profile pic.
// on click listener for the camera trigger
image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent cameraintent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraintent, 101);
}
});
//onActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Uri selectedImage = null;
Bitmap bitmap;
try {
switch (requestCode) {
case 101:
if (resultCode == Activity.RESULT_OK) {
if (null != data) {
selectedImage = data.getData(); // the uri of the image
// taken
bitmap = decodeSampledBitmapFromUri(this,
selectedImage, 100, 100);
image.setImageBitmap(bitmap);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
super.onActivityResult(requestCode, resultCode, data);
}
//Bitmap sampling
public static Bitmap decodeSampledBitmapFromUri(Activity callingActivity,
Uri uri, int reqWidth, int reqHeight) {
try {
InputStream input = callingActivity.getContentResolver()
.openInputStream(uri);
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
options.inSampleSize = 2; // make the bitmap size half of the
// original one
BitmapFactory.decodeStream(input, null, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth,
reqHeight);
input.close();
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
input = callingActivity.getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(input, null, options);
return bitmap;
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (IOException e) {// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
//calculate sample size
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and
// keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}

Related

How to have base fragment code which takes picture from gallery and camera

I need to take pictures from camera and gallery and do certain some functionality,This needs to be done from two places(fragments),
How can i write common code.Is it possible,Like a base class?
private static final int PICK_IMAGE = 1;
int REQUEST_CAMERA = 0;
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.addProductImage:
selectImage();
break;
}
}
private void selectImage() {
final CharSequence[] items = {"Take Photo", "Choose from Library", "Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(this.getActivity());
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Take Photo")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "image.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
startActivityForResult(intent, REQUEST_CAMERA);
} else if (items[item].equals("Choose from Library")) {
selectImageFromGallery();
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == getActivity().RESULT_OK && requestCode == 1 && null != data) {
decodeUri(data.getData());
} else if (resultCode == getActivity().RESULT_OK && requestCode == REQUEST_CAMERA) {
// File file = new File(Environment.getExternalStorageDirectory() + File.separator + "image.jpg");
captureImage();
}
}
This Method is to capture image from Camera
private void captureImage() {
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "image.jpg");
bitmap = decodeSampledBitmapFromFile(file.getAbsolutePath(), 500, 250);
// set the bitmap here to image view
image.setImageBitmap(bitmap);
}
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;
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(path, options);
}
This method is to select image from Galary
public void selectImageFromGallery() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);
}
public void decodeUri(Uri uri) {
ParcelFileDescriptor parcelFD = null;
try {
parcelFD = getActivity().getContentResolver().openFileDescriptor(uri, "r");
FileDescriptor imageSource = parcelFD.getFileDescriptor();
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFileDescriptor(imageSource, null, o);
// the new size we want to scale to
final int REQUIRED_SIZE = 1024;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE) {
break;
}
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
bitmap = BitmapFactory.decodeFileDescriptor(imageSource, null, o2);
// set the bitmap here to image view
image.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
Utility.showToat(mContext, " File Not Found Exception ");
} finally {
if (parcelFD != null)
try {
parcelFD.close();
} catch (IOException e) {
// ignored
}
}
}

Android Imageview FITXY Image shrinking issue

`Hi All, I would like to pick an image from my phone gallery and show it as a background of a imageview.I am able to show it and even I am able to make the image fit whole screen via(FITXY property of imageview).
The issue is image actually shrinks , so I tried Fitcenter and adjustviewbounds property etc and all other properties but no luck , with this properties image fits center and I can see some gaps in(width and height).
Could any one help me on how to fix this issue.
Here is my full code and screenshots for references.
<FrameLayout
android:id="#+id/fm"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:background="#70b29c"
xmlns:android="http://schemas.android.com/apk/res/android">
<ImageView
android:id="#+id/set"
android:contentDescription="#string/hello_world"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:adjustViewBounds="true"/>
Here is my java code:
public class MainActivity extends Activity {
private static int RESULT_LOAD_IMAGE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sc = (LinearLayout) findViewById(R.id.home);
Button wal = (Button) findViewById(R.id.setwall);
wal.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// check if the request code is same as what is passed here it is 2
if (requestCode == RESULT_LOAD_IMAGE && resultCode ==RESULT_OK && null != data) {
Uri picUri = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(picUri,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
filePath = cursor.getString(columnIndex);
cursor.close();
bitmapView = (ImageView) findViewById(R.id.set);
bitmapView.setImageBitmap(ExifUtils.rotateBitmap(filePath, decodeSampledBitmap(new File(filePath), 400, 800)));
bitmapView.setScaleType(ImageView.ScaleType.FIT_XY);
SharedPreferences shre = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
SharedPreferences.Editor edit = shre.edit();
edit.putString("profilePic", filePath);
edit.commit();
}
}
public Bitmap decodeSampledBitmap(File res, int reqWidth, int reqHeight) {
if (res != null) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
try {
FileInputStream stream2 = new FileInputStream(res);
BitmapFactory.decodeStream(stream2, null, options);
stream2.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// Calculate inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
o2.inJustDecodeBounds = false;
FileInputStream stream = null;
try {
stream = new FileInputStream(res);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap bitmap = BitmapFactory.decodeStream(stream, null, o2);
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
} else
return null;
}
public int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
}
Link for the screenshot here
Using FITXY will fit your image to the imageView regardless of the resolution or aspect ratio of image which will result in inappropriate display of image...
If you want your image to be displayed on the whole screen its better to use CENTER or CENTERCROP which will crop the selected image but set it in image's aspect ratio and will fully cover your view....

Load large Bitmap efficiently for dynamic image pick from gallery?

I want to load large Bitmap image in the Imageview.I am follow the code from Loading Large Bitmaps Efficiently .It's shown for single imageView.But I want to pick images from gallery for dynamic ImageView.I try to get the id of the picked Image and set decodeSampledBitmapFromResouce.It's set the Empty in the ImageView.Please help me to solve the Issue.Any help I'm very appreciated.Please see my code Below.
Button loadImg;
ImageView myImageView;
InputStream imageStream;
Bitmap productIndex = null;
private static int RESULT_LOAD_IMAGE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loadImg = (Button)findViewById(R.id.btnPickImage);
myImageView = (ImageView) findViewById(R.id.myImgView);
loadImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent,RESULT_LOAD_IMAGE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
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();
myImageView = (ImageView) findViewById(R.id.myImgView);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(picturePath, options);
int imageHeight = options.outHeight;
int imageWidth = options.outWidth;
String imageType = options.outMimeType;
// here I set the bitmap to ImageView but the Image is not shown
int picId = getResources().getIdentifier(picturePath, "drawable", getApplicationContext().getPackageName());
myImageView.setImageBitmap(decodeSampledBitmapFromResource(getResources(),picId,100,100));
}
}
public static int calculateInSampleSize(BitmapFactory.Options options,int reqWidth,int reqHeight) {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
while ((halfWidth / inSampleSize) > reqWidth && (halfHeight / inSampleSize) > reqHeight) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
public static Bitmap decodeSampledBitmapFromResource(Resources res,int resId,int reqWidth,int reqHeight) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res,resId,options);
/* Calculate inSampleSize */
options.inSampleSize = calculateInSampleSize(options,reqWidth,reqHeight);
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res,resId,options);
}
Try this.
public static Bitmap decodeSampledBitmapFromFile(File f, int reqWidth, int reqHeight) { // BEST QUALITY MATCH
String path = f.getAbsolutePath();
// 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 background
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) {
inSampleSize = Math.round((float) width / (float) reqWidth);
}
options.inSampleSize = inSampleSize;
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
// Correct rotation
ExifInterface exif = null;
try {
exif = new ExifInterface(f.getPath());
} catch (IOException e) {
e.printStackTrace();
}
int rotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
int rotationInDegrees = exifToDegrees(rotation);
Matrix matrix = new Matrix();
if (rotation != 0f) {
matrix.preRotate(rotationInDegrees);
}
Bitmap output = BitmapFactory.decodeFile(path, options);
if (output != null) {
return Bitmap.createBitmap(output, 0, 0, output.getWidth(), output.getHeight(), matrix, false);
} else {
return null;
}
}
public static int exifToDegrees(int exifOrientation) {
if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_90) {
return 90;
} else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_180) {
return 180;
} else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_270) {
return 270;
}
return 0;
}

Android: How do i display this image into a bitmap?

What i'm doing/trying to do, is.
1. Take a photo
2. Save it
3. Load/display it into a Bitmap
Opening the Built in camera application:
public void openCamera() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = new File(Environment.getExternalStorageDirectory()+ File.separator + "image.jpg");
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
onActivityResult:
protected void onActivityResult(int requestCode, int resultCode, Intent data){
//Check that request code matches ours:
if (requestCode == REQUEST_IMAGE_CAPTURE){
//Get our saved file into a bitmap object:
File file = new File(Environment.getExternalStorageDirectory()+File.separator + "image.jpg");
Bitmap image = decodeSampledBitmapFromFile(file.getAbsolutePath(), 1000, 700);
}
}
decodeSamoleBitmapFromFile:
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);
}
I was hoping for it to load it into a bitmap. If anyone could point me in the right direction that would be very helpful!
In order to display a Bitmap, you'll have to use an ImageView. Once you have both the bitmap and the reference to your ImageView, call ImageView.setImageBitmap(Bitmap) to display your bitmap.

Android Camera Bitmap Issue

Hello I am having an issue when using the camera function in my android application. I am able to take a picture using the camera utility, however when returned back, the bitmap image is blank but formatted to the size of the picture taken. Am I missing something, to make the image show? Should I not be using imageview? Thanks! -T
private Uri capturedImageUri;
ImageView picture;
Button snapButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camera_observation);
picture = (ImageView) findViewById(R.id.imageView);
snapButton = (Button) findViewById(R.id.picButton);
snapButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
open();
}
});
}
public void open (){
File file = new File(Environment.getExternalStorageDirectory(), ("test"+".jpg"));
if(!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
file.delete();
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
capturedImageUri = Uri.fromFile(file);
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
i.putExtra(MediaStore.EXTRA_OUTPUT, capturedImageUri);
startActivityForResult(i, 2);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
// super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 2) {
//Bitmap bitmap = (Bitmap) data.getExtras().get("data");
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), capturedImageUri);
picture.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
1) Call the camera intent
private void picPhoto() {
Intent pickIntent = new Intent();
if (Build.VERSION.SDK_INT < 19) {
pickIntent.setType("image/jpeg");
pickIntent.setAction(Intent.ACTION_GET_CONTENT);
} else {
pickIntent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
pickIntent.addCategory(Intent.CATEGORY_OPENABLE);
pickIntent.setType("image/jpeg");
}
Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, getFileDirectory());
takePhotoIntent.putExtra("android.intent.extras.CAMERA_FACING", 1);
String pickTitle = "Select or take a new Picture";
Intent chooserIntent = Intent.createChooser(pickIntent, pickTitle);
chooserIntent.putExtra
(
Intent.EXTRA_INITIAL_INTENTS,
new Intent[]{takePhotoIntent}
);
startActivityForResult(chooserIntent, PICK_IMAGE);
}
2) Method getFileDirectory()
private Uri getFileDirectory() {
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "MyImages");
imagesFolder.mkdirs();
File image = new File(imagesFolder, "MY_PROFILE_PIC.jpg");
return Uri.fromFile(image);
}
3) OnActivityResult
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
// If gallary intent is choosed this condition remain true
if (requestCode == PICK_IMAGE && data != null && data.getData() != null) {
Uri _uri = data.getData();
//User had pick an image.
Cursor cursor = getActivity().getContentResolver().query(_uri, new String[]{android.provider.MediaStore.Images.ImageColumns.DATA}, null, null, null);
cursor.moveToFirst();
//Link to the image
final String imageFilePath = cursor.getString(0);
editPhoto1.setImageBitmap(null);
if (bmp != null) {
bmp.recycle();
}
setImagePicked(imageFilePath, 1);
cursor.close();
} else {
// If camera intent is choosed this condition remain true
editPhoto1.setImageBitmap(null);
if (bmp != null) {
bmp.recycle();
}
setImagePicked(getFileDirectory().getPath(), 0);
}
}
super.onActivityResult(requestCode, resultCode, data);
}
3) Set the image
private void setImagePicked(String filePath, int status) {
try {
bmp = ImageResizer.decodeSampledBitmapFromFile(new File(filePath).getAbsolutePath(), 512, 342);
/* This for rotating the image use if necessary */
if (status == 0) {
Matrix mMatrix = new Matrix();
Matrix mat = editPhoto1.getImageMatrix();
mMatrix.set(mat);
mMatrix.setRotate(270);
bmp = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(),
bmp.getHeight(), mMatrix, false);
}
editPhoto1.setImageBitmap(bmp);
} catch (Exception e) {
Log.e("Exception Image Set :: ", e.getMessage());
}
}
4) Finally the image resizer class
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
public class ImageResizer {
public static Bitmap decodeSampledBitmapFromFile(String filename,
int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options
options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filename, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(filename, options);
}
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// BEGIN_INCLUDE (calculate_sample_size)
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
// This offers some additional logic in case the image has a strange
// aspect ratio. For example, a panorama may have a much larger
// width than height. In these cases the total pixels might still
// end up being too large to fit comfortably in memory, so we should
// be more aggressive with sample down the image (=larger inSampleSize).
long totalPixels = width * height / inSampleSize;
// Anything more than 2x the requested pixels we'll sample down further
final long totalReqPixelsCap = reqWidth * reqHeight * 2;
while (totalPixels > totalReqPixelsCap) {
inSampleSize *= 2;
totalPixels /= 2;
}
}
return inSampleSize;
// END_INCLUDE (calculate_sample_size)
}
}

Categories

Resources