Out of memory error while setting an image in imageview? - android

I can select images using to methods
1.Using gallery
2.Using camera
which is used to upload,So when i take a picture by using camera,it sets in the imageview but after that if i pic an image from gallery,it shows out of memory error.I tried many codes which i have commented in the following code but nothing worked for me.
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if(data.getData() != null) {
//((BitmapDrawable)iv.getDrawable()).getBitmap().recycle();
selectedImageUri = data.getData();
} else {
Log.d("selectedPath1 : ","Came here its null !");
Toast.makeText(getApplicationContext(), "failed to get Image!", 500).show();
}
final BitmapFactory.Options options = new BitmapFactory.Options();
Bitmap photo = (Bitmap) data.getExtras().get("data");
if (requestCode == 100 && resultCode == RESULT_OK) {
options.inSampleSize = 8;
/* if(photo!=null) {
photo.recycle();
photo=null;
}*/
selectedPath = getPath(selectedImageUri);
iv.setImageURI(selectedImageUri);
}
if (requestCode == 10) {
options.inSampleSize = 8;
/*iv.clearAnimation();
if(photo!=null) {
photo.recycle();
photo=null;
}*/
selectedPath = getPath(selectedImageUri);
// ((BitmapDrawable)iv.getDrawable()).getBitmap().recycle();
iv.setImageURI(selectedImageUri);
}
}
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
iv.setImageDrawable(null);
// Dismiss the progress bar when application is closed
if (prgDialog != null) {
prgDialog.dismiss();
}
}

You need to optimise Bitmap loading, there's a very good article on Android Developers that explains how to do it properly.

You are using BitmapFactory.Options but you are not applying them to your image getter:
You should need something like this:
InputStream input = this.getContentResolver().openInputStream(uri);
BitmapFactory.Options onlyBoundsOptions = new BitmapFactory.Options();
options.inSampleSize = 8;
Bitmap bitmap = BitmapFactory.decodeStream(input, null, onlyBoundsOptions);
input.close();
Hope it helps

