Set ImageView with selected Image from Camera or Gallery - android

In my Activity I want put in a ImageView a photo from camera or gallery!
From camera this code work well, while when I take an image from gallery it works until when I choose my photo! After, it don't give me it in imageview! Who can help me?
Here is it MainActivity code:
public class MainActivity extends Activity {
private Button mTakePhoto;
private ImageView mImageView;
private static final int CAMERA_REQUEST = 1;
private static final int PICK_FROM_GALLERY = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTakePhoto = (Button) findViewById(R.id.take_photo);
mImageView = (ImageView) findViewById(R.id.imageview);
final String[] option = new String[] { "Take from Camera", "Select from Gallery" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.select_dialog_item, option);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select Option");
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Log.e("Selected Item", String.valueOf(which));
if (which == 0) {
callCamera();
}
if (which == 1) {
callGallery();
}
}
});
final AlertDialog dialog = builder.create();
mTakePhoto.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dialog.show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if (resultCode != RESULT_OK)
return;
switch (requestCode) {
case CAMERA_REQUEST:
setPic();
break;
case PICK_FROM_GALLERY:
Bundle extras2 = data.getExtras();
if (extras2 != null) {
Bitmap yourImage = extras2.getParcelable("data");
// convert bitmap to byte
ByteArrayOutputStream stream = new ByteArrayOutputStream();
yourImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte imageInByte[] = stream.toByteArray();
Log.e("output before conversion", imageInByte.toString());
// Inserting Contacts
Log.d("Insert: ", "Inserting ..");
Intent i = new Intent(MainActivity.this, MainActivity.class);
startActivity(i);
finish();
}
break;
}
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Log.i(TAG, "onResume: " + this);
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
// TODO Auto-generated method stub
super.onConfigurationChanged(newConfig);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
Log.i(TAG, "onSaveInstanceState");
}
String mCurrentPhotoPath;
File photoFile = null;
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(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
}
// Continue only if the File was successfully created
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, CAMERA_REQUEST);
}
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
String storageDir = Environment.getExternalStorageDirectory() + "/uploads";
File dir = new File(storageDir);
if (!dir.exists())
dir.mkdir();
File image = new File(storageDir + "/" + imageFileName + ".jpg");
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
Log.i(TAG, "photo path = " + mCurrentPhotoPath);
return image;
}
private void setPic() {
// Get the dimensions of the View
int targetW = mImageView.getWidth();
int targetH = mImageView.getHeight();
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(mCurrentPhotoPath, 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(mCurrentPhotoPath, bmOptions);
Matrix mtx = new Matrix();
mtx.postRotate(90);
// Rotating Bitmap
Bitmap rotatedBMP = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), mtx, true);
mImageView.setImageBitmap(rotatedBMP);
}
public void callCamera() {
dispatchTakePictureIntent();
}
public void callGallery() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 0);
intent.putExtra("aspectY", 0);
intent.putExtra("outputX", 200);
intent.putExtra("outputY", 150);
intent.putExtra("return-data", true);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_GALLERY);
}
}
Thanks,Marco

Because you have this code in your camera :
mImageView.setImageBitmap(rotatedBMP);
But you dont have it on the gallery. You should set the bitmap too in case PICK_FROM_GALLERY on your onActivityResult.
The code should be like this :
if (extras2 != null)
{
Bitmap yourImage = extras2.getParcelable("data");
//your other code
mImageView.setImageBitmap(yourImage);
}

Related

How to make custom camera layout in Android?

