How to uplaod high quality image to imageview in android? - android

I want to upload the high quality image to server and get it in Imageview in my app. I'm able to do so. But the problem is quality of image which is very low. How can i upload the desire resolution of image to server and get it in imageview. Help me. Thanks
Here is my Code:
public class ChangeProfileActivity extends Activity {
ImageView updateBT, IV;
private SharedPreferences saveImagePref;
private SharedPreferences.Editor saveImagePrefEditor;
protected static final int CAMERA_REQUEST = 0;
protected static final int GALLERY_PICTURE = 1;
private Intent pictureActionIntent = null;
Bitmap bitmap;
private TouchImageView touch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
// setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_change_profile);
updateBT = (ImageView) findViewById(R.id.buttonUpdate);
dialog = new AlertDialogCheck(ChangeProfileActivity.this);
IV = (ImageView) findViewById(R.id.PersonalPictureIV);
saveImagePref = getSharedPreferences("saveImage", MODE_PRIVATE);
saveImagePrefEditor = saveImagePref.edit();
saveDOBPref = getSharedPreferences("saveImage", MODE_PRIVATE);
saveDOBPrefEditor = saveImagePref.edit();
registerForContextMenu(IV);
A = saveImagePref.getString("SAVE", "0");
bitmap = StringToBitMap(A);
if (bitmap != null) {
bitmap = Bitmap.createScaledBitmap(bitmap, 250, 250, false);
IV.setImageBitmap(bitmap);
}
if (bitmap == null) {
bitmap = BitmapFactory.decodeResource(this.getResources(),
R.drawable.user_profile_image);
IV.setImageBitmap(bitmap);
IV.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
startDialog();
uploadImage();
}
});
}
IV.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
startDialog();
}
});
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
}
private void startDialog() {
AlertDialog.Builder myAlertDialog = new AlertDialog.Builder(this);
myAlertDialog.setTitle("Upload Pictures Option");
myAlertDialog.setMessage("How do you want to set your picture?");
myAlertDialog.setPositiveButton("Gallery",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
pictureActionIntent = new Intent(
Intent.ACTION_GET_CONTENT, null);
pictureActionIntent.setType("image/*");
pictureActionIntent.putExtra("return-data", true);
startActivityForResult(pictureActionIntent,
GALLERY_PICTURE);
}
});
myAlertDialog.setNegativeButton("Camera",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
pictureActionIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(pictureActionIntent,
CAMERA_REQUEST);
}
});
myAlertDialog.show();
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_PICTURE) {
if (resultCode == RESULT_OK) {
if (data != null) {
// our BitmapDrawable for the thumbnail
BitmapDrawable bmpDrawable = null;
// try to retrieve the image using the data from the intent
Cursor cursor = getContentResolver().query(data.getData(),
null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(ImageColumns.DATA);
String fileSrc = cursor.getString(idx);
BitmapFactory.Options options=new BitmapFactory.Options();
options.inSampleSize=1;
bitmap = BitmapFactory.decodeFile(fileSrc);
bitmap = Bitmap.createScaledBitmap(bitmap, 250, 250,
true);
saveImagePrefEditor.clear();
saveImagePrefEditor.commit();
saveImagePrefEditor.putString("SAVE",
BitMapToString(bitmap));
saveImagePrefEditor.commit();
IV.setImageBitmap(bitmap);
// touch.setImageBitmap(bitmap);+
A = saveImagePref.getString("SAVE", "0");
uploadImage();
} else {
bmpDrawable = new BitmapDrawable(getResources(), data
.getData().getPath());
IV.setImageDrawable(bmpDrawable);
// touch.setImageBitmap(bitmap);
A = saveImagePref.getString("SAVE", "0");
uploadImage();
}
} else {
Toast.makeText(getApplicationContext(), "Cancelled",
Toast.LENGTH_SHORT).show();
}
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(getApplicationContext(), "Cancelled",
Toast.LENGTH_SHORT).show();
}
} else if (requestCode == CAMERA_REQUEST) {
if (resultCode == RESULT_OK) {
if (data.hasExtra("data")) {
bitmap = (Bitmap) data.getExtras().get("data");
bitmap = Bitmap.createScaledBitmap(bitmap, 250, 250, false);
saveImagePrefEditor.clear();
saveImagePrefEditor.commit();
saveImagePrefEditor.putString("SAVE",
BitMapToString(bitmap));
saveImagePrefEditor.commit();
// update the image view with the bitmap
IV.setImageBitmap(bitmap);
// touch.setImageBitmap(bitmap);
A = saveImagePref.getString("SAVE", "0");
uploadImage();
} else if (data.getExtras() == null) {
Toast.makeText(getApplicationContext(),
"No extras to retrieve!", Toast.LENGTH_SHORT)
.show();
BitmapDrawable thumbnail = new BitmapDrawable(
getResources(), data.getData().getPath());
// update the image view with the newly created drawable
IV.setImageDrawable(thumbnail);
// touch.setImageBitmap(bitmap);
A = saveImagePref.getString("SAVE", "0");
uploadImage();
}
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(getApplicationContext(), "Cancelled",
Toast.LENGTH_SHORT).show();
} }
}
public String BitMapToString(Bitmap bitmap) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
String temp = Base64.encodeToString(b, Base64.DEFAULT);
return temp;
}
public Bitmap StringToBitMap(String encodedString) {
try {
byte[] encodeByte = Base64.decode(encodedString, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(encodeByte, 0,
encodeByte.length);
return bitmap;
} catch (Exception e) {
e.getMessage();
return null;
}}
}