you are try this just i do this code for in my application register
// Image Purpose
String selectedImagePath, ServerUploadPath = "" + "", str_response;
public static final int MEDIA_TYPE_IMAGE = 1;
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
private static final int SELECT_PICTURE = 1;
private static final String IMAGE_DIRECTORY_NAME = "Hello Camera";
static File mediaFile;
private Uri fileUri; // file url to store image/video
boolean ChangeButton = true, btnChangePic = false;
// ImageView DefaultImage;
Bitmap DefaultImage;
Bitmap rotatedBMP;
public void cameraAndGalaryPicture() {
final String[] opString = { "Take Photo", "Choose From Gallery",
"Cancel" };
AlertDialog.Builder dbuilder = new AlertDialog.Builder(
SignUp_Activity.this);
dbuilder.setTitle("Add Photo!");
dbuilder.setItems(opString, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (opString[which].equals("Take Photo")) {
fromCamera();
} else if (opString[which].equals("Choose From Gallery")) {
fromFile();
} else {
dialog.dismiss();
}
}
});
dbuilder.show();
}
public void fromCamera() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
IMAGE_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
+ IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else {
return null;
}
Log.e("path", "media file:-" + mediaFile);
return mediaFile;
}
public void fromFile() {
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "Select File"),
SELECT_PICTURE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == this.RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
System.out.println("Image Path : " + selectedImagePath);
Log.d("select pah", "path" + selectedImagePath);
previewCapturedImage();
}
}
// if the result is capturing Image
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == this.RESULT_OK) {
// successfully captured the image
// display it in image view
selectedImagePath = mediaFile.toString();
previewCapturedImage();
} else if (resultCode == this.RESULT_CANCELED) {
// user cancelled Image capture
Toast.makeText(getApplicationContext(),
"User cancelled image capture", Toast.LENGTH_SHORT)
.show();
} else {
// failed to capture image
Toast.makeText(getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = this.managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
private void previewCapturedImage() {
try {
int targetW = 380;
int targetH = 800;
Log.d("Get w", "width" + targetW);
Log.d("Get H", "height" + targetH);
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(selectedImagePath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
// Determine how much to scale down the image
int scaleFactor = Math.min(photoW / targetW, photoH / targetH);
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor << 1;
bmOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(selectedImagePath,
bmOptions);
Matrix mtx = new Matrix();
try {
File imageFile = new File(selectedImagePath);
ExifInterface exif = new ExifInterface(
imageFile.getAbsolutePath());
int orientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
Log.e("Orintation", " :-" + orientation);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_270:
mtx.postRotate(270);
rotatedBMP = Bitmap.createBitmap(bitmap, 0, 0,
bitmap.getWidth(), bitmap.getHeight(), mtx, true);
if (rotatedBMP != bitmap)
bitmap.recycle();
iv_SelectPhoto.setImageBitmap(rotatedBMP);
Global.rg_image = rotatedBMP;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
mtx.postRotate(180);
rotatedBMP = Bitmap.createBitmap(bitmap, 0, 0,
bitmap.getWidth(), bitmap.getHeight(), mtx, true);
if (rotatedBMP != bitmap)
bitmap.recycle();
iv_SelectPhoto.setImageBitmap(rotatedBMP);
Global.rg_image = rotatedBMP;
break;
case ExifInterface.ORIENTATION_ROTATE_90:
mtx.postRotate(90);
rotatedBMP = Bitmap.createBitmap(bitmap, 0, 0,
bitmap.getWidth(), bitmap.getHeight(), mtx, true);
if (rotatedBMP != bitmap)
bitmap.recycle();
iv_SelectPhoto.setImageBitmap(rotatedBMP);
Global.rg_image = rotatedBMP;
break;
case ExifInterface.ORIENTATION_NORMAL:
mtx.postRotate(0);
rotatedBMP = Bitmap.createBitmap(bitmap, 0, 0,
bitmap.getWidth(), bitmap.getHeight(), mtx, true);
if (rotatedBMP != bitmap)
bitmap.recycle();
iv_SelectPhoto.setImageBitmap(rotatedBMP);
Global.rg_image = rotatedBMP;
break;
default:
mtx.postRotate(0);
rotatedBMP = Bitmap.createBitmap(bitmap, 0, 0,
bitmap.getWidth(), bitmap.getHeight(), mtx, true);
if (rotatedBMP != bitmap)
bitmap.recycle();
iv_SelectPhoto.setImageBitmap(rotatedBMP);
// img_profilepic.setImageBitmap(BitmapFactory
// .decodeFile(mCurrentPhotoPath));
Global.rg_image = rotatedBMP;
}
Log.i("RotateImage", "Exif orientation: " + orientation);
} catch (Exception e) {
e.printStackTrace();
}
} catch (NullPointerException e) {
e.printStackTrace();
}
}
rg_image is i use for to store image in Global class in my application.

Related

Android camera photo saved in wrong orientation

I am trying to take photo and let the photo saved in portrait orientation. I could not do so even if I changed the manifest nor the intent's orientation to set it portrait. I Google and tried various ways, but none works. Please assist.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.i("request", requestCode + " result " + resultCode + " intent "
+ data);
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == RESULT_SAVE_ITEM){
clearItemContents();
}
else if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK)
{ExifInterface ei = new ExifInterface(cameraImagePath);
int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_UNDEFINED);
switch(orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
rotateImage(bitmap, 90);
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotateImage(bitmap, 180);
break;
case ExifInterface.ORIENTATION_ROTATE_270:
rotateImage(bitmap, 270);
break;
case ExifInterface.ORIENTATION_NORMAL:
default:
break;
}
openGallery();
}
else{
if (gallery == true) {
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();
imageArray = imageToByteArray(new File(picturePath));
setImagePicture(picturePath);
} else {
}
} else if (gallery == false) {
File file = new File(cameraImagePath);
if (file.exists()) {
imageArray = imageToByteArray(file);
setImagePicture(cameraImagePath);
} else {
}
} else {
this.finish();
startActivity(new Intent(this, DefectAdd.class));
}}
}
public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, int pixels)
{
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap
.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
final RectF rectF = new RectF(rect);
final float roundPx = pixels;
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
return output;
}
private byte[] imageToByteArray(File file) {
try {
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
for (int readNum; (readNum = fis.read(buf)) != -1;) {
bos.write(buf, 0, readNum);
System.out.println("read " + readNum + " bytes,");
}
byte[] bytes = bos.toByteArray();
return bytes;
} catch (IOException ex) {
ex.printStackTrace();
}
return null;
}
private void setImagePicture(String photoPath) {
editTextItemPic.setVisibility(ImageView.GONE);
itemImage.setVisibility(ImageView.VISIBLE);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(photoPath, options);
itemImage.setRotation(90);
itemImage.setImageBitmap(bitmap);
}
public void showDialog() {
builder.setTitle("Choose Action!");
builder.setItems(dialogItems, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (item == 0) {
openGallery();
} else if(item == 1) {
openCamera();
}else{
imageArray = null;
editTextItemPic.setVisibility(ImageView.VISIBLE);
itemImage.setVisibility(ImageView.GONE);
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
public void openGallery() {
MaterialAddActivity.gallery = true;
Intent i = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, MaterialAddActivity.RESULT_LOAD_IMAGE);
}
public void openCamera() {
USE_CAMERA=1;
Intent cameraIntent=new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
private String appFolderCheckandCreate() {
String appFolderPath = "";
File externalStorage =Environment.getExternalStorageDirectory();
if (externalStorage.canWrite()) {
appFolderPath = "/storage/emulated/0/DCIM/Camera/";
File dir = new File(externalStorage+"/storage/emulated/0/DCIM/Camera/");
if (!dir.exists()) {
dir.mkdirs();
}
} else {
}
return appFolderPath;
}
#SuppressLint("SimpleDateFormat") private String getTimeStamp() {
final long timestamp = new Date().getTime();
final Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(timestamp);
final String timeString = new SimpleDateFormat("HH_mm_ss_SSS")
.format(cal.getTime());
return timeString;
}
public void saveImage()
{
File filename;
try
{
USE_CAMERA=0;
String path = Environment.getExternalStorageDirectory().toString();
new File(path + "/QSHelper").mkdirs();
filename = new File(path + "/QSHelper/image"+LASTINSERTEDID+".png");
FileOutputStream out = new FileOutputStream(filename);
photo.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
MediaStore.Images.Media.insertImage(getContentResolver(),
filename.getAbsolutePath(), filename.getName(),
filename.getName());
} catch (Exception e)
{
e.printStackTrace();
}
}

Upload from camera and gallery is not working properly in all the versions

I am trying number of tutorials and sample codes for take an image from gallery or camera then crop the image and upload it to server. I was implemented the code for that in that code am facing few problems the are.
In pre Lollipop devices when I crop the image using photos app the image is not getting reflected in image view but it's showing the message as image saved..
In nexus phone both camera and gallery is not working.
5.0 versions in few devices when I crop the image am getting the image like shown below
below is my code snippet.`
public void getPhoto() {
final String[] items = new String[] { "Take from camera",
"Select from gallery" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.select_dialog_item, items);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Select Image");
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) { // pick from
// camera
if (item == 0) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(
"android.intent.extras.CAMERA_FACING",
android.hardware.Camera.CameraInfo.CAMERA_FACING_FRONT);
mImageCaptureUri = Uri.fromFile(new File(Environment
.getExternalStorageDirectory(), "tmp_avatar_"
+ String.valueOf(System.currentTimeMillis())
+ ".jpg"));
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
mImageCaptureUri);
try {
intent.putExtra("return-data", true);
startActivityForResult(intent, PICK_FROM_CAMERA);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
} else { // pick from file
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
// startActivityForResult(intent, SELECT_PICTURE);
startActivityForResult(intent, PICK_FROM_FILE);
}
}
});
final AlertDialog dialog = builder.create();
dialog.show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != Activity.RESULT_OK)
return;
switch (requestCode) {
case PICK_FROM_CAMERA:
doCrop();
break;
case PICK_FROM_FILE:
mImageCaptureUri = data.getData();
doCrop();
break;
case CROP_FROM_CAMERA:
Bundle extras = data.getExtras();
if (extras != null) {
photo = extras.getParcelable("data");
profile_image = encodeTobase64(photo);
saveType = "photo";
try {
JSONObject obj = new JSONObject();
obj.put("user_id", user_id);
obj.put("mode", saveType);
obj.put("photo", profile_image);
obj.put("is_profile", 1);
saveResponse(obj);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
File f = new File(mImageCaptureUri.getPath());
if (f.exists())
f.delete();
break;
}
}
private void doCrop() {
final ArrayList<CropOption> cropOptions = new ArrayList<CropOption>();
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setType("image/*");
List<ResolveInfo> list = getActivity().getPackageManager()
.queryIntentActivities(intent, 0);
int size = list.size();
if (size == 0) {
Toast.makeText(getActivity(), "Can not find image crop app",
Toast.LENGTH_SHORT).show();
return;
} else {
intent.setData(mImageCaptureUri);
intent.putExtra("crop", "true");
intent.putExtra("outputX", 300);
intent.putExtra("outputY", 300);
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("scale", true);
intent.putExtra("circleCrop", new String(""));
intent.putExtra("return-data", true);
if (size == 1) {
Intent i = new Intent(intent);
ResolveInfo res = list.get(0);
i.setComponent(new ComponentName(res.activityInfo.packageName,
res.activityInfo.name));
startActivityForResult(i, CROP_FROM_CAMERA);
} else {
for (ResolveInfo res : list) {
final CropOption co = new CropOption();
co.title = getActivity().getPackageManager()
.getApplicationLabel(
res.activityInfo.applicationInfo);
co.icon = getActivity().getPackageManager()
.getApplicationIcon(
res.activityInfo.applicationInfo);
co.appIntent = new Intent(intent);
co.appIntent
.setComponent(new ComponentName(
res.activityInfo.packageName,
res.activityInfo.name));
cropOptions.add(co);
}
CropOptionAdapter adapter = new CropOptionAdapter(
getActivity(), cropOptions);
AlertDialog.Builder builder = new AlertDialog.Builder(
getActivity());
builder.setTitle("Choose Crop App");
builder.setAdapter(adapter,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
startActivityForResult(
cropOptions.get(item).appIntent,
CROP_FROM_CAMERA);
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
if (mImageCaptureUri != null) {
getActivity().getContentResolver().delete(
mImageCaptureUri, null, null);
mImageCaptureUri = null;
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
}
public String encodeTobase64(Bitmap image) {
Bitmap immagex = image;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
immagex.compress(Bitmap.CompressFormat.JPEG, 100, baos);
image_Array = baos.toByteArray();
String imageEncoded = Base64
.encodeToString(image_Array, Base64.DEFAULT);
return imageEncoded;
}
`
comment below before duplicating this question because i was checked a lot but didn't find any solution for this, please let me know if you need more information.
I have the same problem last week and I finally solve it, it's a little bit different in my case I get an image in Base64 from a server then crop it
here's the code
byte[] decodedString = Base64.decode(imageJson, Base64.DEFAULT);
Bitmap tmp = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
bitmapDecoded = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int h = metrics.heightPixels;
int w = metrics.widthPixels;
Bitmap resized = Bitmap.createScaledBitmap(tmp, tmp.getWidth(), (int) (tmp.getHeight()*1.6), true);
imageView.setImageBitmap(canvas.getCircleBitmap(resized, w,h));
imageJson is the image in Base64 it's a String I transform it in a Bitmap, after I get the size of the screen, the Bitmap resized is here for have a square image, cause I have a 16/9 image this is maybe not usefull for you, and finally I show the bitmap in an imageView and crop it with the canvas method getCircleBitmap
here is the method
public Bitmap getCircleBitmap(Bitmap bitmap,int width, int height) {
final Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
bitmap.getHeight(), Bitmap.Config.ARGB_8888);
final Canvas canvas = new Canvas(output);
final int color = Color.RED;
final Paint paint = new Paint();
final Rect rect = new Rect((int)(bitmap.getWidth()*0.054), (int) (height*0.005), (int) (bitmap.getWidth()*0.945), (bitmap.getHeight()));
final RectF rectF = new RectF(rect);
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawOval(rectF, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
bitmap.recycle();
return output;
}
You can change the value of the rect for fit it for your usage
I declare this method in a canvas class who extends View, really hope this help you too and sorry for my english
i also facing this issue..Now its working fine because i m using library
**compile 'com.soundcloud.android:android-crop:1.0.1#aar'**
public Uri mImageCaptureUri=null;
Pick image from gallery
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, PICK_FROM_FILE);
this is add to onActivityResult method
//call this line after crop it
if(requestCode == Crop.REQUEST_CROP){
handleCrop(resultCode, data);
}
case PICK_FROM_FILE:
mImageCaptureUri = data.getData();
beginCrop(mImageCaptureUri);
break;
private void beginCrop(Uri source) {
Uri destination = Uri.fromFile(new File(getCacheDir(), "cropped"));
Crop.of(source, destination).asSquare().start(this);
}
private void handleCrop(int resultCode, Intent result) {
if (resultCode == RESULT_OK) {
// mImage.setImageURI(Crop.getOutput(result));
Picasso.with(SettingsActivity.this).load(Crop.getOutput(result)).transform(new RoundTransform()).into(mImage);
mImageCaptureUri=Crop.getOutput(result);
getImageUri(mImageCaptureUri); //this method uri stored to sdcard
} else if (resultCode == Crop.RESULT_ERROR) {
Toast.makeText(this, Crop.getError(result).getMessage(), Toast.LENGTH_SHORT).show();
}
}
If user requests to take a picture:
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(BaseActivity.this.getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = ImageVideoUtil.createImageFile();
} catch (IOException ex) {
ex.printStackTrace();
}
if (photoFile != null) {
imagePath = Uri.fromFile(photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imagePath);
startActivityForResult(takePictureIntent, ApplicationConstants.REQUEST_CAMERA);
}
}
If user requests to pick from camera you can use:
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, ApplicationConstants.REQUEST_GALLERY);
dialog.dismiss();
And on your activity result you can get uri and use it:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
BaseFragment fragment = (BaseFragment) getSupportFragmentManager().findFragmentById(R.id.fl_main);
if (resultCode == RESULT_OK) {
Bitmap bitmap = null;
switch (requestCode) {
case ApplicationConstants.REQUEST_CAMERA:
if (imagePath != null && fragment instanceof PhotoView) {
bitmap = Tools.fromGallery(this, imagePath);
if (bitmap != null) {
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth() / 2, bitmap.getHeight() / 2);
((PhotoView) fragment).onPhotoSet(bitmap);
}
}
break;
case ApplicationConstants.REQUEST_GALLERY:
Uri uri = data.getData();
imagePath = uri;
bitmap = Tools.fromGallery(this, uri);
if (bitmap != null && fragment instanceof PhotoView) {
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth() / 2, bitmap.getHeight() / 2);
((PhotoView) fragment).onPhotoSet(bitmap);
}
break;
case ApplicationConstants.REQUEST_VIDEO:
if (fragment instanceof VideoView) {
((VideoView) fragment).onVideoSelected(videoPath);
}
break;
}
}
}
Here the ImageVideoUtil Class which'll help you to crop, scale, save and read image video operations.
public class ImageVideoUtil {
public static void startCameraIntent(Activity activity) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(activity.getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
ex.printStackTrace();
}
// Continue only if the File was successfully created
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
activity.startActivityForResult(takePictureIntent, ApplicationConstants.REQUEST_CAMERA);
}
}
}
public static File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "SnapSense" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(imageFileName, /* prefix */
ApplicationConstants.DEFAULT_IMGAE_SUFFIX, /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
return image;
}
public static File createVideoFile() throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "SnapSense" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);
File video = File.createTempFile(imageFileName, /* prefix */
ApplicationConstants.DEFAULT_VIDEO_SUFFIX, /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
return video;
}
public static Bitmap decodeBitmap(Bitmap bmp) {
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 50, out);
return BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray()));
} catch (Exception ex) {
ex.printStackTrace();
}
return bmp;
}
}
Finally here are some other static methods to help you:
public static Bitmap fromGallery(Context context, final Uri selectedImageUri) {
try {
Bitmap bm = MediaStore.Images.Media.getBitmap(context.getContentResolver(), selectedImageUri);
ExifInterface exif = new ExifInterface(selectedImageUri.getPath());
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
int angle = 0;
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
angle = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
angle = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
angle = 270;
break;
default:
angle = 0;
break;
}
Matrix mat = new Matrix();
if (angle == 0 && bm.getWidth() > bm.getHeight())
mat.postRotate(90);
else
mat.postRotate(angle);
return Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), mat, true);
} catch (IOException e) {
e.printStackTrace();
} catch (OutOfMemoryError oom) {
oom.printStackTrace();
}
return null;
}
public static String getRealPathFromURI(Activity activity, Uri contentUri) {
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = activity.managedQuery(contentUri, proj, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
I hope my code helps you. Good Luck.
I was facing same issue in Nexus. I used Android Image Cropper which is very lightweight and flexible.
compile 'com.theartofdev.edmodo:android-image-cropper:2.2.+'
Each version has there own way to get path:
Try this method will work for every version, IT WORKED FOR ME:
public static String getRealPathFromURI(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/"
+ split[1];
}
// TODO handle non-primary volumes
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"),
Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[]{split[1]};
return getDataColumn(context, contentUri, selection,
selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}

Android image from gallery orientation

public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == getActivity().RESULT_OK && data != null && data.getData() != null) {
filePath = data.getData();
String wholeID = DocumentsContract.getDocumentId(filePath);
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
String[] column = { MediaStore.Images.Media.DATA };
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = getActivity().getContentResolver().
query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[]{id}, null);
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
uploadFilePath = cursor.getString(columnIndex);
uploadFilePath = decodeFile(uploadFilePath, 512, 512);
}
cursor.close();
try {
bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), filePath);
if(sendImageType.equals("profile")){
imgProfile.setImageBitmap(bitmap);
}
else if(sendImageType.equals("cover")){
imgCover.setImageBitmap(bitmap);
}
pDialog = ProgressDialog.show(getActivity(), "", "Uploading file...", true);
new Thread(new Runnable() {
public void run() {
uploadFile(uploadFilePath);
}
}).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Decode File :
private String decodeFile(String path,int DESIREDWIDTH, int DESIREDHEIGHT) {
String strMyImagePath = null;
Bitmap scaledBitmap = null;
try {
// Part 1: Decode image
Bitmap unscaledBitmap = ScalingUtilities.decodeFile(path, DESIREDWIDTH, DESIREDHEIGHT, ScalingUtilities.ScalingLogic.FIT);
if (!(unscaledBitmap.getWidth() <= DESIREDWIDTH && unscaledBitmap.getHeight() <= DESIREDHEIGHT)) {
// Part 2: Scale image
scaledBitmap = ScalingUtilities.createScaledBitmap(unscaledBitmap, DESIREDWIDTH, DESIREDHEIGHT, ScalingUtilities.ScalingLogic.FIT);
} else {
unscaledBitmap.recycle();
return path;
}
// Store to tmp file
String extr = Environment.getExternalStorageDirectory().toString();
File mFolder = new File(extr + "/TMMFOLDER");
if (!mFolder.exists()) {
mFolder.mkdir();
}
String s = "tmp.png";
File f = new File(mFolder.getAbsolutePath(), s);
strMyImagePath = f.getAbsolutePath();
FileOutputStream fos = null;
try {
fos = new FileOutputStream(f);
scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 75, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
scaledBitmap.recycle();
} catch (Throwable e) {
}
if (strMyImagePath == null) {
return path;
}
return strMyImagePath;
}
Hi, i have an image uploader, i am uploading image from android gallery to my server. But some photos load horizontally. How can i understand, photo is horizontal or vertical and how do i rotate.
It look below, after upload :
to check the orientation of an image
ExifInterface ei = new ExifInterface(photoPath);
int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
switch(orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
break;
case ExifInterface.ORIENTATION_ROTATE_180:
break;
// etc.
}
To rotate the image use
private Bitmap rotateImage(Bitmap source, float angle) {
Bitmap bitmap = null;
Matrix matrix = new Matrix();
matrix.postRotate(angle);
try {
bitmap = Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(),
matrix, true);
} catch (OutOfMemoryError err) {
err.printStackTrace();
}
return bitmap;
}
try this code:
public static Bitmap getOriententionBitmap(String filePath){
Bitmap myBitmap = null;
try
{
File f = new File(filePath);
ExifInterface exif = new ExifInterface(f.getPath());
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
int angle = 0;
if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
angle = 90;
}
else if (orientation == ExifInterface.ORIENTATION_ROTATE_180) {
angle = 180;
}
else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) {
angle = 270;
}
Matrix mat = new Matrix();
mat.postRotate(angle);
Bitmap bmp1 = BitmapFactory.decodeStream(new FileInputStream(f), null, null);
myBitmap = Bitmap.createBitmap(bmp1, 0, 0, bmp1.getWidth(), bmp1.getHeight(), mat, true);
}
catch (IOException e) {
Log.w("TAG", "-- Error in setting image");
}
catch(OutOfMemoryError oom) {
Log.w("TAG", "-- OOM Error in setting image");
}
return myBitmap;
}