I am trying to develop some kind of OCR application with Text Recognizing feature. I wrote and found some codes which is working properly but my problem is I want make some customization in the camera layout. I want to add my own capture button and add a frame. I actually did it on a different project with "surface view/holder". But I cannot implement my project because it works so differently.
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_GALLERY = 0;
private static final int REQUEST_CAMERA = 1;
private static final String TAG = MainActivity.class.getSimpleName();
private Uri imageUri;
private TextView detectedTextView; // layouttaki text view
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.choose_from_gallery).setOnClickListener(new View.OnClickListener() { // galeriden resim seçme işlemi
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, REQUEST_GALLERY);
}
});
findViewById(R.id.take_a_photo).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) { // resim çekme işlemi
String filename = System.currentTimeMillis() + ".jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, filename);
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent();
intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, REQUEST_CAMERA);
}
});
detectedTextView = (TextView) findViewById(R.id.detected_text);
detectedTextView.setMovementMethod(new ScrollingMovementMethod());
}
private void inspectFromBitmap(Bitmap bitmap) { //kendisine gelen bitmap resimden inspect yapar
TextRecognizer textRecognizer = new TextRecognizer.Builder(this).build();
try {
if (!textRecognizer.isOperational()) {
new AlertDialog.
Builder(this).
setMessage("Text recognizer could not be set up on your device").show();
return;
}
Frame frame = new Frame.Builder().setBitmap(bitmap).build();
SparseArray<TextBlock> origTextBlocks = textRecognizer.detect(frame);
List<TextBlock> textBlocks = new ArrayList<>();
for (int i = 0; i < origTextBlocks.size(); i++) {
TextBlock textBlock = origTextBlocks.valueAt(i);
textBlocks.add(textBlock);
}
Collections.sort(textBlocks, new Comparator<TextBlock>() {
#Override
public int compare(TextBlock o1, TextBlock o2) {
int diffOfTops = o1.getBoundingBox().top - o2.getBoundingBox().top;
int diffOfLefts = o1.getBoundingBox().left - o2.getBoundingBox().left;
if (diffOfTops != 0) {
return diffOfTops;
}
return diffOfLefts;
}
});
StringBuilder detectedText = new StringBuilder();
for (TextBlock textBlock : textBlocks) {
if (textBlock != null && textBlock.getValue() != null) {
detectedText.append(textBlock.getValue());
detectedText.append("\n");
}
}
detectedTextView.setText(detectedText); // detectedText is a final string
}
finally {
textRecognizer.release();
}
}
private void inspect(Uri uri) {
InputStream is = null;
Bitmap bitmap = null;
try {
is = getContentResolver().openInputStream(uri);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
options.inSampleSize = 2;
options.inScreenDensity = DisplayMetrics.DENSITY_LOW;
bitmap = BitmapFactory.decodeStream(is, null, options);
Bitmap rotatedMap = RotateBitmap(bitmap,90);
inspectFromBitmap(rotatedMap);
} catch (FileNotFoundException e) {
Log.w(TAG, "Failed to find the file: " + uri, e);
} finally {
if (bitmap != null) {
bitmap.recycle();
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
Log.w(TAG, "Failed to close InputStream", e);
}
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_GALLERY:
if (resultCode == RESULT_OK) {
inspect(data.getData());
}
break;
case REQUEST_CAMERA:
if (resultCode == RESULT_OK) {
if (imageUri != null) {
inspect(imageUri);
}
}
break;
default:
super.onActivityResult(requestCode, resultCode, data);
break;
}
}
public static Bitmap RotateBitmap(Bitmap source, float angle) // it rotates the bitmap for given parameter
{
Matrix matrix = new Matrix();
matrix.postRotate(angle);
return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);
}
In that case, what should I do ? Thank you guys.
No, you cannot change the layout of the camera app that fulfills ACTION_IMAGE_CAPTURE intent. Actually, different devices will not have same camera apps. Each may have very different look-and-feel. You need a 'custom camera' to control its layout and UX.

Android Choose Image or Camera

I have implemented the code for choosing an image from SD or Camera.
But, my image doesn't show up in ImageView and I can't choose an image from SD card.
When I click on an image from SD card it jumps instant back to my Activity.
final String[] items = new String[] {"From Camera","From SD Card"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.select_dialog_item,items);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select Image");
builder.setAdapter(adapter,new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog,int which){
if(which == 0){
intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = new File(Environment.getExternalStorageDirectory(),"event_image"+String.valueOf(System.currentTimeMillis()+".jpg"));
imageCaptureUri = Uri.fromFile(file);
try {
intent.putExtra(MediaStore.EXTRA_OUTPUT,imageCaptureUri);
intent.putExtra("return data",true);
startActivityForResult(intent,PICK_FROM_CAMERA);
}catch(Exception ex){
ex.printStackTrace();
}
dialog.cancel();
}else{
intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Complete action using"),PICK_FROM_FILE);
}
}
});
final AlertDialog dialog = builder.create();
mImageView = (ImageView) findViewById(R.id.imageView);
imagePicker = (ImageButton) findViewById(R.id.image_picker);
imagePicker.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
dialog.show();
}
});
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode != RESULT_OK)
return;
Bitmap bitmap = null;
String path ="";
if(requestCode == PICK_FROM_FILE) {
imageCaptureUri = data.getData();
path = getRealPathFromURI(imageCaptureUri);
if(path == null)
path = imageCaptureUri.getPath();
if(path != null){
bitmap = BitmapFactory.decodeFile(path);
}
}else{
path = imageCaptureUri.getPath();
bitmap = BitmapFactory.decodeFile(path);
}
mImageView.setImageBitmap(bitmap);
}
public String getRealPathFromURI(Uri contentURI){
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery(contentURI,proj,null,null,null);
if(cursor == null) return null;
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
First you need to use permission WRITE_EXTERNAL_STORAGE in AndroidManifest.xml
In your xml layout :
<ImageView
android:id="#+id/img"
android:layout_width="match_parent"
android:layout_height="380dp"
android:background="#f241c9" />
<Button
android:id="#+id/btnCapture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:text="Take Photo" />
<Button
android:id="#+id/btnPick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:text="Pick Photo" />
In your activity class :
private static final String TAG = "my_log";
private static final int REQUEST_CAPTURE_FROM_CAMERA = 1;
private static final int REQUEST_PICK_FROM_FILE = 2;
private static final int REQUEST_CROP_INTENT = 3;
ImageView img;
Button btnCapture, btnPick;
File file;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img = (ImageView) findViewById(R.id.img);
btnCapture = (Button) findViewById(R.id.btnCapture);
btnPick = (Button) findViewById(R.id.btnPick);
btnCapture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
file = new File(Environment.getExternalStorageDirectory() + File.separator + "img_captured.jpg");
// put Uri as extra in intent object
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
startActivityForResult(intent, REQUEST_CAPTURE_FROM_CAMERA);
}
});
btnPick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), REQUEST_PICK_FROM_FILE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) return;
if (requestCode == REQUEST_CAPTURE_FROM_CAMERA) {
try {
cropImage(Uri.fromFile(file));
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "Your device does not support the crop action!", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
} else if (requestCode == REQUEST_PICK_FROM_FILE) {
try {
cropImage(data.getData());
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "Your device does not support the crop action!", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
} else if (requestCode == REQUEST_CROP_INTENT) {
// Create an instance of bundle and get the returned data
Bundle extras = data.getExtras();
// get the cropped bitmap from extras
Bitmap bitmap = extras.getParcelable("data");
img.setImageBitmap(bitmap);
if (saveBitmapToStorage(bitmap)) {
Log.d(TAG, "Bitmap saved to file successful.");
} else {
Log.d(TAG, "Failed to save Bitmap to storage.");
}
}
}
public void cropImage(Uri picUri) {
//call the standard crop action intent
Intent cropIntent = new Intent("com.android.camera.action.CROP");
//indicate image type and Uri of image
cropIntent.setDataAndType(picUri, "image/*");
//set crop properties
cropIntent.putExtra("crop", "true");
//indicate aspect of desired crop
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1);
//indicate output X and Y
cropIntent.putExtra("outputX", 256);
cropIntent.putExtra("outputY", 256);
//retrieve data on return
cropIntent.putExtra("return-data", true);
//start the activity - we handle returning in onActivityResult
startActivityForResult(cropIntent, REQUEST_CROP_INTENT);
}
private boolean saveBitmapToStorage(Bitmap finalBitmap) {
boolean result = false;
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "img_cropped.jpg");
Log.d(TAG, "file path = " + file.getAbsolutePath());
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
// send Broadcast to notify this photo and see it in Gallery
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(file);
mediaScanIntent.setData(contentUri);
sendBroadcast(mediaScanIntent);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}

