I am working on a basic camera app. I can take a photo, and I can see it in my app. But I want to see my photo in gallery asynchronous. When restart the phone, I can see my photo in the gallery.
Sample code.
public class PhotosActivity extends Fragment implements View.OnClickListener {
private final int REQUEST_CODE = 100;
private Button fotobutton;
private ImageView foto_image;
private static final String IMAGE_DIRECTORY_NAME = "OlkunMustafa";
public static final int MEDIA_TYPE_IMAGE = 1;
private Uri fileUri;
// Directory name to store captured images and videos
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.photos_activity,container,false);
fotobutton = (Button) rootView.findViewById(R.id.fotobutton);
foto_image = (ImageView) rootView.findViewById(R.id.foto_image);
fotobutton.setOnClickListener(this);
return rootView;
}
#Override
public void onClick(View v) {
if( v == fotobutton) {
Intent photo_intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFile(MEDIA_TYPE_IMAGE);
photo_intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(photo_intent,100);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == getActivity().RESULT_OK)
{
BitmapFactory.Options options = new BitmapFactory.Options();
final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
options);
foto_image.setImageBitmap(bitmap);
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = getOutputMediaFile(MEDIA_TYPE_IMAGE);
mediaScanIntent.setData(contentUri);
getActivity().sendBroadcast(mediaScanIntent);
}
}
private static Uri getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStorageDirectory(),
IMAGE_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
+ IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
}
else {
return null;
}
return Uri.fromFile(mediaFile);
}
}
How can I do it?
You need to call a broadcast to tell Android OS that you have added an Image
First Method
private void galleryAddPic()
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
{
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File("file://"+ Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES));
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
else
{
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
}
}
Second Method
Or Call
ctx.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,Uri.parse("file://" + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES))));
Also have a look on this answer
you can use this method to store image file on media store provider:
public static void addImageToGallery(final String filePath, final Context context) {
ContentValues values = new ContentValues();
values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(Images.Media.MIME_TYPE, "image/jpeg");
values.put(MediaStore.MediaColumns.DATA, filePath);
context.getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI, values);
}
And ScanListener
You can directly save image to Gallery
MediaStore.Images.Media.insertImage(getContentResolver(), yourBitmap, yourTitle , yourDescription);
Try using this logic :
private static int TAKE_PICTURE = 1;
private Uri imageUri;
public void takePhoto(View view) {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
File photo = new File(Environment.getExternalStorageDirectory(), "Pic.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photo));
imageUri = Uri.fromFile(photo);
startActivityForResult(intent, TAKE_PICTURE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case TAKE_PICTURE:
if (resultCode == Activity.RESULT_OK) {
Uri selectedImage = imageUri;
getContentResolver().notifyChange(selectedImage, null);
ImageView imageView = (ImageView) findViewById(R.id.ImageView);
ContentResolver cr = getContentResolver();
Bitmap bitmap;
try {
bitmap = android.provider.MediaStore.Images.Media
.getBitmap(cr, selectedImage);
imageView.setImageBitmap(bitmap);
Toast.makeText(this, selectedImage.toString(),
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT)
.show();
Log.e("Camera", e.toString());
}
}
}
}
Related
I have an app in which I try to capture user images from camera and also from gallery. The image capture works fine and the image is visible in the ImageView but when I restart the app the image disappears as if it wasn't saved.
public class MainActivity extends AppCompatActivity {
ImageView imageView;
int REQUEST_CAMERA =1;
int SELECT_FILE = 0;
public String photoFileName;
File photoFile = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
imageView = findViewById(R.id.imageView);
final FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
selectImage();
}
});
}
public void selectImage(){
final CharSequence [] items = {"Camera","Gallery","Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Add Image");
builder.setItems(items, new DialogInterface.OnClickListener() {
#SuppressLint("IntentReset")
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if (items[i].equals("Camera")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,REQUEST_CAMERA);
try {
photoFile = createImageFile();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this,
"Photo file can't be created, please try again",
Toast.LENGTH_SHORT).show();
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(MainActivity.this,
"com.example.android.fileprovider",
photoFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
}
}else if (items[i].equals("Gallery")){
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(intent.createChooser(intent,"Select File"),SELECT_FILE);
galleryAddPic();
}else if (items[i].equals("Cancel")){
dialogInterface.dismiss();
}
}
});
builder.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CAMERA && resultCode == Activity.RESULT_OK){
Bundle bundle = null;
if (data != null) {
bundle = data.getExtras();
}
Bitmap bitmap = null;
if (bundle != null) {
bitmap = (Bitmap) bundle.get("data");
}
imageView.setImageBitmap(bitmap);
}else if (requestCode == SELECT_FILE){
Uri uri = data.getData();
imageView.setImageURI(uri);
}
}
private void galleryAddPic() {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(String.valueOf(photoFile));
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
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 = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
photoFileName = image.getAbsolutePath();
return image;
}
}
While restart the app image is not showing becuase of all variable initialize again, for showing that you have to store it path locally.
Hello everyone! I am using a camera which saves photo's in the phones gallery. But I don't want to save the photo in the gallery. I want to save it somewhere else. So all i need is not to save it automatically in the gallery.
This is my code:
public class MainActivity extends AppCompatActivity {
ImageView photo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button click = (Button)findViewById(R.id.btnPhoto);
photo = (ImageView) findViewById(R.id.imgPhoto);
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 0);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Bitmap bitmap = (Bitmap)data.getExtras().get("data");
photo.setImageBitmap(bitmap);
}
}
If my question is not good enough, please ask me! And please help me out.
This method for open camera and path is File declare global.
private void openCamera() {
Logger.i("openCamera");
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(this.getPackageManager()) != null) {
File rootPath = new File(Environment.getExternalStorageDirectory(), "folderName");
if (!rootPath.exists())
rootPath.mkdirs();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd-kk-mm-ss");
String snapshotImage = df.format(new Date()) + ".jpg";
rootPath = new File(rootPath + "/" + snapshotImage);
path = rootPath;
takePictureIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(path));
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
get result
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
FileOutputStream fos = null;
try {
// Float Latitude=0.0f, Longitude=0.0f;
imageDvr.setImageURI(Uri.parse(path.getAbsolutePath()));
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
}
}
}
}
}
}
and also give per\mission in manifest file
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
You will get the bitmap of image in onActivityResult(), and you will store that Image by bitmap.
Use below function to store image on your self made folder. you need to make that folder and need to use path of that.
like this.
public void SaveImage(Bitmap showedImgae){
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/YourSelfMadeFolder");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "FILENAME-"+ n +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
showedImgae.compress(Bitmap.CompressFormat.JPEG, 100, out);
Toast.makeText(activityname.this, "Image Saved", Toast.LENGTH_SHORT).show();
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(file);
mediaScanIntent.setData(contentUri);
getApplicationContext().sendBroadcast(mediaScanIntent);
}
You can add intent android.provider.MediaStore.EXTRA_OUTPUT with your URI:
private File getOutputMediaFile() {
File mediaStorageDir = null;
String state = Environment.getExternalStorageState();
if (state.contains(Environment.MEDIA_MOUNTED)) {
mediaStorageDir = new File(Environment
.getExternalStorageDirectory().toString() + "/yourFolderName");
} else {
mediaStorageDir = new File(Environment
.getExternalStorageDirectory().toString() + "/yourFolderName");
}
if (!mediaStorageDir.exists()) {
Logger.d("Desc", "File dir " + mediaStorageDir.mkdirs());
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"Image_" + timeStamp + ".jpg");
return mediaFile;
}
your button click:
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Uri mImageCaptureUri = null;
File mediaFile = getOutputMediaFile();
mImageCaptureUri = Uri.fromFile(mediaFile);
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
intent.putExtra("return-data", true);
this.startActivityForResult(intent, REQUEST_CODE_TAKE_PICTURE);
}}0;
on activity result:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d("FilePath","Path"+mediaFile.getAbsolutePath();)
}
I have followed and literally picked up code from other answers but its still not working.
When a picture is clicked, it's saved by default in DCIM/camera with name such as 20150910_111841.jpg (date_timeInMilliseconds) but I want to save it as "myName_date.jpg".
public void OnClick(){
if (items[item].equals("Take Photo")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
f = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
mMediaUri=Uri.fromFile(new File(f, "MEDIT"+System.currentTimeMillis()+"jpg"));
intent.putExtra(MediaStore.EXTRA_OUTPUT, mMediaUri);
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode==RESULT_OK){
switch(requestCode) {
case REQUEST_IMAGE_CAPTURE:
Bitmap bm = BitmapFactory.decodeFile(mMediaUri.getPath());
//imgVIew.setImageBitmap(bm);
Bitmap scaledBitmap=ScaleImage(bm);
final ByteArrayOutputStream bos = new ByteArrayOutputStream();
scaledBitmap.compress(Bitmap.CompressFormat.JPEG,100, bos);
//Bitmap decoded = BitmapFactory.decodeStream(new ByteArrayInputStream(bos.toByteArray()));
imgVIew.setImageBitmap(scaledBitmap);
imageView.setImage(ImageSource.bitmap(scaledBitmap));
imageView1.setImage(ImageSource.bitmap(bm));
break;
case REQUEST_GALLERY:
//Uri selectedImage = imageReturnedIntent.getData();
//imageview.setImageURI(selectedImage);
break;
}//Close switch statement
}else {
Log.d("Error ", "user canceled !");
}
}
I have not yet added code for the gallery part but that shouldn't be a problem. As of now no matter what I do its being saved as default but I realized if people don't have an SD card then it can cause an issue. I'd rather have this picture available, in the default DCIM location but with a custom name. Thanks!
Try the below code to save the image with the name you want:
/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type) {
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
/*
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyCameraApp");
*/
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DCIM), "the_name_of_directory");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("canberra trailpass", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE){
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"myName"+ timeStamp + ".jpg");
} else {
return null;
}
return mediaFile;
}
To use a custom name, replace this -
mMediaUri=Uri.fromFile(new File(f, "MEDIT"+System.currentTimeMillis()+"jpg"));
With this -
mMediaUri=Uri.fromFile(new File(f, "MEDIT"+"Your Custom Name"+System.currentTimeMillis()+"jpg"));
It will like, this
File fPath = getAlbumStorageDir("myName_date");
File f = new File(fPath, "myName_date" + Calendar.getInstance().getTimeInMillis() + ".jpg");
It's not a device problem,
as example my working code, i have achieve like this,
public static Uri getUri(String filePath) {
File media = new File(filePath);
Uri uri = Uri.fromFile(media);
return uri;
}
public static File getAlbumStorageDir(String albumName) {
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), albumName);
if (file.exists()) {
Log.d(LOGTAG, "storeage file exists");
}
if (!(file.mkdirs() || file.isDirectory())) {
Log.e(LOGTAG, "Directory not created");
}
return file;
}
public static class SaveImageTask extends AsyncTask<Bitmap, Void, String> {
private SaveImageListener listener;
public SaveImageTask(SaveImageListener listener) {
this.listener = listener;
}
#Override
protected String doInBackground(Bitmap... params) {
Bitmap bitmapToSave = params[0];
File fPath = getAlbumStorageDir("AppName");
File f = new File(fPath, "AppName" + Calendar.getInstance().getTimeInMillis() + ".jpg");
String filePath = null;
try {
FileOutputStream strm = new FileOutputStream(f);
bitmapToSave.compress(Bitmap.CompressFormat.JPEG, 100, strm);
strm.close();
filePath = f.getPath();
} catch (IOException e) {
e.printStackTrace();
}
return filePath;
}
#Override
protected void onPostExecute(String filePath) {
super.onPostExecute(filePath);
listener.onImageSaved(filePath);
}
interface SaveImageListener {
void onImageSaved(String filePath);
}
}
Uri mImageCaptureUri;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
mImageCaptureUri = Uri.fromFile(new File(Environment
.getExternalStorageDirectory(), "example.jpg"));
takePictureIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
mImageCaptureUri);
startActivityForResult(takePictureIntent, 1);
onActivityResult :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK) {
switch (requestCode) {
case 1:
if(mImageCaptureUri!=null) {
imageName = "";
Bitmap bitmap = getCameraImage(activity, mImageCaptureUri);
imgView.setImageBitmap(bitmap );
removeFile(mImageCaptureUri.getPath());
break;
}
}
}
get camera image :
public static Bitmap getCameraImage(Activity activity, Uri mImageCaptureUri){
if(mImageCaptureUri==null) {
return null;
} else {
activity.getContentResolver().notifyChange(mImageCaptureUri, null);
ContentResolver cr = activity.getContentResolver();
Bitmap bitmap = null;
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 6;
AssetFileDescriptor fileDescriptor =null;
fileDescriptor =
cr.openAssetFileDescriptor( mImageCaptureUri, "r");
bitmap
= BitmapFactory.decodeFileDescriptor(
fileDescriptor.getFileDescriptor(), null, options);
//bitmap = android.provider.MediaStore.Images.Media.getBitmap(cr, mImageCaptureUri);
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
}
I need to take a picture with the camera, save the picture, show in ImageView and when I click the Imageview show in fullscreen mode .
In the future will need to send the picture to the internet.
This is what I've done :
public void captureImage(View v) {
Intent camera_intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(camera_intent, CAMERA_PIC_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
imgView = (ImageView) findViewById(R.id.formRegister_picture);
imgView.setScaleType(ImageView.ScaleType.CENTER_CROP);
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode){
case CAMERA_PIC_REQUEST:
if(resultCode==RESULT_OK){
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
imgView.setImageBitmap(thumbnail);
}
}
}
You can invoke camera Activity by adding these lines in your code :
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
private static int RESULT_IMAGE_CLICK = 1;
cameraImageUri = getOutputMediaFileUri(1);
// set the image file name
intent.putExtra(MediaStore.EXTRA_OUTPUT, cameraImageUri);
startActivityForResult(intent, RESULT_IMAGE_CLICK);
Now create file Uri because in some android phones you will get null data in return
so here is the method to get the image URI :
/** Create a file Uri for saving an image or video */
private static Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type) {
// Check that the SDCard is mounted
File mediaStorageDir = new File(
Environment.getExternalStorageDirectory(), Environment.DIRECTORY_PICTURES);
// Create the storage directory(MyCameraVideo) if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.e("Item Attachment",
"Failed to create directory MyCameraVideo.");
return null;
}
}
java.util.Date date = new java.util.Date();
String timeStamp = getTimeStamp();
File mediaFile;
if (type == 1) {
// For unique video file name appending current timeStamp with file
// name
mediaFile = new File(mediaStorageDir.getPath() + File.separator +abc+ ".jpg");
} else {
return null;
}
return mediaFile;
}
For retrieving clicked image :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == RESULT_IMAGE_CLICK) {
// Here you have the ImagePath which you can set to you image view
Log.e("Image Name", cameraImageUri.getPath());
Bitmap myBitmap = BitmapFactory.decodeFile(cameraImageUri.getPath());
yourImageView.setImageBitmap(myBitmap);
// For further image Upload i suppose your method for image upload is UploadImage
File imageFile = new File(cameraImageUri.getPath());
uploadImage(imageFile);
}
}
}
Since there is no proper solution for this, I will put here what I have put together that is working and correct.
ImageButton takepic = (ImageButton) returnView.findViewById(R.id.takepic);
takepic.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) { Intent intent = new Intent();
addPhoto();
}
});
Android Manifest :
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.example.android.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths"></meta-data>
</provider>
Android Manifest again at the top :
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
External res/xml/file_paths.xml file:
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-files-path name="my_images" />
</paths>
CreateImageFile Function
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
storageDir = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
AddPhoto Function
private void addPhoto() {
// Camera.
final List<Intent> cameraIntents = new ArrayList<Intent>();
final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
final PackageManager packageManager = getActivity().getPackageManager();
final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
for(ResolveInfo res : listCam) {
final String packageName = res.activityInfo.packageName;
final Intent intent = new Intent(captureIntent);
intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
intent.setPackage(packageName);
intent.putExtra(MediaStore.MEDIA_IGNORE_FILENAME, ".nomedia");
cameraIntents.add(intent);
}
// Filesystem.
final Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
// Chooser of filesystem options.
final Intent chooserIntent = Intent.createChooser(galleryIntent, "profileimg");
// Add the camera options.
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[]{}));
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) {
Uri photoURI = FileProvider.getUriForFile(getContext(),
"com.example.android.fileprovider",
photoFile);
chooserIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(chooserIntent, 100);}
}
On activity callback
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100) {
try {
Bundle extras = data.getExtras();
Uri uri = data.getData();
ImageButton takepic = (ImageButton) returnView.findViewById(R.id.takepic);
if (extras!=null){
Bitmap imageBitmap = (Bitmap) extras.get("data");
Log.d(TAG, "onActivityResult: "+mCurrentPhotoPath);
takepic.setImageBitmap(imageBitmap);
}
String wholeID = DocumentsContract.getDocumentId(uri);
// Split at colon, use second item in the array
String idx = wholeID.split(":")[1];
String[] column = {MediaStore.Images.Media.DATA};
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = getContext().getContentResolver().
query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[]{idx}, null);
String filePath = "";
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
}
cursor.close();
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContext().getContentResolver(), uri);
takepic.setImageBitmap(bitmap);
Toast.makeText(getContext(), "Uploading In Progress",
Toast.LENGTH_LONG);
}catch(Exception e){
e.getMessage();
}
}}
Try this, to save image to file explorer:
public void captureImage(View v) {
Intent camera_intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(Environment.getExternalStorageDirectory(), "image.png");
camera_intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(camera_intent, CAMERA_PIC_REQUEST);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode== Activity.RESULT_OK){
f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("image.png")) {
f = temp;
imagePath= f.getAbsolutePath();
Bitmap thumbnail= BitmapFactory.decodeFile(f.getAbsolutePath(), options);
imgView.setImageBitmap(thumbnail);
}
You can fetch image from path "imagePath" whenever you have to display it.
I have a button, which opens up a dialog box asking user to either "Take Picture" or "Choose from gallery".
I am facing issues when user "Take photo" , image is getting clicked, and for verification purpose I am setting Bitmap image inside the circularImage view, but when I go to specified location path of the image, either Image is not there or Image is corrupted.
Also I am trying to upload the image to the server using AsyncHttpClient in android but not being able to do it successfully.
Everytime I am getting Java Socket TimeOut Exception.
Below is the code for my Camera Intent Activity
public class AddAnUpdateActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
this.composeEditText = (EditText) findViewById(R.id.composeEditText);
setContentView(R.layout.add_update);
ProfilePictureImage = (CircularImageView) findViewById(R.id.ProfilePic);
insertVideo = (ImageButton) findViewById(R.id.insertVideoButton);
setBtnListenerOrDisable(insertVideo,mTakeVidOnClickListener, MediaStore.ACTION_VIDEO_CAPTURE);
insertImage = (ImageButton) findViewById(R.id.insertImageButton);
insertImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
}
private void setBtnListenerOrDisable(ImageButton btn,
Button.OnClickListener onClickListener,
String intentName) {
if (isIntentAvailable(this, intentName)) {
btn.setOnClickListener(onClickListener);
} else {
btn.setClickable(false);
}
}
private 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 selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(AddAnUpdateActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(options,new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if(options[item].equals("Take Photo"))
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "Image.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
}
else if (options[item].equals("Choose from Gallery"))
{
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
}
else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#SuppressLint("Assert")
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory().toString());
Log.d("PhotoImage","file path:"+f);
Log.d("PhotoImage","list of file path:"+ Arrays.toString(f.listFiles()));
for (File temp : f.listFiles()) {
if (temp.getName().equals("Image.jpg")) {
Log.w("PhotoImage","enter in if block");
f = temp;
break;
}
}
try {
Log.w("PhotoImage","enter in else block");
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),bitmapOptions);
ProfilePictureImage.setImageBitmap(bitmap);
if(bitmap!=null)
{
bitmap.recycle();
bitmap=null;
}
String path = android.os.Environment.getExternalStorageDirectory()+ File.separator+ "Pictures" + File.separator + "Screenshots";
Log.w("PhotoImage","path where the image is stored :"+path);
setFilePath(path);
f.delete();
OutputStream outFile;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
Log.w("PhotoImage","file value:"+String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
outFile.flush();
outFile.close();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
setFilePath(picturePath);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
Log.d("PhotoImage path of image from gallery......******************.........", picturePath + "");
ProfilePictureImage.setImageBitmap(thumbnail);
}
else if(requestCode == 3){
handleCameraVideo(data) ;
}
}
}
private void handleCameraVideo(Intent data) {
VideoUri = data.getData();
VideoView.setVideoURI(VideoUri);
//mImageBitmap = null;
} }
private void startActivityFeedActivity() {
Intent i = new Intent(getApplicationContext(), ActivityFeedActivity.class);
startActivity(i);
}
}
I simplified your code .keep reference of file path global
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "Image.jpg");
globalpath =f.getAbsolutePath(); //String make it global
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
//your onactivityresult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
File myfile = new File(globalpath);
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(myfile.getAbsolutePath(),
bitmapOptions);
ProfilePictureImage.setImageBitmap(bitmap);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Pictures" + File.separator + "Screenshots";
OutputStream outFile;
File file = new File(path, String.valueOf(System
.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
outFile.flush();
outFile.close();
myfile.delete();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Depending on your Android version and device, the camera intent is to be implemented differently. Check out https://github.com/ralfgehrer/AndroidCameraUtil. The code is tested on 100+ devices.
After take the photo remember to use this:
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(myNewFile)));
to scan the media file in your gallery. If you doesn't do it your photo will appear after some time. You can do it in onClick:
insertImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(myNewFile)));
}
});