I use this code and MediaStore return me bitmapimage with small size.
How to use mediastore to get normal size of photo?
Someone help me solve the problem? Need some help to solve this problem. Need normal size of photo.
public class ActivityPhoto extends Activity implements OnClickListener{
File directory;
final int TYPE_PHOTO = 1;
final int REQUEST_CODE_PHOTO = 1;
ImageView imageViewPhoto;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.schedule_of_subject_photo);
createDirectory();
imageViewPhoto = (ImageView) findViewById(R.id.imageViewPhoto);
}
public void onClickPhoto(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, generateFileUri(TYPE_PHOTO));
startActivityForResult(intent, REQUEST_CODE_PHOTO);
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
if (requestCode == REQUEST_CODE_PHOTO) {
if (resultCode == RESULT_OK) {
if (intent == null) {
Log.d(TAG, "Intent is null");
} else {
Log.d(TAG, "Photo uri: " + intent.getData());
Bundle bndl = intent.getExtras();
if (bndl != null) {
Object obj = intent.getExtras().get("data");
if (obj instanceof Bitmap) {
Bitmap bitmap = (Bitmap) obj;
Log.d(TAG, "bitmap " + bitmap.getWidth() + " x " + bitmap.getHeight());
imageViewPhoto.setImageBitmap(bitmap);
}
}
}
} else if (resultCode == RESULT_CANCELED) {
Log.d(TAG, "Canceled");
}
}
}
private Uri generateFileUri(int type) {
File file = null;
switch (type) {
case TYPE_PHOTO:
file = new File(directory.getPath() + "/" + "photo_"
+ System.currentTimeMillis() + ".jpg");
break;
}
Log.d(TAG, "fileName = " + file);
return Uri.fromFile(file);
}
private void createDirectory() {
directory = new File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "MyFolder");
if (!directory.exists())
directory.mkdirs();
}
}
Looks like there's no way to get it from MediaStore.
As documentation for MediaStore.ACTION_IMAGE_CAPTURE says:
The caller may pass an extra EXTRA_OUTPUT to control where this image
will be written. If the EXTRA_OUTPUT is not present, then a small
sized image is returned as a Bitmap object in the extra field. This is
useful for applications that only need a small image. If the
EXTRA_OUTPUT is present, then the full-sized image will be written to
the Uri value of EXTRA_OUTPUT.
So, receiving smaller image (or no image at all as on my test device) is expected behavior. I think you need to decode image by yourself in order to get original dimensions. Like the following:
public class MyActivity extends Activity {
private static final String TAG = "MyActivity";
File directory;
final int TYPE_PHOTO = 1;
final int REQUEST_CODE_PHOTO = 1;
ImageView imageViewPhoto;
private Uri mFileUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
createDirectory();
imageViewPhoto = (ImageView) findViewById(R.id.imageViewPhoto);
}
#Override
public boolean onCreateOptionsMenu(final Menu menu) {
getMenuInflater().inflate(R.menu.action_bar, menu);
return true;
}
public void onClickPhoto(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
mFileUri = generateFileUri(TYPE_PHOTO);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mFileUri);
startActivityForResult(intent, REQUEST_CODE_PHOTO);
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
if (requestCode == REQUEST_CODE_PHOTO) {
if (resultCode == RESULT_OK) {
imageViewPhoto.setImageURI(mFileUri);
new SetPictureTask(getApplicationContext(), mFileUri, imageViewPhoto).execute();
} else if (resultCode == RESULT_CANCELED) {
Log.d(TAG, "Canceled");
}
}
}
private Uri generateFileUri(int type) {
File file = null;
switch (type) {
case TYPE_PHOTO:
file = new File(directory.getPath() + "/" + "photo_"
+ System.currentTimeMillis() + ".jpg");
break;
}
Log.d(TAG, "fileName = " + file);
return Uri.fromFile(file);
}
private void createDirectory() {
directory = new File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "MyFolder");
if (!directory.exists())
directory.mkdirs();
}
private static class SetPictureTask extends AsyncTask<Void, Void, Void> {
private final ImageView mImageView;
private final Uri mFileUri;
private final Context mContext;
private Bitmap mBitmap;
private int mWidth;
private int mHeight;
public SetPictureTask(final Context context, final Uri fileUri, final ImageView imageViewPhoto) {
mImageView = imageViewPhoto;
mFileUri = fileUri;
mContext = context;
}
#Override
protected Void doInBackground(final Void... params) {
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
BitmapFactory.decodeFile(mFileUri.getPath(), opts);
mWidth = opts.outWidth;
mHeight = opts.outHeight;
// required width for image in order to decode faster and consume less memory
final int scaleFactor = Math.min(mWidth / mImageView.getWidth(), mHeight / mImageView.getHeight());
opts.inJustDecodeBounds = false;
opts.inSampleSize = scaleFactor;
opts.inPurgeable = true;
mBitmap = BitmapFactory.decodeFile(mFileUri.getPath(), opts);
return null;
}
#Override
protected void onPostExecute(final Void aVoid) {
mImageView.setImageBitmap(mBitmap);
Toast.makeText(mContext, "Bitmap dimensions are (" + mWidth + " x " + mHeight + ")", Toast.LENGTH_LONG).show();
}
}
}
Please note added AsyncTask for getting dimensions and decoded Bitmap.
Related
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.
I'm using Google PhotoIntentActivity sample to implement the native Android camera in my app.
In this sample you click a button from the main activity (called PhotoIntentActivity), the camera is launched, you take a photo and then the photo is visualized in a ImageView placed always in the same activity.
Instead of staying there, I'd like to start an intent and visualize the photo in a new activity.
I can't understand where the photo is passed again in the main activity and where/how I should launch a new intent. This is the code:
public class PhotoIntentActivity extends Activity {
private static final int ACTION_TAKE_PHOTO = 1;
private static final String BITMAP_STORAGE_KEY = "viewbitmap";
private static final String IMAGEVIEW_VISIBILITY_STORAGE_KEY = "imageviewvisibility";
private ImageView mImageView;
private Bitmap mImageBitmap;
private static final String VIDEO_STORAGE_KEY = "viewvideo";
private static final String VIDEOVIEW_VISIBILITY_STORAGE_KEY = "videoviewvisibility";
private VideoView mVideoView;
private Uri mVideoUri;
private String mCurrentPhotoPath;
private static final String JPEG_FILE_PREFIX = "IMG_";
private static final String JPEG_FILE_SUFFIX = ".jpg";
private AlbumStorageDirFactory mAlbumStorageDirFactory = null;
/* Photo album for this application */
private String getAlbumName() {
return getString(R.string.album_name);
}
private File getAlbumDir() {
File storageDir = null;
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
storageDir = mAlbumStorageDirFactory.getAlbumStorageDir(getAlbumName());
if (storageDir != null) {
if (! storageDir.mkdirs()) {
if (! storageDir.exists()){
Log.d("CameraSample", "failed to create directory");
return null;
}
}
}
} else {
Log.v(getString(R.string.app_name), "External storage is not mounted READ/WRITE.");
}
return storageDir;
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = JPEG_FILE_PREFIX + timeStamp + "_";
File albumF = getAlbumDir();
File imageF = File.createTempFile(imageFileName, JPEG_FILE_SUFFIX, albumF);
return imageF;
}
private File setUpPhotoFile() throws IOException {
File f = createImageFile();
mCurrentPhotoPath = f.getAbsolutePath();
return f;
}
private void setPic() {
/* There isn't enough memory to open up more than a couple camera photos */
/* So pre-scale the target bitmap into which the file is decoded */
/* Get the size of the ImageView */
int targetW = mImageView.getWidth();
int targetH = mImageView.getHeight();
/* Get the size of the image */
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
/* Figure out which way needs to be reduced less */
int scaleFactor = 1;
if ((targetW > 0) || (targetH > 0)) {
scaleFactor = Math.min(photoW/targetW, photoH/targetH);
}
/* Set bitmap options to scale the image decode target */
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
/* Decode the JPEG file into a Bitmap */
Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
/* Associate the Bitmap to the ImageView */
mImageView.setImageBitmap(bitmap);
mVideoUri = null;
mImageView.setVisibility(View.VISIBLE);
mVideoView.setVisibility(View.INVISIBLE);
}
private void galleryAddPic() {
Intent mediaScanIntent = new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE");
File f = new File(mCurrentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
private void dispatchTakePictureIntent(int actionCode) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
switch(actionCode) {
case ACTION_TAKE_PHOTO:
File f = null;
try {
f = setUpPhotoFile();
mCurrentPhotoPath = f.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
} catch (IOException e) {
e.printStackTrace();
f = null;
mCurrentPhotoPath = null;
}
break;
default:
break;
} // switch
startActivityForResult(takePictureIntent, actionCode);
}
private void handleBigCameraPhoto() {
if (mCurrentPhotoPath != null) {
setPic();
galleryAddPic();
mCurrentPhotoPath = null;
}
}
private void handleCameraVideo(Intent intent) {
mVideoUri = intent.getData();
mVideoView.setVideoURI(mVideoUri);
mImageBitmap = null;
mVideoView.setVisibility(View.VISIBLE);
mImageView.setVisibility(View.INVISIBLE);
}
Button.OnClickListener mTakePicOnClickListener =
new Button.OnClickListener() {
#Override
public void onClick(View v) {
dispatchTakePictureIntent(ACTION_TAKE_PHOTO);
}
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mImageView = (ImageView) findViewById(R.id.imageView1);
mVideoView = (VideoView) findViewById(R.id.videoView1);
mImageBitmap = null;
mVideoUri = null;
Button picBtn = (Button) findViewById(R.id.btnIntend);
setBtnListenerOrDisable(
picBtn,
mTakePicOnClickListener,
MediaStore.ACTION_IMAGE_CAPTURE
);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
mAlbumStorageDirFactory = new FroyoAlbumDirFactory();
} else {
mAlbumStorageDirFactory = new BaseAlbumDirFactory();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case ACTION_TAKE_PHOTO: {
if (resultCode == RESULT_OK) {
handleBigCameraPhoto();
}
break;
} // ACTION_TAKE_PHOTO
} // switch
}
// Some lifecycle callbacks so that the image can survive orientation change
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putParcelable(BITMAP_STORAGE_KEY, mImageBitmap);
outState.putParcelable(VIDEO_STORAGE_KEY, mVideoUri);
outState.putBoolean(IMAGEVIEW_VISIBILITY_STORAGE_KEY, (mImageBitmap != null) );
outState.putBoolean(VIDEOVIEW_VISIBILITY_STORAGE_KEY, (mVideoUri != null) );
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mImageBitmap = savedInstanceState.getParcelable(BITMAP_STORAGE_KEY);
mVideoUri = savedInstanceState.getParcelable(VIDEO_STORAGE_KEY);
mImageView.setImageBitmap(mImageBitmap);
mImageView.setVisibility(
savedInstanceState.getBoolean(IMAGEVIEW_VISIBILITY_STORAGE_KEY) ?
ImageView.VISIBLE : ImageView.INVISIBLE
);
mVideoView.setVideoURI(mVideoUri);
mVideoView.setVisibility(
savedInstanceState.getBoolean(VIDEOVIEW_VISIBILITY_STORAGE_KEY) ?
ImageView.VISIBLE : ImageView.INVISIBLE
);
}
/**
* Indicates whether the specified action can be used as an intent. This
* method queries the package manager for installed packages that can
* respond to an intent with the specified action. If no suitable package is
* found, this method returns false.
* http://android-developers.blogspot.com/2009/01/can-i-use-this-intent.html
*
* #param context The application's environment.
* #param action The Intent action to check for availability.
*
* #return True if an Intent with the specified action can be sent and
* responded to, false otherwise.
*/
public static boolean isIntentAvailable(Context context, String action) {
final PackageManager packageManager = context.getPackageManager();
final Intent intent = new Intent(action);
List<ResolveInfo> list =
packageManager.queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
}
private void setBtnListenerOrDisable(
Button btn,
Button.OnClickListener onClickListener,
String intentName
) {
if (isIntentAvailable(this, intentName)) {
btn.setOnClickListener(onClickListener);
} else {
btn.setText(
getText(R.string.cannot).toString() + " " + btn.getText());
btn.setClickable(false);
}
}
}
Can anyone please help me?
Thanks
The file is saved to the path you get from the your createImageFile() method, which is saved as mCurrentPhotoPath. You can retrieve the photo from this path at any time, as you do in setPic() with BitmapFactory.decodeFile(). Therefore, to view the image in a new Activity, you just have to pass that path to the Intent in onActivityResult():
Intent intent = new Intent(this, ViewActivity.class);
intent.setData(Uri.parse(mCurrentPhotoPath));
startActivity(intent);
Then you can retrieve this path in the new Activity:
String photoPath = getIntent().getData().toString();
I have been stuck on this problem for a while now.
I am trying to take a picture with the Camera and save the full size picture directly into the internal memory.
I can save to the external storage without a glitch, but for some reason I cannot get it to work for the internal memory.
The solution below ONLY saves the small picture returned by the data object, and not the full-size picture.
It seems that the camera does not retrieve the full size picture, or that when I use file functions (new File, FileOutputStream...), Android is not retrieving the image from the camera Intent (shows a blank image).
I read all the forums, tutorials and tried different ways of achieving this, but I have not found the answer. I can't be the only one trying to do this.
Could you please help me with this problem?
Thanks!
Here is my code:
public class AddItem extends Fragment {
ListCell cell = new ListCell();
View view;
private Bitmap mImageBitmap;
protected myCamera cameraObject = null;
private Button saveBtn;
private Button cancelBtn;
DBSchema dbSchema;
protected boolean bdisplaymessage;
protected boolean ExternalStorage = false;
public AddItem(){
}
private class ListCell{
private EditText total;
private ImageView mImageView;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View rootView = inflater.inflate(R.layout.add_item, container,
false);
saveBtn = (Button) rootView.findViewById(R.id.SaveItem);
cancelBtn = (Button) rootView.findViewById(R.id.CancelItem);
cameraObject = new myCamera();
cell.total = (EditText) rootView.findViewById(R.id.item_total_Value);
cell.mImageView = (ImageView) rootView.findViewById(R.id.item_logo);
cell.mImageView.setImageResource(R.drawable.camera_icon);
cell.mImageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dispatchTakePictureIntent();
}
});
saveBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//save item to internal db
//get names of columns from db
bdisplaymessage = true;
dbSchema = new DBSchema();
Transaction transac = dbSchema.new Transaction();
Context context = getActivity().getApplicationContext();
//put values in content values
ContentValues values = new ContentValues();
values.put(transac.Total,cell.total.getText().toString());
StatusData statusData = ((MyFunctions) getActivity().getApplication()).statusData;
long nInsert = 0;
nInsert = statusData.insert(values,dbSchema.table_transaction);
if(nInsert!=0){
Toast.makeText(context, "inserted " + nInsert , Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(context, "not inserted " + nInsert , Toast.LENGTH_LONG).show();
}
}
});
cancelBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//redirect to home page
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container, new LoadMenu()).commit();
}
});
return rootView;
}
// Some lifecycle callbacks so that the image can survive orientation change
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putParcelable(cameraObject.BITMAP_STORAGE_KEY, mImageBitmap);
outState.putBoolean(cameraObject.IMAGEVIEW_VISIBILITY_STORAGE_KEY, (mImageBitmap != null) );
super.onSaveInstanceState(outState);
}
//take picture
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//takePictureIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
String mCurrentPhotoPath;
File f = null;
try {
//create image
f = cameraObject.setUpPhotoFile(getResources().getString(R.string.album_name),ExternalStorage, getActivity().getApplicationContext());
cameraObject.setCurrentPath(f.getAbsolutePath());
Log.d("uri_fromfile",Uri.fromFile(f).toString());
//uncomment the line below when ExternalStorage=true
//takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
} catch (IOException e) {
e.printStackTrace();
f = null;
mCurrentPhotoPath = null;
}
startActivityForResult(takePictureIntent, cameraObject.CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
#Override
public void onActivityResult(int requestcode, int resultCode, Intent data) {
if (requestcode == cameraObject.CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE && resultCode == getActivity().RESULT_OK) {
handleCameraPhoto(data);
}
}
private void handleCameraPhoto(Intent data) {
setPic(data);
galleryAddPic();
}
private void setPic(Intent data) {
/* There isn't enough memory to open up more than a couple camera photos */
/* So pre-scale the target bitmap into which the file is decoded */
/* Get the size of the ImageView */
int targetW = cell.mImageView.getWidth();
int targetH = cell.mImageView.getHeight();
/* Get the size of the image */
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(cameraObject.getCurrentPath(), bmOptions);
Log.d("image_path",cameraObject.getCurrentPath());
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
/* Figure out which way needs to be reduced less */
int scaleFactor = 1;
if ((targetW > 0) || (targetH > 0)) {
scaleFactor = Math.min(photoW/targetW, photoH/targetH);
}
/* Set bitmap options to scale the image decode target */
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
/* Decode the JPEG file into a Bitmap */
Bitmap bitmap = null;
if(ExternalStorage){
bitmap = BitmapFactory.decodeFile(cameraObject.getCurrentPath(), bmOptions);
}
else{
File internalStorage = getActivity().getApplicationContext().getDir("imageDir", Context.MODE_PRIVATE);
File reportFilePath = new File(internalStorage, cameraObject.JPEG_FILE_PREFIX +"hello" + ".jpg");
String picturePath = reportFilePath.toString();
FileOutputStream fos = null;
try {
fos = new FileOutputStream(reportFilePath);
bitmap = (Bitmap) data.getExtras().get("data");
bitmap.compress(Bitmap.CompressFormat.PNG, 100 /*quality*/, fos);
fos.close();
}
catch (Exception ex) {
Log.i("DATABASE", "Problem updating picture", ex);
picturePath = "";
}
/* below is a bunch of options that I tried with decodefile, FileOutputStream... none seems to work */
//File out = new File(getActivity().getApplicationContext().getFilesDir(),cameraObject.JPEG_FILE_PREFIX + "hello");
//bitmap = BitmapFactory.decodeFile(out.getAbsolutePath());
//FileOutputStream fos = null;
//try {
//fos = new FileOutputStream(new File(getActivity().getApplicationContext().getFilesDir(),"/" + cameraObject.JPEG_FILE_PREFIX + "hello" + cameraObject.JPEG_FILE_SUFFIX).getAbsolutePath());
//bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
// Use the compress method on the BitMap object to write image to the OutputStream
//fos.close();
//Bitmap bitmap = null;
/*try{
FileInputStream fis = new FileInputStream(new File(getActivity().getApplicationContext().getFilesDir(),"/" + cameraObject.JPEG_FILE_PREFIX + "hello" + cameraObject.JPEG_FILE_SUFFIX).getAbsolutePath());
//getActivity().getApplicationContext().openFileInput(cameraObject.getCurrentPath());
bitmap = BitmapFactory.decodeStream(fis);
//
fis.close();
}
catch(Exception e){
Log.d("what?",e.getMessage());
bitmap = null;
}*/
/*} catch (Exception e) {
e.printStackTrace();
}*/
/*File mypath=new File(getActivity().getApplicationContext().getFilesDir(),"/" + cameraObject.JPEG_FILE_PREFIX + "hello" + cameraObject.JPEG_FILE_SUFFIX);
bitmap = BitmapFactory.decodeFile(mypath.getAbsolutePath());*/
//bitmap = (Bitmap) data.getExtras().get("data");
}
/* Associate the Bitmap to the ImageView */
cell.mImageView.setImageBitmap(bitmap);
cell.mImageView.setVisibility(View.VISIBLE);
}
private void galleryAddPic() {
Intent mediaScanIntent = new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE");
File f = new File(cameraObject.mCurrentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
getActivity().sendBroadcast(mediaScanIntent);
}
}
My other class called myCamera handles the camera:
public class myCamera extends MainMenu{
private ImageView mImageView;
private Bitmap mImageBitmap;
static final String BITMAP_STORAGE_KEY = "viewbitmap";
static final String IMAGEVIEW_VISIBILITY_STORAGE_KEY = "imageviewvisibility";
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
protected static final int ACTION_TAKE_PHOTO_B = 1;
protected static final int ACTION_TAKE_PHOTO_S = 2;
protected int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = MEDIA_TYPE_IMAGE;
protected Uri fileUri;
protected String mCurrentPhotoPath;
protected static final String JPEG_FILE_PREFIX = "IMG_";
protected static final String JPEG_FILE_SUFFIX = ".jpg";
private static final String CAMERA_DIR = "/dcim/";
protected String mAlbumName;
protected AlbumStorageDirFactory mAlbumStorageDirFactory = null;
protected String getAlbumName() {
return "test";
}
protected String getCurrentPath(){
return mCurrentPhotoPath;
}
protected void setCurrentPath(String mCurrentPhotoPath){
this.mCurrentPhotoPath=mCurrentPhotoPath;
}
public File getAlbumStorageDir(String albumName) {
return new File (
Environment.getExternalStorageDirectory()
+ CAMERA_DIR
+ albumName
);
}
private File getAlbumDir() {
File storageDir = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
mAlbumStorageDirFactory = new FroyoAlbumDirFactory();
} else {
mAlbumStorageDirFactory = new BaseAlbumDirFactory();
}
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
storageDir = getAlbumStorageDir(getAlbumName());
if (storageDir != null) {
if (! storageDir.mkdirs()) {
if (! storageDir.exists()){
Log.d("CameraSample", "failed to create directory");
return null;
}
}
}
} else {
Log.v(getString(R.string.app_name), "External storage is not mounted READ/WRITE.");
}
return storageDir;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.base_for_drawer);
mAlbumName = getIntent().getStringExtra("AlbumName");
}
public myCamera(){
}
//save full size picture
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = JPEG_FILE_PREFIX + timeStamp + "_";
File storageDir = getAlbumDir();
File image = File.createTempFile(imageFileName,JPEG_FILE_SUFFIX, storageDir);
return image;
}
protected File setUpPhotoFile(String albumName, boolean ExternalStorage, Context context) throws IOException {
mAlbumName = albumName;
File f =null;
if(ExternalStorage){
f = createImageFile();
}
else{
f = saveToInternalSorage(context);
}
// Save a file: path for use with ACTION_VIEW intents
if(f !=null){
mCurrentPhotoPath = f.getAbsolutePath();
}
return f;
}
private File saveToInternalSorage(Context context) throws IOException{
ContextWrapper cw = new ContextWrapper(context);
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = JPEG_FILE_PREFIX + "hello";
// path to /data/data/yourapp/app_data/imageDir
File directory = context.getDir("imageDir", Context.MODE_PRIVATE);
File mypath=new File(directory,imageFileName + JPEG_FILE_SUFFIX);
/*below is a bunch of options that I tried*/
//File directory =context.getFilesDir();
//File directory = new File(getFilesDir(),imageFileName,Context.MODE_PRIVATE);
// Create imageDir
//File image = File.createTempFile(imageFileName,JPEG_FILE_SUFFIX, storageDir);
//File mypath = File.createTempFile(imageFileName,JPEG_FILE_SUFFIX, directory);
//return image;
return mypath;
}
}
I found the solution! I did not use the native camera application, but rather created my own camera class and use the data sent back by the camera via a callback. Works smoothly!
I am having a NullPointerException in my android code on this section
String title = titleEt.getText().toString();
String description = descriptionEt.getText().toString();
Log.i("title",title);
Log.i("description",description);
audioRecordPasser.onAudioRecordPass(title, "hiphop", description, fileUri.getPath());
getDialog().dismiss();
The exception is on the line
audioRecordPasser.onAudioRecordPass(title, "hiphop", description, fileUri.getPath());
audioRecordPasser is an interface.
The complete code implementation is
public class UploadFragment extends DialogFragment implements AdapterView.OnItemSelectedListener, View.OnClickListener {
Spinner genres;
ImageView photo;
TextView submit;
String fileName = "";
EditText titleEt, descriptionEt;
private static final String KEY = "choice";
public Uri fileUri; // file url to store image/video
OnAudioRecordPass audioRecordPasser;
public UploadFragment(){
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
View v = inflater.inflate(R.layout.fragment_upload, null);
builder.setView(v);
submit = (TextView) v.findViewById(R.id.upload_textView_submit);
genres = (Spinner) v.findViewById(R.id.upload_spinner_genre);
photo = (ImageView) v.findViewById(R.id.upload_imageView_photo);
titleEt = (EditText) v.findViewById(R.id.upload_edittext_title);
descriptionEt = (EditText) v.findViewById(R.id.upload_editText_description);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getActivity(),
R.layout.ngoma_spinner, getResources().getStringArray(R.array.genres));
dataAdapter
.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
genres.setAdapter(dataAdapter);
genres.setOnItemSelectedListener(this);
submit.setOnClickListener(this);
photo.setOnClickListener(this);
return builder.create();
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
private static final int INT_CODE = 1;
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.upload_textView_submit:
Log.i("URI", fileUri.getPath());
// audioRecordPasser.onAudioRecordPass(titleEt.getText().toString(),"hiphop",descriptionEt.getText().toString(),fileUri.getPath());
if (validateInput()==false){
Toast.makeText(getActivity(),"Fields cannot be blank.",Toast.LENGTH_SHORT).show();
}
else {
String title = titleEt.getText().toString();
String description = descriptionEt.getText().toString();
Log.i("title",title);
Log.i("description",description);
audioRecordPasser.onAudioRecordPass(title, "hiphop", description, fileUri.getPath());
getDialog().dismiss();
}
break;
case R.id.upload_imageView_photo:
UploadPhotoDialog uploadDialog = new UploadPhotoDialog();
uploadDialog.setTargetFragment(this, INT_CODE);
uploadDialog.show(getActivity().getSupportFragmentManager(), "uploadPhoto");
break;
}
}
/**
* **************************************************************************************************
*/
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
public static final int MEDIA_TYPE_IMAGE = 1;
private static int RESULT_LOAD_IMAGE = 1;
/**
* Select image from gallery
*/
private void selectFromGallery() {
Intent i = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
/**
* Capturing Camera Image will lauch camera app requrest image capture
*/
private void captureImage() {
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);
}
/**
* Here we store the file url as it will be null after returning from camera
* app
*/
// directory name to store captured images and videos
private static final String IMAGE_DIRECTORY_NAME = "ngoma";
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// save file url in bundle as it will be null on screen orientation
// changes
outState.putParcelable("file_uri", fileUri);
}
/*
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// get the file url
fileUri = savedInstanceState.getParcelable("file_uri");
}*/
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// get the file url
//fileUri = savedInstanceState.getParcelable("file_uri");
}
/**
* Receiving activity result method will be called after closing the camera
*/
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if the result is capturing Image
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
// successfully captured the image
// display it in image view
previewCapturedImage();
} else if (resultCode == Activity.RESULT_CANCELED) {
// user cancelled Image capture
Toast.makeText(getActivity().getApplicationContext(),
"User cancelled image capture", Toast.LENGTH_SHORT)
.show();
} else {
// failed to capture image
Toast.makeText(getActivity().getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
} else if (requestCode == RESULT_LOAD_IMAGE && resultCode == Activity.RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
fileUri = selectedImage;
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
// String picturePath contains the path of selected Image
previewFromGallery(picturePath);
}
}
/**
* Display image from a path to ImageView
*/
private void previewCapturedImage() {
try {
// bimatp factory
BitmapFactory.Options options = new BitmapFactory.Options();
// downsizing image as it throws OutOfMemory Exception for larger
// images
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
options);
Log.i("previewCapturedImage", fileUri.getPath());
photo.setImageBitmap(bitmap);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
private void previewFromGallery(String picturePath) {
photo.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
/**
* ------------ Helper Methods ----------------------
* */
/**
* Creating file uri to store image/video
*/
public Uri getOutputMediaFileUri(int type) {
fileUri = Uri.fromFile(getOutputMediaFile(type));
Log.i("getOutputMediaFileUri", fileUri.getPath());
return fileUri;
}
/**
* returning image / video
*/
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! Error creating "
+ IMAGE_DIRECTORY_NAME + " directory.");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else {
return null;
}
return mediaFile;
}
public void choiceSelector(String data) {
if (data.equalsIgnoreCase("camera")) {
captureImage();
} else if (data.equalsIgnoreCase("gallery")) {
selectFromGallery();
}
}
public interface OnAudioRecordPass {
public void onAudioRecordPass(String title, String genre, String description, String photouri);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
audioRecordPasser = (OnAudioRecordPass) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnAudioRecordPass");
}
}
private boolean validateInput() {
if (titleEt.getText().toString().equalsIgnoreCase("") || descriptionEt.getText().toString().equalsIgnoreCase("")) {
return false;
} else {
return true;
}
}
}
Everything runs fine.In my logcat, I can see the values of title and desription and fileUri.getPath() variables.What could be the issue?
The logcat content
10-31 15:42:44.032 4101-4101/ngoma.android.shimba.com.ngoma E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.shimba.android.ngoma.activities.MainActivity.onAudioRecordPass(MainActivity.java:516)
at com.shimba.android.ngoma.fragments.UploadFragment.onClick(UploadFragment.java:101)
at android.view.View.performClick(View.java:3511)
at android.view.View$PerformClick.run(View.java:14105)
at android.os.Handler.handleCallback(Handler.java:605)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4440)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:787)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:554)
at dalvik.system.NativeStart.main(Native Method)
The problem is with the parameter fileUri.getPath()
May be this is not properly initialized and as a result its value is null
Check the value of fileUri variable value before passing it to the function.
This will solve your problem
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.