Android : Integrating gallery functionality with camera capture

I am working on an Android project in which I have the functionality where user can click on the a button and it will open the camera to upload the image. The upload button is hidden until there is image taken and shown in preview.
What I would like to do is to use the same upload button, which I have set to visible by default now and on clicking it, I would like to open a gallery, which the user can then use to select an image, and it would be shown in preview.
I have a boolean flag to manage this, where if the flag is false, then gallery is opened, else the image in the preview is uploaded.
I have this, but I don't know how to open a gallery and then send the image to preview, to upload. I am new to Android programming, so kindly take that into consideration.
I searched for similar functionality, but the problem is, I have not found, where such features are integrated.
Java code :
RobotoTextView BtnSelectImage;
private ImageView ImgPhoto;
CheckBox profilePhotoCheckBox;
final RestaurantImageServiceImpl restaurantService = new RestaurantImageServiceImpl();
private static final int CAMERA_PHOTO = 111;
private Uri imageToUploadUri;
private static volatile Bitmap reducedSizeBitmap;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
private static boolean galleryFlag = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_restaurant_images);
ImgPhoto = (ImageView) findViewById(R.id.userPhotoImageView);
BtnSelectImage = (RobotoTextView) findViewById(R.id.userPhotoButtonSelect);
profilePhotoCheckBox = (CheckBox)findViewById(R.id.profilePhotoCheckBox);
BtnSelectImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
galleryFlag = true;
captureCameraImage();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Couldn't load photo", Toast.LENGTH_LONG).show();
}
}
});
uploadImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!(v == null)) {
if(!galleryFlag){
// I think the gallery open code should come here.
}
if (profilePhotoCheckBox.isChecked()) {
uploadImage(true);
}else {
uploadImage(false);
}
new AlertDialog.Builder(AddPhotosForRestaurant.this)
.setTitle("Add more photos")
.setMessage("Are you sure you want to add more photos?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
startActivity(getIntent());
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(getApplicationContext(), RestaurantMenu.class);
startActivity(intent);
finish();
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
}
});
}
private Bitmap getBitmap(String path) {
Uri uri = Uri.fromFile(new File(path));
InputStream in = null;
try {
final int IMAGE_MAX_SIZE = 1200000; // 1.2MP
in = getContentResolver().openInputStream(uri);
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(in, null, o);
in.close();
int scale = 1;
while ((o.outWidth * o.outHeight) * (1 / Math.pow(scale, 2)) >
IMAGE_MAX_SIZE) {
scale++;
}
Log.d("", "scale = " + scale + ", orig-width: " + o.outWidth + ", orig-height: " + o.outHeight);
Bitmap b = null;
in = getContentResolver().openInputStream(uri);
if (scale > 1) {
scale--;
// scale to max possible inSampleSize that still yields an image
// larger than target
o = new BitmapFactory.Options();
o.inSampleSize = scale;
b = BitmapFactory.decodeStream(in, null, o);
// resize to desired dimensions
int height = b.getHeight();
int width = b.getWidth();
Log.d("", "1th scale operation dimenions - width: " + width + ", height: " + height);
double y = Math.sqrt(IMAGE_MAX_SIZE
/ (((double) width) / height));
double x = (y / height) * width;
Bitmap scaledBitmap = Bitmap.createScaledBitmap(b, (int) x,
(int) y, true);
b.recycle();
b = scaledBitmap;
System.gc();
} else {
b = BitmapFactory.decodeStream(in);
}
in.close();
Log.d("", "bitmap size - width: " + b.getWidth() + ", height: " +
b.getHeight());
return b;
} catch (IOException e) {
Log.e("", e.getMessage(), e);
return null;
}
}
private void captureCameraImage() {
Intent chooserIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(Environment.getExternalStorageDirectory(), "POST_IMAGE.jpg");
chooserIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
imageToUploadUri = Uri.fromFile(f);
startActivityForResult(chooserIntent, CAMERA_PHOTO);
}
#Override
public void onBackPressed() {
Intent intent = new Intent(this, Login.class);
StaticRestTemplate.setReplyString("");
StaticRestTemplate.setLoggedInUser("");
StaticRestTemplate.setJsessionid("");
startActivity(intent);
finish();
}
#Override
protected void onActivityResult(final int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_PHOTO && resultCode == Activity.RESULT_OK) {
if(imageToUploadUri != null){
Uri selectedImage = imageToUploadUri;
getContentResolver().notifyChange(selectedImage, null);
reducedSizeBitmap = getBitmap(imageToUploadUri.getPath());
if(reducedSizeBitmap != null){
ImgPhoto.setImageBitmap(reducedSizeBitmap);
RobotoTextView uploadImageButton = (RobotoTextView) findViewById(R.id.uploadUserImageButton);
uploadImageButton.setVisibility(View.VISIBLE);
}else{
Toast.makeText(this,"Error while capturing Image",Toast.LENGTH_LONG).show();
}
}else{
Toast.makeText(this,"Error while capturing Image",Toast.LENGTH_LONG).show();
}
}
}
private void uploadImage(boolean profilePhoto) {
if(!(reducedSizeBitmap == null)){
if(reducedSizeBitmap == null){
Log.d("Image bitmap"," Is null");
}
reducedSizeBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
this.restaurantService.addRestaurantImage(byteArray,profilePhoto);
}
}
}
I hope this much information is enough. Can anyone point me which functions I should put and where. Thanks a lot. :-)
Edit with Answer
Finally the integration works. I had to combine answers from the one I received and here on SO.
Final Code
public class AddPhotosForRestaurant extends RestaurantDrawerActivity {
RobotoTextView BtnSelectImage;
private ImageView ImgPhoto;
CheckBox profilePhotoCheckBox;
final RestaurantImageServiceImpl restaurantService = new RestaurantImageServiceImpl();
private static final int CAMERA_PHOTO = 111;
public static final int GALLERY_INTENT_REQUEST_CODE = 0x000005;
private Uri imageToUploadUri = null;
private static volatile Bitmap reducedSizeBitmap;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
private boolean galleryFlag = false;
private boolean uploadNow = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_restaurant_images);
set(null, null);
final RobotoTextView uploadImageButton = (RobotoTextView) findViewById(R.id.uploadUserImageButton);
ImgPhoto = (ImageView) findViewById(R.id.userPhotoImageView);
BtnSelectImage = (RobotoTextView) findViewById(R.id.userPhotoButtonSelect);
profilePhotoCheckBox = (CheckBox) findViewById(R.id.profilePhotoCheckBox);
BtnSelectImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
galleryFlag = true;
captureCameraImage();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Couldn't load photo", Toast.LENGTH_LONG).show();
}
}
});
uploadImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!(v == null)) {
if (uploadNow) {
uploadNow = false;
galleryFlag = true;
if (profilePhotoCheckBox.isChecked()) {
uploadImage(true);
} else {
uploadImage(false);
}
}
if (!galleryFlag) {
galleryFlag = true;
uploadNow = true;
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"),
GALLERY_INTENT_REQUEST_CODE);
} else {
if (profilePhotoCheckBox.isChecked()) {
uploadImage(true);
} else {
uploadImage(false);
}
new AlertDialog.Builder(AddPhotosForRestaurant.this)
.setTitle("Add more photos")
.setMessage("Are you sure you want to add more photos?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
startActivity(getIntent());
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(getApplicationContext(), RestaurantMenu.class);
startActivity(intent);
finish();
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
}
}
});
}
private Bitmap getBitmap(String path) {
Uri uri = Uri.fromFile(new File(path));
InputStream in = null;
try {
final int IMAGE_MAX_SIZE = 1200000; // 1.2MP
in = getContentResolver().openInputStream(uri);
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(in, null, o);
in.close();
int scale = 1;
while ((o.outWidth * o.outHeight) * (1 / Math.pow(scale, 2)) >
IMAGE_MAX_SIZE) {
scale++;
}
Bitmap b;
in = getContentResolver().openInputStream(uri);
if (scale > 1) {
scale--;
// scale to max possible inSampleSize that still yields an image
// larger than target
o = new BitmapFactory.Options();
o.inSampleSize = scale;
b = BitmapFactory.decodeStream(in, null, o);
// resize to desired dimensions
int height = b.getHeight();
int width = b.getWidth();
double y = Math.sqrt(IMAGE_MAX_SIZE
/ (((double) width) / height));
double x = (y / height) * width;
Bitmap scaledBitmap = Bitmap.createScaledBitmap(b, (int) x,
(int) y, true);
b.recycle();
b = scaledBitmap;
System.gc();
} else {
b = BitmapFactory.decodeStream(in);
}
in.close();
return b;
} catch (IOException e) {
return null;
}
}
private void captureCameraImage() {
Intent chooserIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(Environment.getExternalStorageDirectory(), "POST_IMAGE.jpg");
chooserIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
imageToUploadUri = Uri.fromFile(f);
startActivityForResult(chooserIntent, CAMERA_PHOTO);
}
#Override
public void onBackPressed() {
Intent intent = new Intent(this, Login.class);
StaticRestTemplate.setReplyString("");
StaticRestTemplate.setLoggedInUser("");
StaticRestTemplate.setJsessionid("");
startActivity(intent);
finish();
}
#Override
protected void onActivityResult(final int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_PHOTO && resultCode == Activity.RESULT_OK) {
if (imageToUploadUri != null) {
Uri selectedImage = imageToUploadUri;
getContentResolver().notifyChange(selectedImage, null);
reducedSizeBitmap = getBitmap(imageToUploadUri.getPath());
if (reducedSizeBitmap != null) {
ImgPhoto.setImageBitmap(reducedSizeBitmap);
RobotoTextView uploadImageButton = (RobotoTextView) findViewById(R.id.uploadUserImageButton);
uploadImageButton.setVisibility(View.VISIBLE);
} else {
Toast.makeText(this, "Error while capturing Image", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(this, "Error while capturing Image", Toast.LENGTH_LONG).show();
}
}
if (requestCode == GALLERY_INTENT_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
try {
Uri selectedImage = Uri.parse(data.getDataString());
reducedSizeBitmap = MediaStore.Images.Media.getBitmap(
getApplicationContext().getContentResolver(),
selectedImage);
ImgPhoto.setImageBitmap(reducedSizeBitmap);
} catch (Exception e) {
Toast.makeText(this, "Error while selecting Image", Toast.LENGTH_LONG).show();
}
}
}
private void uploadImage(boolean profilePhoto) {
if (!(reducedSizeBitmap == null)) {
reducedSizeBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
this.restaurantService.addRestaurantImage(byteArray, profilePhoto);
}
}
}
Thanks a lot for all your help.. :-)
In Constant file write in my case(ActivityConstantUtils.java)
public static final int GALLERY_INTENT_REQUEST_CODE = 0x000005;
To open Gallery & get path of selected image use following code :
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
photoPickerIntent.setType("image/*");
photoPickerIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
mActPanelFragment.startActivityForResult(photoPickerIntent, ActivityConstantUtils.GALLERY_INTENT_REQUEST_CODE);
After that you get path in onActivityResult() method
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
(requestCode == ActivityConstantUtils.GALLERY_INTENT_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
try {
String imagePath = getFilePath(data);
// TODO: Here you set data to preview screen
}catch(Exception e){}
}
}
private String getFilePath(Intent data) {
String imagePath;
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imagePath = cursor.getString(columnIndex);
cursor.close();
return imagePath;
}