How to pick image from gallery and upload to server (parse.com) ?

Hi I m using Eclipse and new to Android.
Is there a simple way to pick image and upload it to parse.com server.
also, is is there is a simple way to retrieve image from server and set this image to a ImageView on layout.
try to this way for pickup image from camera & gallery.
// this is local variable.
String selectedImagePath, ServerUploadPath = "" + "", str_response;
public static final int MEDIA_TYPE_IMAGE = 1;
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
private static final int SELECT_PICTURE = 1;
private static final String IMAGE_DIRECTORY_NAME = "Hello Camera";
static File mediaFile;
private Uri fileUri; // file url to store image/video
this method for camera & Gallery image pick up.
public void cameraAndGalaryPicture() {
final String[] opString = { "Take Photo", "Choose From Gallery",
"Cancel" };
AlertDialog.Builder dbuilder = new AlertDialog.Builder(this);
dbuilder.setTitle("Add Photo!");
dbuilder.setItems(opString, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (opString[which].equals("Take Photo")) {
fromCamera();
} else if (opString[which].equals("Choose From Gallery")) {
fromFile();
} else {
// Picasso.with(getApplicationContext())
// .load(R.drawable.default_image).resize(360, 200)
// .into(iv_Profile_pic);
rotatedBMP = BitmapFactory.decodeResource(getResources(),
R.drawable.default_image);
Global.mImage = rotatedBMP;
Log.e("Else if", "msg::19th Feb- " + rotatedBMP);
Log.e("Else if", "msg::19th Feb- " + Global.mImage);
// dialog.dismiss();
}
}
});
dbuilder.show();
}
public void fromCamera() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
private static File getOutputMediaFile(int type) {
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
IMAGE_DIRECTORY_NAME);
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
+ IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else {
return null;
}
Log.e("path", "media file:-" + mediaFile);
return mediaFile;
}
public void fromFile() {
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "Select File"),
SELECT_PICTURE);
}
public String getPath(Uri uri, Activity activity) {
String[] projection = { MediaColumns.DATA };
Cursor cursor = activity
.managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
this method for compress image
private void previewCapturedImage() {
try {
int targetW = 380;
int targetH = 800;
Log.d("Get w", "width" + targetW);
Log.d("Get H", "height" + targetH);
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(selectedImagePath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
// Determine how much to scale down the image
int scaleFactor = Math.min(photoW / targetW, photoH / targetH);
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor << 1;
bmOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(selectedImagePath,
bmOptions);
Matrix mtx = new Matrix();
try {
File imageFile = new File(selectedImagePath);
ExifInterface exif = new ExifInterface(
imageFile.getAbsolutePath());
int orientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
Log.e("Orintation", " :-" + orientation);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_270:
mtx.postRotate(270);
rotatedBMP = Bitmap.createBitmap(bitmap, 0, 0,
bitmap.getWidth(), bitmap.getHeight(), mtx, true);
if (rotatedBMP != bitmap)
bitmap.recycle();
iv_Profile_pic.setImageBitmap(rotatedBMP);
Global.edtImage = rotatedBMP;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
mtx.postRotate(180);
rotatedBMP = Bitmap.createBitmap(bitmap, 0, 0,
bitmap.getWidth(), bitmap.getHeight(), mtx, true);
if (rotatedBMP != bitmap)
bitmap.recycle();
iv_Profile_pic.setImageBitmap(rotatedBMP);
Global.edtImage = rotatedBMP;
break;
case ExifInterface.ORIENTATION_ROTATE_90:
mtx.postRotate(90);
rotatedBMP = Bitmap.createBitmap(bitmap, 0, 0,
bitmap.getWidth(), bitmap.getHeight(), mtx, true);
if (rotatedBMP != bitmap)
bitmap.recycle();
iv_Profile_pic.setImageBitmap(rotatedBMP);
Global.edtImage = rotatedBMP;
break;
case ExifInterface.ORIENTATION_NORMAL:
mtx.postRotate(0);
rotatedBMP = Bitmap.createBitmap(bitmap, 0, 0,
bitmap.getWidth(), bitmap.getHeight(), mtx, true);
if (rotatedBMP != bitmap)
bitmap.recycle();
iv_Profile_pic.setImageBitmap(rotatedBMP);
Global.edtImage = rotatedBMP;
break;
default:
mtx.postRotate(0);
rotatedBMP = Bitmap.createBitmap(bitmap, 0, 0,
bitmap.getWidth(), bitmap.getHeight(), mtx, true);
if (rotatedBMP != bitmap)
bitmap.recycle();
iv_Profile_pic.setImageBitmap(rotatedBMP);
// img_profilepic.setImageBitmap(BitmapFactory
// .decodeFile(mCurrentPhotoPath));
Global.edtImage = rotatedBMP;
}
Log.i("RotateImage", "Exif orientation: " + orientation);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] data = stream.toByteArray();
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
// hear store data in parse table.
ParseFile ParseimageFile1 = new ParseFile("IMG_" + timeStamp
+ ".jpg", data);
ParseimageFile1.saveInBackground();
// ParseimageFile1 variable declare at Globle
} catch (Exception e) {
e.printStackTrace();
}
} catch (NullPointerException e) {
e.printStackTrace();
}
}
and this is on activity result.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
System.out.println("Image Path : " + selectedImagePath);
Log.d("select pah", "path" + selectedImagePath);
previewCapturedImage();
}
}
// if the result is capturing Image
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// successfully captured the image
// display it in image view
selectedImagePath = mediaFile.toString();
previewCapturedImage();
} else if (resultCode == RESULT_CANCELED) {
// user cancelled Image capture
Toast.makeText(getApplicationContext(),
"User cancelled image capture", Toast.LENGTH_SHORT)
.show();
} else {
// failed to capture image
Toast.makeText(getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
}
}
now store data at parse table like.
and after store fetch data
ParseObject obj = new ParseObject("ClassName");
obj.put("table colum name", ParseimageFile1);
obj.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
// TODO Auto-generated method stub
if (e == null) {
// success
} else {
// fail
}
}
});
// now get image from parse table
// in parse table image data type is parseFile
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>(
"Class Name");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> list, ParseException e) {
// TODO Auto-generated method stub
if (e == null) {
// success
for (ParseObject parseObject : list) {
ParseFile image = (ParseFile) parseObject
.get("key_name");
Log.e(key_TAG, "get Image URL " + image.getUrl());
}
} else {
// fail
}
}
});