You can use android best practice.
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;
}
public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
public static Bitmap decodeFile(int width , int height ,File f) {
try {
// decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
// decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = calculateInSampleSize(o, width, height);
//System.out.println("Scale: " + scale);
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {
//System.out.println("--- exception "+e.toString());
e.printStackTrace();
}
return null;
}

Related

Android App Using too much Memory more than 500MB

I am using Camera Kit Library on that activity the memory usage is too much in app app what could be the possible issue?
This is a camera view activity which uses camera Kit Library. Camera Results are received when user clicks captureButton and cameraView.captureImage() is called and results are sent to next Preview Activity. But i am seeing huge memory usage when just activity is opened and no image is captured yet.
My activity Code:
public class PSLSelfieActivity extends AppCompatActivity {
private CameraKitView cameraView;
private FloatingActionButton captureButton, switchCamera, useGallery;
private String TAG = "ramiz";
private int orientation = 0;//0=pot,1=land
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pslselfie);
getWindow().getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
try {
cameraView = findViewById(R.id.camera);
captureButton = findViewById(R.id.captureButton);
useGallery = findViewById(R.id.useGalleryButton);
OrientationEventListener mOrientationListener = new OrientationEventListener(
getApplicationContext()) {
#Override
public void onOrientationChanged(int orientation) {
PSLSelfieActivity.this.orientation = orientation;
}
};
if (mOrientationListener.canDetectOrientation()) {
mOrientationListener.enable();
}
captureButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cameraView.captureImage(new CameraKitView.ImageCallback() {
#Override
public void onImage(CameraKitView cameraKitView, byte[] bytes) {
Intent i = new Intent(PSLSelfieActivity.this, PSLSelfiePreview.class);
Bitmap b = loadBitmap(bytes);
Log.d(TAG, "OnCaptureImage: Bitmap Size= w=" + b.getWidth() + " h=" + b.getHeight());
PSLSelfiePreview.inputImage = b;
i.putExtra("orientation", orientation);
i.putExtra("flipImage", true);
startActivity(i);
}
});
}
});
useGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, USE_GALLERY_REQUEST);
}
});
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getContext(), "There is some error with opening camera.", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (requestCode == USE_GALLERY_REQUEST) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
try {
final Uri imageUri = data.getData();
final InputStream imageStream = getContentResolver().openInputStream(imageUri);
Intent i = new Intent(PSLSelfieActivity.this, PSLSelfiePreview.class);
Bitmap b = loadBitmap(imageUri);
Log.d(TAG, "onActivityResult: Bitmap Size= w=" + b.getWidth() + " h=" + b.getHeight());
PSLSelfiePreview.inputImage = b;
i.putExtra("orientation", 0);
i.putExtra("flipImage", false);
startActivity(i);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getContext(), "Cannot Load Image.", Toast.LENGTH_SHORT).show();
} catch (OutOfMemoryError e) {
e.printStackTrace();
Toast.makeText(getContext(), "Cannot Load Image. Image too Large.", Toast.LENGTH_SHORT).show();
}
} else {
}
}
}
#Override
protected void onStart() {
cameraView.onStart();
super.onStart();
}
#Override
protected void onResume() {
cameraView.onResume();
super.onResume();
}
#Override
protected void onPause() {
cameraView.onPause();
super.onPause();
}
#Override
protected void onStop() {
cameraView.onStop();
super.onStop();
}
#Override
protected void onDestroy() {
System.gc();
super.onDestroy();
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
cameraView.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
System.gc();
}
public Bitmap loadBitmap(byte[] bytes) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
Bitmap b = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options);
options.inSampleSize = calculateInSampleSize(options, 480, 640);
Log.d(TAG, "loadBitmap: inSampleSize=" + options.inSampleSize);
options.inJustDecodeBounds = false;
return BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options);
}
public Bitmap loadBitmap(Uri imageUri) throws IOException {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
final InputStream imageStream;
imageStream = getContentResolver().openInputStream(imageUri);
Bitmap b = BitmapFactory.decodeStream(imageStream, null, options);
options.inSampleSize = calculateInSampleSize(options, 480, 640);
Log.d(TAG, "loadBitmap: inSampleSize=" + options.inSampleSize);
options.inJustDecodeBounds = false;
final InputStream imageStreamNew;
imageStreamNew = getContentResolver().openInputStream(imageUri);
Bitmap outBitmap = BitmapFactory.decodeStream(imageStreamNew, null, options);
if (imageStream != null) {
imageStream.close();
}
if (imageStreamNew != null) {
imageStreamNew.close();
}
return outBitmap;
}
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;
Log.d(TAG, "calculateInSampleSize: h=" + height + " - w=" + width);
if (width > height) {
int temp = reqHeight;
reqHeight = reqWidth;
reqWidth = temp;
}
Log.d(TAG, "calculateInSampleSize: updated h=" + height + " - w=" + width);
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;
}
private Context getContext() {
return this;
}
}

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