How to do custom image cropping in android

In my application, I need to take images from gallery/camera, crop those images, then save the cropped images some where else. The below code does most of that, but cannot crop images to my liking. Using the below code, I can crop images using 4 coordinates, top, bottom, left and right side of image middle coordinates; but I need to crop using 8 coordinates. This image shows what I mean.
public class MainActivity extends Activity {
private static final int PICK_FROM_CAMERA = 1;
private static final int PICK_FROM_GALLERY = 2;
private static final int PRESS_OK = 3;
ImageView imgview;
String m_path;
Bitmap m_thePic;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgview = (ImageView) findViewById(R.id.imageView1);
Button buttonCamera = (Button) findViewById(R.id.btn_take_camera);
Button buttonGallery = (Button) findViewById(R.id.btn_select_gallery);
Button buttonOk = (Button) findViewById(R.id.btn_ok);
File folder = new File(Environment.getExternalStorageDirectory().toString() + "/Images/");
folder.mkdirs();
buttonCamera.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// call android default camera
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI.toString());
// ******** code for crop image
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 0);
intent.putExtra("aspectY", 0);
intent.putExtra("outputX", 100);
intent.putExtra("outputY", 150);
try {
intent.putExtra("return-data", true);
startActivityForResult(intent, PICK_FROM_CAMERA);
} catch (ActivityNotFoundException e) {
// Do nothing for now
}
}
});
buttonGallery.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();
// call android default gallery
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
// ******** code for crop image
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 0);
intent.putExtra("aspectY", 0);
intent.putExtra("outputX", 200);
intent.putExtra("outputY", 150);
try {
intent.putExtra("return-data", true);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), 1);
} catch (ActivityNotFoundException e) {
// Do nothing for now
}
}
});
buttonOk.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String m_path = Environment.getExternalStorageDirectory().toString();
File m_imgDirectory = new File(m_path + "/Images/");
File m_file = new File(m_path);
String m_fileid = "nm_tech" + System.currentTimeMillis() + "";
m_file = new File(m_path, "/Images/" + m_fileid + ".jpg");
Uri outputFileUri = Uri.fromFile(m_file);
Intent intent = new Intent(MainActivity.this,
ImageGalleryDemoActivity.class);
intent.putExtra("image", m_fileid);
startActivity(intent);
// startActivityForResult(intent,PRESS_OK);
// call android default camera
// Toast.makeText(getApplicationContext(), ,1234).show();
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Bundle extras = data.getExtras();
Bitmap m_thePic = extras.getParcelable("data");
String m_path = Environment.getExternalStorageDirectory().toString();
File m_imgDirectory = new File(m_path + "/Images/");
if (!m_imgDirectory.exists()) {
m_imgDirectory.mkdir();
}
OutputStream m_fOut = null;
File m_file = new File(m_path);
m_file.delete();
String m_fileid = "nm_tech" + System.currentTimeMillis() + "";
m_file = new File(m_path, "/Images/" + m_fileid + ".jpg");
try {
if (!m_file.exists()) {
m_file.createNewFile();
}
m_fOut = new FileOutputStream(m_file);
Bitmap m_bitmap = m_thePic.copy(Bitmap.Config.ARGB_8888, true);
m_bitmap.compress(Bitmap.CompressFormat.PNG, 100, m_fOut);
m_fOut.flush();
m_fOut.close();
MediaStore.Images.Media.insertImage(getContentResolver(),
m_file.getAbsolutePath(),
m_file.getName(),
m_file.getName());
} catch (Exception p_e) {
}
if (requestCode == PICK_FROM_CAMERA) {
if (extras != null) {
// Bitmap photo = extras.getParcelable("data");
imgview.setImageBitmap(m_thePic);
}
}
if (requestCode == PICK_FROM_GALLERY) {
// Bundle extras2 = data.getExtras();
if (extras != null) {
imgview.setImageBitmap(m_thePic);
}
}
if (requestCode == PRESS_OK) {
Bundle extras11 = data.getExtras();
Bitmap bmp = (Bitmap) extras.get("data");
/*
* Bitmap photo = extras.getParcelable("data");
* imgview.setImageBitmap(photo); Intent n=new
* Intent(getApplicationContext(),ImageGalleryDemoActivity.class);
* n.putExtra("data",photo); startActivity(n);
*/
}
}
}
Here is a simple way for you to create minimum needed rect from an array of coordinates
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Rect r = getRect(new int[]{10, 10, 20, 20, 30, 30}, new int[]{20, 100, 10, 110, 20, 100});
System.out.println(r.left + " " + r.top + " " + r.bottom + " " + r.right);
}
public Rect getRect(int[] x, int y[]){
Rect r = new Rect();
// Set the first coordinate, in order not to include 0, 0
r.set(x[0], y[0], x[0], y[0]);
for(int i = 1; i < x.length; i++){
r.union(x[i], y[i]);
}
return r;
}
EDIT: look you have 8 points, just call this getRect like this
Rect rectToDraw = getRect(new int{yourx1, yourx2, yourx3, yourx4, yourx5, yourx6, yourx7, yourx8,}, new int{youry1, youry2, youry3, youry4, youry5, youry6, youry7, youry8});
You can pass this function ass many points you want, not just 8
Hope this helps and enjoy your work