Android bitmap redraw

In my app I take picture from camera and preview it. My app takes picture in landscape mode so that I changed it to portrait mode using exifInterface but I get stretched image.
How can I redraw my Image with out stretched image from the bitmap. if I take picture in landscape mode, it looks good.
this is my code for camera part:
public class TakePic extends Fragment {
#SuppressWarnings("deprecation")
#SuppressLint("NewApi")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (container == null) {
return null;
}
View v = inflater.inflate(R.layout.add_spot_2, container, false);
....
upload.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
String path = Environment.getExternalStorageDirectory()
+ "/pic";
File photopath = new File(path);
if (!photopath.exists()) {
photopath.mkdir();
}
imagePath = new File(photopath, "pic"
+ System.currentTimeMillis() + ".png");
DataPassing.imagePath = imagePath;
if(imageUri==null){
Log.e("Image uri is null", "Image uri is null 1");
}
else{
Log.e("Image uri is NOT null", "Image uri is NOT null 1");
}
Log.e("file path ", imagePath.getAbsolutePath());
imageUri = Uri.fromFile(imagePath);
DataPassing.imageUri = imageUri;
if(imageUri==null){
Log.e("Image uri is null ", "Image uri is null 2");
}
else{
Log.e("Image uri is NOT null", "Image uri is NOT null 2");
}
Log.e("uri file path ", imageUri.getPath());
intent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(imagePath));
startActivityForResult(intent, 100);
}
});
........
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#SuppressWarnings({ "deprecation" })
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100 && resultCode == Activity.RESULT_OK) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 10;
if (DataPassing.imageUri == null) {
Toast.makeText(getActivity(), "Please retry",
Toast.LENGTH_SHORT).show();
} else {
Bitmap bm = readBitmap(DataPassing.imageUri);
int or = 0;
try {
or = resolveBitmapOrientation(DataPassing.imagePath);
Log.e("int", String.valueOf(or));
} catch (IOException e) {
e.printStackTrace();
}
if(or==1){
image.setBackgroundDrawable(new BitmapDrawable(bm));
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] array = stream.toByteArray();
AddNewSpotValues.comm_2_picture_path = array;
DataPassing.addspot2_bm = bm;
}
else{
int w = bm.getWidth();
int h = bm.getHeight();
Log.e("w & h", ""+w + " & " + h);
Matrix mtx = new Matrix();
mtx.postRotate(90);
Bitmap rbm = Bitmap.createBitmap(bm, 0, 0, w, h, mtx, true);
// Bitmap rbm = Bitmap.createBitmap(bm, 0, 0, 200,150, mtx, true);
image.setBackgroundDrawable(new BitmapDrawable(rbm));
ByteArrayOutputStream stream = new ByteArrayOutputStream();
rbm.compress(Bitmap.CompressFormat.PNG, 100, stream);
DataPassing.addspot2_bm = rbm;
byte[] array = stream.toByteArray();
AddNewSpotValues.comm_2_picture_path = array;
}
}
}
}
#Override
public void onLowMemory() {
// TODO Auto-generated method stub
super.onLowMemory();
}
private Bitmap readBitmap(Uri selectedImage) {
try {
File f = new File(selectedImage.getPath());
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 100;
// Find the correct scale value. It should be the power of 2.
int scale = 1;
while (o.outWidth / scale / 2 >= REQUIRED_SIZE
&& o.outHeight / scale / 2 >= REQUIRED_SIZE)
scale *= 2;
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {
}
return null;
}
private int resolveBitmapOrientation(File bitmapFile) throws IOException {
ExifInterface exif = null;
exif = new ExifInterface(bitmapFile.getAbsolutePath());
return exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
}
}
You might need to open your camera in portrait mode instead of manipulating the image itself accepted answer here show you how to do it

Categories

Resources