Need help to show image from gallery only in portrait mode Android

I am a new bie in Android development.
Please bare with my english.
I struck with a problem where I am unable to show image from gallery in portrait mode,it is showing in landscape mode.Here is the code for your reference,Could you please help me to solve this issue.Thanks in Advance.
What I tried sofar is, I have gone through the below stackoverflow answers to the same issue and tried to place the same code in my class but the image still sits in landscape mode only.
Stackvoerflow links I followed are:
1.Open Image from Gallery Only in Potrait mode
2.http://codereply.com/answer/5xf8di/android-detect-image-orientation-portrait-landscape-picked-gallery-setting-imageview.html
3.Android: Bitmaps loaded from gallery are rotated in ImageView
public class FragmentTab1 extends Fragment {
RelativeLayout homes;
private static int RESULT_LOAD_IMAGE = 1;
ImageView bitmapView;
BitmapFactory.Options options;
String filePath;
Button rot;
private int mDegree = 0;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Get the view from fragmenttab1.xml
View ima = inflater.inflate(R.layout.fragmenttab1, container, false);
homes = (RelativeLayout) ima.findViewById(R.id.hmt);
bitmapView = (ImageView) ima.findViewById(R.id.image);
homes.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
return false;
}
});
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
final String filePath = prefs.getString("profilePic", "");
if (!filePath.equals("")) {
bitmapView = (ImageView) ima.findViewById(R.id.image);
bitmapView.setImageBitmap(BitmapLoaderf.loadBitmap(filePath, 500, 500));
bitmapView.setScaleType(ImageView.ScaleType.FIT_XY);
}
return ima;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == getActivity().RESULT_OK && null != data) {
Uri picUri = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().getContentResolver().query(picUri,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
filePath = cursor.getString(columnIndex);
cursor.close();
bitmapView.setImageBitmap(BitmapLoaderf.loadBitmap(filePath, 500, 500));
bitmapView.setScaleType(ImageView.ScaleType.FIT_XY);
SharedPreferences shre = PreferenceManager.getDefaultSharedPreferences(getActivity());
Editor edit = shre.edit();
edit.putString("profilePic", filePath);
edit.commit();
}
}
}
class BitmapLoaderf {
public static int getScale(int originalWidth, int originalHeight,
final int requiredWidth, final int requiredHeight) {
//a scale of 1 means the original dimensions
//of the image are maintained
int scale = 1;
//calculate scale only if the height or width of
//the image exceeds the required value.
if ((originalWidth > requiredWidth) || (originalHeight > requiredHeight)) {
//calculate scale with respect to
//the smaller dimension
if (originalWidth < originalHeight)
scale = Math.round((float) originalWidth / requiredWidth);
else
scale = Math.round((float) originalHeight / requiredHeight);
}
return scale;
}
public static BitmapFactory.Options getOptions(String filePath,
int requiredWidth, int requiredHeight) {
BitmapFactory.Options options = new BitmapFactory.Options();
//setting inJustDecodeBounds to true
//ensures that we are able to measure
//the dimensions of the image,without
//actually allocating it memory
options.inJustDecodeBounds = true;
//decode the file for measurement
BitmapFactory.decodeFile(filePath, options);
//obtain the inSampleSize for loading a
//scaled down version of the image.
//options.outWidth and options.outHeight
//are the measured dimensions of the
//original image
options.inSampleSize = getScale(options.outWidth,
options.outHeight, requiredWidth, requiredHeight);
//set inJustDecodeBounds to false again
//so that we can now actually allocate the
//bitmap some memory
options.inJustDecodeBounds = false;
return options;
}
public static Bitmap loadBitmap(String filePath,
int requiredWidth, int requiredHeight) {
BitmapFactory.Options options = getOptions(filePath,
requiredWidth, requiredHeight);
return BitmapFactory.decodeFile(filePath, options);
}
}
This is what I usually do :
public class ExifUtils {
public static Bitmap rotateBitmap(String src, Bitmap bitmap) {
try {
int orientation = getExifOrientation(src);
if (orientation == 1) {
return bitmap;
}
Matrix matrix = new Matrix();
switch (orientation) {
case 2:
matrix.setScale(-1, 1);
break;
case 3:
matrix.setRotate(180);
break;
case 4:
matrix.setRotate(180);
matrix.postScale(-1, 1);
break;
case 5:
matrix.setRotate(90);
matrix.postScale(-1, 1);
break;
case 6:
matrix.setRotate(90);
break;
case 7:
matrix.setRotate(-90);
matrix.postScale(-1, 1);
break;
case 8:
matrix.setRotate(-90);
break;
default:
return bitmap;
}
try {
Bitmap oriented = Bitmap.createBitmap(bitmap, 0, 0,
bitmap.getWidth(), bitmap.getHeight(), matrix, true);
bitmap.recycle();
return oriented;
} catch (OutOfMemoryError e) {
e.printStackTrace();
return bitmap;
}
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
private static int getExifOrientation(String src) throws IOException {
int orientation = 1;
try {
/**
* if your are targeting only api level >= 5 ExifInterface exif =
* new ExifInterface(src); orientation =
* exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
*/
if (Build.VERSION.SDK_INT >= 5) {
Class<?> exifClass = Class
.forName("android.media.ExifInterface");
Constructor<?> exifConstructor = exifClass
.getConstructor(new Class[] { String.class });
Object exifInstance = exifConstructor
.newInstance(new Object[] { src });
Method getAttributeInt = exifClass.getMethod("getAttributeInt",
new Class[] { String.class, int.class });
java.lang.reflect.Field tagOrientationField = exifClass
.getField("TAG_ORIENTATION");
String tagOrientation = (String) tagOrientationField.get(null);
orientation = (Integer) getAttributeInt.invoke(exifInstance,
new Object[] { tagOrientation, 1 });
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
return orientation;
}
}
Then in the main Activity you call it like this:
image.setImageBitmap(ExifUtils.rotateBitmap(path, decodeSampledBitmap(new File(path), 400, 400)));
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;
}
In this code you extract the bitmap from the file path, give it a certain height and width and pass it to the ExifUtils to show the bitmap in the correct way.
I think this wraps your class and more.
If you need anymore help I am more than ready to offer

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

unable to add image to imageview from camera capture

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

Categories

Resources