Camera activity returning null android

I am building an application where I want to capture an image by the default camera activity and return back to my activity and load that image in a ImageView. The problem is camera activity always returning null. In my onActivityResult(int requestCode, int resultCode, Intent data) method I am getting data as null. Here is my code:
public class CameraCapture extends Activity {
protected boolean _taken = true;
File sdImageMainDirectory;
Uri outputFileUri;
protected static final String PHOTO_TAKEN = "photo_taken";
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.cameracapturedimage);
File root = new File(Environment
.getExternalStorageDirectory()
+ File.separator + "myDir" + File.separator);
root.mkdirs();
sdImageMainDirectory = new File(root, "myPicName");
startCameraActivity();
} catch (Exception e) {
finish();
Toast.makeText(this, "Error occured. Please try again later.",
Toast.LENGTH_SHORT).show();
}
}
protected void startCameraActivity() {
outputFileUri = Uri.fromFile(sdImageMainDirectory);
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE:
{
if(resultCode==Activity.RESULT_OK)
{
try{
ImageView imageView=(ImageView)findViewById(R.id.cameraImage);
imageView.setImageBitmap((Bitmap) data.getExtras().get("data"));
}
catch (Exception e) {
// TODO: handle exception
}
}
break;
}
default:
break;
}
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
if (savedInstanceState.getBoolean(CameraCapture.PHOTO_TAKEN)) {
_taken = true;
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putBoolean(CameraCapture.PHOTO_TAKEN, _taken);
}
}
Am I doing anything wrong?
You are getting wrong because you are doing it wrong way.
If you pass the extra parameter MediaStore.EXTRA_OUTPUT with the camera intent then camera activity will write the captured image to that path and it will not return the bitmap in the onActivityResult method.
If you will check the path which you are passing then you will know that actually camera had write the captured file in that path.
For further information you can follow this, this and this
I am doing it another way. The data.getData() field is not guaranteed to return a Uri, so I am checking if it's null or not, if it is then the image is in extras. So the code would be -
if(data.getData()==null){
bitmap = (Bitmap)data.getExtras().get("data");
}else{
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), data.getData());
}
I am using this code in the production application, and it's working.
I had a similar problem. I had commented out some lines in my manifest file which caused the thumbnail data to be returned as null.
You require the following to get this to work:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
I hope this resolves your issue
If you phone is a Samsung, it could be related to this http://kevinpotgieter.wordpress.com/2011/03/30/null-intent-passed-back-on-samsung-galaxy-tab/
There is another open question which may give additional information
If you are using an ImageView to display the Bitmap returned by Camera Intent
you need to save the imageview reference inside onSaveInstanceState and also restore it later on inside onRestoreInstanceState. Check out the code for onSaveInstanceState and onRestoreInstanceState below.
public class MainActivity extends Activity {
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 1;
String mCurrentPhotoPath;
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
imageView = (ImageView) findViewById(R.id.imageView1);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void startCamera(View v) throws IOException {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File photoFile = null;
photoFile = createImageFile();
//intent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(photoFile));
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE
&& resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
System.out.println(imageBitmap);
imageView.setImageBitmap(imageBitmap);
}
}
private File createImageFile() throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
System.out.println(mCurrentPhotoPath);
return image;
}
private void setPic() {
// Get the dimensions of the View
int targetW = imageView.getWidth();
int targetH = imageView.getHeight();
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(mCurrentPhotoPath, 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;
bmOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
imageView.setImageBitmap(bitmap);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
System.out.println(mCurrentPhotoPath);
imageView = (ImageView) findViewById(R.id.imageView1);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onRestoreInstanceState(savedInstanceState);
System.out.println(mCurrentPhotoPath);
imageView = (ImageView) findViewById(R.id.imageView1);
}
}
after many search :
private static final int TAKE_PHOTO_REQUEST = 1;
private ImageView mImageView;
String mCurrentPhotoPath;
private File photoFile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_saisir_frais);
mImageView = (ImageView) findViewById(R.id.imageViewPhoto);
dispatchTakePictureIntent();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == TAKE_PHOTO_REQUEST && resultCode == RESULT_OK) {
// set the dimensions of the image
int targetW =100;
int targetH = 100;
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(photoFile.getAbsolutePath(), 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;
bmOptions.inPurgeable = true;
// stream = getContentResolver().openInputStream(data.getData());
Bitmap bitmap = BitmapFactory.decodeFile(photoFile.getAbsolutePath(),bmOptions);
mImageView.setImageBitmap(bitmap);
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
return image;
}
private void dispatchTakePictureIntent() {
Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
try {
photoFile = createImageFile();
takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
startActivityForResult(takePhotoIntent, TAKE_PHOTO_REQUEST);
} catch (IOException e) {
e.printStackTrace();
}
}
Try following code
{
final String[] imageColumns = { MediaStore.Images.Media._ID,MediaStore.Images.Media.DATA };
final String imageOrderBy = MediaStore.Images.Media._ID + " DESC";
Cursor imageCursor = managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, imageColumns, null, null, imageOrderBy);
imageCursor.moveToFirst();
do {
String fullPath = imageCursor.getString(imageCursor.getColumnIndex(MediaStore.Images.Media.DATA));
if (fullPath.contains("DCIM")) {
//get bitmap from fullpath here.
return;
}
}
while (imageCursor.moveToNext());
While taking from camera few mobiles would return null. The below workaround will solve. Make sure to check data is null:
private int CAMERA_NEW = 2;
private String imgPath;
private void takePhotoFromCamera() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, setImageUri());
startActivityForResult(intent, CAMERA_NEW);
}
// to get the file path
private Uri setImageUri() {
// Store image in dcim
File file = new File(Environment.getExternalStorageDirectory() + "/DCIM/", "image" + new Date().getTime() + ".png");
Uri imgUri = Uri.fromFile(file);
this.imgPath = file.getAbsolutePath();
return imgUri;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_NEW) {
try {
Log.i("Crash","CAMERA_NEW");
if(data!=null &&(Bitmap) data.getExtras().get("data")!=null){
bitmap = (Bitmap) data.getExtras().get("data");
personImage.setImageBitmap(bitmap);
Utils.saveImage(bitmap, getActivity());
}else{
File f= new File(imgPath);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
options.inSampleSize= 4;
bitmap = BitmapFactory.decodeStream(new FileInputStream(f), null, options);
personImage.setImageBitmap(bitmap);
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getActivity(), "Failed!", Toast.LENGTH_SHORT).show();
}
}
You can generate bitmap from the file that you send to camera intent. Please use this code...
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
switch (requestCode) {
case CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE:
{
if(resultCode==Activity.RESULT_OK)
{
int orientation = getOrientationFromExif(sdImageMainDirectory);// get orientation that image taken
BitmapFactory.Options options = new BitmapFactory.Options();
InputStream is = null;
Matrix m = new Matrix();
m.postRotate(orientation);//rotate image
is = new FileInputStream(sdImageMainDirectory);
options.inSampleSize = 4 //(original_image_size/4);
Bitmap bitmap = BitmapFactory.decodeStream(is,null,options);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
bitmap.getHeight(), m, true);
// set bitmap to image view
//bitmap.recycle();
}
break;
}
default:
break;
}
}
private int getOrientationFromExif(String imagePath) {
int orientation = -1;
try {
ExifInterface exif = new ExifInterface(imagePath);
int exifOrientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
switch (exifOrientation) {
case ExifInterface.ORIENTATION_ROTATE_270:
orientation = 270;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
orientation = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_90:
orientation = 90;
break;
case ExifInterface.ORIENTATION_NORMAL:
orientation = 0;
break;
default:
break;
}
} catch (IOException e) {
//Log.e(LOG_TAG, "Unable to get image exif orientation", e);
}
return orientation;
}
File cameraFile = null;
public void openChooser() {
Intent pickIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraFile = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile));
String pickTitle = "Select or take a new Picture"; // Or get from strings.xml
Intent chooserIntent = Intent.createChooser(pickIntent, pickTitle);
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS,new Intent[]{takePhotoIntent});
startActivityForResult(chooserIntent, SELECT_PHOTO);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case SELECT_PHOTO:
if (resultCode == Activity.RESULT_OK) {
Uri selectedImage = data.getData();
if (selectedImage != null) {
//from gallery
} else if (cameraFile != null) {
//from camera
Uri cameraPictureUri = Uri.fromFile(cameraFile);
}
}
break;
}
}
Try this tutorial. It works for me and use permission as usual in manifesto & also
check permission
https://androidkennel.org/android-camera-access-tutorial/
After a lot of vigorous research I finally reached to a conclusion.
For doing this, you should save the image captured to the external storage.
And then,retrieve while uploading.
This way the image res doesnt degrade and you dont get NullPointerException too!
I have used timestamp to name the file so we get a unique filename everytime.
private void fileChooser2() {
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
Intent intent=new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File pictureDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
String pictureName=getPictureName();
fi=pictureName;
File imageFile=new File(pictureDirectory,pictureName);
Uri pictureUri = Uri.fromFile(imageFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT,pictureUri);
startActivityForResult(intent,PICK_IMAGE_REQUEST2);
}
Function to create a file name :
private String getPictureName() {
SimpleDateFormat adf=new SimpleDateFormat("yyyyMMdd_HHmmss");
String timestamp = adf.format(new Date());
return "The New image"+timestamp+".jpg";//give a unique string so that the imagename cant be overlapped with other apps'image formats
}
and the onActivityResult:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==PICK_IMAGE_REQUEST2 && resultCode==RESULT_OK )//&& data!=null && data.getData()!=null)
{
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading");
progressDialog.show();
Toast.makeText(getApplicationContext(),"2",Toast.LENGTH_SHORT).show();
File picDir=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File imageFile=new File(picDir.getAbsoluteFile(),fi);
filePath=Uri.fromFile(imageFile);
try {
}catch (Exception e)
{
e.printStackTrace();
}
StorageReference riversRef = storageReference.child(mAuth.getCurrentUser().getUid()+"/2");
riversRef.putFile(filePath)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), "File Uploaded ", Toast.LENGTH_LONG).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), exception.getMessage(), Toast.LENGTH_LONG).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
progressDialog.setMessage("Uploaded " + ((int) progress) + "%...");
}
});
Edit: give permissions for camera and to write and read from storage in your manifest.

Categories

Resources