Saving image from app / camera - java

I have this code in MainActivity:
onCreate() :
mtestImage = (ImageView) findViewById(R.id.testImage);
mtestImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, RESULT_LOAD_IMAGE);
}
});
public void onActivityResult(int reqCode, int resCode, Intent data):
if (resCode == RESULT_OK) {
if (reqCode == 1) {
mtestImage.setImageURI(data.getData());
}
}
It works and ImageView shows me the picture that I opened, but if I restart Activity :
Intent intent = getIntent();
finish();
startActivity(intent);
The ImageView is restore default picture. How Can I save image that I took to work with it in future? (I'm trying to change BG of DrawerMenu with new pictures, that user can choose).
I founud some code in internet, but I'm not sure how I can combine it with my code:
private File createImageFile() throws IOException
{
String timeSnap = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeSnap + " ";
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
File image = File.createTempFile(imageFileName, ".jpg", storageDir);
return image;
}
THANK YOU!

Try this code.
private Uri getOutputMediaFile() {
File mediaStorageDir = new File(
Environment.getExternalStorageDirectory(), ".camerapics");
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
mediaStorageDir.mkdirs();
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
Uri uri = null;
if (mediaFile != null) {
uri = Uri.fromFile(mediaFile);
}
return uri;
}
mtestImage = (ImageView) findViewById(R.id.testImage);
mtestImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
fileUri = getOutputMediaFile();
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, RESULT_LOAD_IMAGE);
}
});
public void onActivityResult(int reqCode, int resCode, Intent data)
{
if (resCode == RESULT_OK) {
if (reqCode == RESULT_LOAD_IMAGE) {
Bitmap bmp = BitmapFactory.decodeStream(getContentResolver().openInputStream(fileUri));
mtestImage.setImageBitmap(bmp);
setUsername(this,fileUri.getPath());
}
}
}

Related

Android/Java: <input type="file" accept="image/*;capture=camera"> doesn't work anymore in WebView

How can I open the camera from a webview directly in html to take a picture or pick up a gallery photo with android? It seems that the
<input type="file" accept="image/*;capture=camera">
doesn't work anymore...
Here is my code:
main class:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
if (requestCode != INPUT_FILE_REQUEST_CODE || mFilePathCallback == null) {
super.onActivityResult(requestCode, resultCode, data);
return;
}
Uri[] results = null;
// Check that the response is a good one
if (resultCode == Activity.RESULT_OK) {
if (data == null) {
// If there is not data, then we may have taken a photo
if (mCameraPhotoPath != null) {
results = new Uri[]{Uri.parse(mCameraPhotoPath)};
}
} else {
String dataString = data.getDataString();
if (dataString != null) {
results = new Uri[]{Uri.parse(dataString)};
}
}
}
mFilePathCallback.onReceiveValue(results);
mFilePathCallback = null;
} else if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
if (requestCode != FILECHOOSER_RESULTCODE || mUploadMessage == null) {
super.onActivityResult(requestCode, resultCode, data);
return;
}
if (requestCode == FILECHOOSER_RESULTCODE) {
if (null == this.mUploadMessage) {
return;
}
Uri result = null;
try {
if (resultCode != RESULT_OK) {
result = null;
} else {
// retrieve from the private variable if the intent is null
result = data == null ? mCapturedImageURI : data.getData();
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "activity :" + e,
Toast.LENGTH_LONG).show();
}
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
}
return;
}
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 storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
// File storageDir = new File(LoginActivity.getAppContext().getFilesDir() + "/NTA/temp");
if (!storageDir.exists()) {
storageDir.mkdir();
}
File imageFile = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
return imageFile;
}
...
view = findViewById(R.id.vieweb);
view.getSettings().setJavaScriptEnabled(true);
view.getSettings().setAllowFileAccessFromFileURLs(true);
view.getSettings().setAllowUniversalAccessFromFileURLs(true);
view.getSettings().setAllowFileAccess(true);
view.getSettings().setPluginState(WebSettings.PluginState.ON);
view.getSettings().setAllowContentAccess(true);
view.getSettings().setBuiltInZoomControls(true);
view.getSettings().setDisplayZoomControls(false);
view.getSettings().setLoadWithOverviewMode(true);
view.getSettings().setUseWideViewPort(true);
view.getSettings().setDomStorageEnabled(true);
view.getSettings().setLoadWithOverviewMode(true);
view.getSettings().setSupportZoom(true);
view.getSettings().setDefaultTextEncodingName("utf-8");
view.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);
view.getSettings().setMediaPlaybackRequiresUserGesture(false);
view.getSettings().setAppCachePath(Environment.DIRECTORY_DOWNLOADS);
view.getSettings().setAppCacheEnabled(true);
view.getSettings().setSupportMultipleWindows(true);
view.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
view.addJavascriptInterface(new JavaScriptInterface(this), "Android");
view.getSettings().setJavaScriptEnabled(true);
view.getSettings().setDomStorageEnabled(true);
view.getSettings().setPluginState(WebSettings.PluginState.ON);
view.getSettings().setAppCacheEnabled(false);
view.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
view.getSettings().setUseWideViewPort(true);
view.getSettings().setLoadWithOverviewMode(true);
view.getSettings().setBuiltInZoomControls(false);
view.getSettings().setSupportZoom(false);
view.getSettings().setDefaultZoom(WebSettings.ZoomDensity.FAR);
view.getSettings().setDomStorageEnabled(true);
view.getSettings().setDatabaseEnabled(true);
bottomNavigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem Item) {
//put initialization to not initialize the bottom navigation bar
newBottomNav.updated = 0;
newBottomNav.initialization = 1;
view.loadUrl("file:///" + LoginActivity.getAppContext().getFilesDir() + "/NTA/APP/index.html?" + MenuMap.get(Item.toString()) + "&" + codeLangue);
return true;
}
});
//TEST BEGIN
view.getSettings().setJavaScriptEnabled(true);
view.getSettings().setPluginState(WebSettings.PluginState.OFF);
view.getSettings().setLoadWithOverviewMode(true);
view.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
view.getSettings().setUseWideViewPort(true);
view.getSettings().setUserAgentString("Android Mozilla/5.0 AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30");
view.getSettings().setAllowFileAccess(true);
view.getSettings().setAllowFileAccess(true);
view.getSettings().setAllowContentAccess(true);
view.getSettings().supportZoom();
view.loadUrl(url);
view.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// do your handling codes here, which url is the requested url
// probably you need to open that url rather than redirect:
if ( url.contains(".pdf")){
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(url), "application/pdf");
try{
view.getContext().startActivity(intent);
} catch (ActivityNotFoundException e) {
//user does not have a pdf viewer installed
}
} else {
view.loadUrl(url);
}
return false; // then it is not handled by default action
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Log.e("error",description);
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) { //show progressbar here
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url) {
//hide progressbar here
}
});
view.setWebChromeClient(new LocalNav.ChromeClient());
}
}
//TEST BEGIN
public class ChromeClient extends WebChromeClient {
// For Android 5.0
public boolean onShowFileChooser(WebView view, ValueCallback<Uri[]> filePath, WebChromeClient.FileChooserParams fileChooserParams) {
// Double check that we don't have any existing callbacks
if (mFilePathCallback != null) {
mFilePathCallback.onReceiveValue(null);
}
mFilePathCallback = filePath;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
} catch (IOException ex) {
// Error occurred while creating the File
Log.e("check", "Unable to create Image File", ex);
}
// Continue only if the File was successfully created
if (photoFile != null) {
mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
} else {
takePictureIntent = null;
}
}
Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
contentSelectionIntent.setType("image/*");
Intent[] intentArray;
if (takePictureIntent != null) {
intentArray = new Intent[]{takePictureIntent};
} else {
intentArray = new Intent[0];
}
Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);
return true;
}
// openFileChooser for Android 3.0+
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
mUploadMessage = uploadMsg;
// Create AndroidExampleFolder at sdcard
// Create AndroidExampleFolder at sdcard
String path = LoginActivity.getAppContext().getFilesDir() + "/NTA/temp";
//File storageDir = new File(path);
// File imageStorageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File imageStorageDir = new File(
getExternalFilesDir(Environment.DIRECTORY_PICTURES)
, "Temp");
if (!imageStorageDir.exists()) {
// Create AndroidExampleFolder at sdcard
imageStorageDir.mkdirs();
}
// Create camera captured image file path and name
File file = new File(
path + File.separator + "IMG_"
+ String.valueOf(System.currentTimeMillis())
+ ".jpg");
mCapturedImageURI = Uri.fromFile(file);
// Camera capture image intent
final Intent captureIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
// Create file chooser intent
Intent chooserIntent = Intent.createChooser(i, "Image Chooser");
// Set camera intent to file chooser
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS
, new Parcelable[] { captureIntent });
// On select image call onActivityResult method of activity
startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
}
// openFileChooser for Android < 3.0
public void openFileChooser(ValueCallback<Uri> uploadMsg) {
openFileChooser(uploadMsg, "");
}
//openFileChooser for other Android versions
public void openFileChooser(ValueCallback<Uri> uploadMsg,
String acceptType,
String capture) {
openFileChooser(uploadMsg, acceptType);
}
}
Thanks

How can I send video that I have recorded from one activity to another?

I am trying to send the video that I have recorded from one activity to another. I am thinking of sending the address but couldn't do so.
public void startRecordingVideo(View view) {
if (getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FRONT)) {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
File mediaFile = new File(
Environment.getExternalStorageDirectory().getAbsolutePath() + "/myvideo.mp4");
videoUri = Uri.fromFile(mediaFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, videoUri);
startActivityForResult(intent, VIDEO_CAPTURE);
} else {
Toast.makeText(this, "No camera on device", Toast.LENGTH_LONG).show();
}
}
public void convert(View view){
Intent i = new Intent(getApplicationContext(),convertVid.class);
File mediaFile = new File(
Environment.getExternalStorageDirectory().getAbsolutePath() + "/myvideo.mp4");
videoUri = Uri.fromFile(mediaFile);
i.putExtra("video1",videoUri);
startActivityForResult(i,1);
}
}

Cannot take picture or choose image from gallery

Sorry guys, I'm very new to android and now need to create a simple camera in my android studio.
When I choose an image from gallery or take a picture, it will crashed.
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View claims = inflater.inflate(R.layout.camera_main, container, false);
b=(Button)claims.findViewById(R.id.btnSelectPhoto);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
return claims;
}
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(Claims.this.getActivity());
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(), "temp.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();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity. RESULT_OK) {
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);
viewImage.setImageBitmap(bitmap);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Phoenix" + File.separator + "default";
f.delete();
OutputStream outFile = null;
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();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} 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 = getActivity().getContentResolver().query(selectedImage, filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
Log.w("path of image ", picturePath + "");
viewImage.setImageBitmap(thumbnail);
}
}
}
}
LogCat Error
java.lang.RuntimeException: Failure delivering result ResultInfo{who=android:fragment:0, request=2, result=-1, data=Intent { dat=content://com.sec.android.gallery3d.provider/picasa/item/5843197728949359042 (has extras) }} to activity {com.example.project.project/com.example.project.project.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.deliverResults(ActivityThread.java:3752)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3795)
Can someone explain to me why would this happen and how to fix it?
Thanks a lot :)
you can using this method
public class MainActivity extends AppCompatActivity {
private static final int IMAGE_REQUEST_CODE = 1;
private static final int CAMERA_REQUEST_CODE = 2;
private static final String IMG_FILE_NAME = "tempImg";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// From Gallery
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), IMAGE_REQUEST_CODE);
// Take a Picture
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = Uri.fromFile(GetOutputMediaFile());
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, CAMERA_REQUEST_CODE);
}
public static File GetOutputMediaFile() {
// External sdcard location
File mediaStorageDir = new File(
Environment.getExternalStorageDirectory() + "/" + HConstants.IMG_FILE_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
return null;
}
}
// Create a media file name
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ IMG_FILE_NAME + ".jpg");
return mediaFile;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK){
if(requestCode == IMAGE_REQUEST_CODE){
fileUri = data.getData();
Log.i(getClass().getName(), "fileUri" + fileUri);
}else{
Log.i(getClass().getName(), fileUri);
}
}
}
}
Getting Image from Gallery.
Try the following code.Hopefully it will work
public class ImageGalleryDemoActivity extends Activity {
private static int RESULT_LOAD_IMAGE = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button buttonLoadImage = (Button) findViewById(R.id.buttonLoadPicture);
buttonLoadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.imgView);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
}
Taking Picture
public class CameraDemoActivity extends Activity {
int TAKE_PHOTO_CODE = 0;
public static int count=0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//here,we are making a folder named picFolder to store pics taken by the camera using this application
final String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/picFolder/";
File newdir = new File(dir);
newdir.mkdirs();
Button capture = (Button) findViewById(R.id.btnCapture);
capture.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// here,counter will be incremented each time,and the picture taken by camera will be stored as 1.jpg,2.jpg and likewise.
count++;
String file = dir+count+".jpg";
File newfile = new File(file);
try {
newfile.createNewFile();
} catch (IOException e) {}
Uri outputFileUri = Uri.fromFile(newfile);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(cameraIntent, TAKE_PHOTO_CODE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == TAKE_PHOTO_CODE && resultCode == RESULT_OK) {
Log.d("CameraDemo", "Pic saved");
}
}
}
Also add the permissions in Manifest File:
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

save images in specific sdcard folder

file hase created and also display but it store in by default dcim folder
public class MainActivity extends Activity {
Button camera;
ImageView mImageView;
static final int REQUEST_TAKE_PHOTO = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
camera=(Button)findViewById(R.id.captureButton);
mImageView= (ImageView) findViewById(R.id.imageView);
camera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dispatchTakePictureIntent();
}
});
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
}
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
}
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
String mCurrentPhotoPath;
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,
".jpg",
storageDir
);
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
return image;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
mImageView.setImageBitmap(imageBitmap);
}
}
}
why storageDir folder has not created ? how can i create a folder ? and store images in particular folder give me some code which help me thanks in andvace
This worked for me.
File myDir=new File("/sdcard/folder_you_want_to_save_in");
myDir.mkdirs();
String fname = "JPEG_"+ timeStamp +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}

MediaStore.EXTRA_OUTPUT renders data null, other way to save photos?

Google offers this versatile code for taking photos via an intent:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// create Intent to take a picture and return control to the calling application
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); // create a file to save the image
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name
// start the image capture Intent
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
The problem is that if you're like me and you want to pass the photos as extras, using EXTRA_OUTPUT seemingly runs off with the photo data and makes subsequent actions think the intent data is null.
It appears this is a big bug with Android.
I'm trying to take a photo then display it as a thumbnail in a new view. I'd like to have it saved as a full sized image in the user's gallery. Does anyone know a way to specify the image location without using EXTRA_OUTPUT?
Here's what I have currently:
public void takePhoto(View view) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
// takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE);
}
/** 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 */
#SuppressLint("SimpleDateFormat")
private static File getOutputMediaFile(int type){
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "JoshuaTree");
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("JoshuaTree", "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 +
"IMG_"+ timeStamp + ".jpg");
} else {
return null;
}
return mediaFile;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
handleSmallCameraPhoto(data);
}
}
}
private void handleSmallCameraPhoto(Intent intent) {
Bundle extras = intent.getExtras();
mImageBitmap = (Bitmap) extras.get("data");
Intent displayIntent = new Intent(this, DisplayPhotoActivity.class);
displayIntent.putExtra("BitmapImage", mImageBitmap);
startActivity(displayIntent);
}
}
If you specified MediaStore.EXTRA_OUTPUT, the image taken will be written to that path, and no data will given to onActivityResult. You can read the image from what you specified.
See another solved same question here: Android Camera : data intent returns null
Basically, there are two ways to retrieve the image from Camera, if you use to send a captured image through intent extras you cannot retrieve it on ActivityResult on intent.getData() ' because it saves the image data through extras.
So the idea is:
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
And retrieving it on ActivityResults checking the retrieved intent:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (resultCode == RESULT_OK) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (intent.getData() != null) {
ParcelFileDescriptor parcelFileDescriptor = context.getContentResolver().openFileDescriptor(intent.getData(), "r"); 
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
parcelFileDescriptor.close();
} else {
Bitmap imageRetrieved = (Bitmap) intent.getExtras().get("data");
}
}
}
}
Here is how you can achieve what you want:
public void onClick(View v)
{
switch(v.getId())
{
case R.id.iBCamera:
File image = new File(appFolderCheckandCreate(), "img" + getTimeStamp() + ".jpg");
Uri uriSavedImage = Uri.fromFile(image);
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
i.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
i.putExtra("return-data", true);
startActivityForResult(i, CAMERA_RESULT);
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode)
{
case CAMERA_RESULT:
if(resultCode==RESULT_OK)
{
handleSmallCameraPhoto(uriSavedImage);
}
break;
}
}
private void handleSmallCameraPhoto(Uri uri)
{
Bitmap bmp=null;
try {
bmp = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
Intent displayIntent = new Intent(this, DisplayPhotoActivity.class);
displayIntent.putExtra("BitmapImage", bmp);
startActivity(displayIntent);
}
private String appFolderCheckandCreate(){
String appFolderPath="";
File externalStorage = Environment.getExternalStorageDirectory();
if (externalStorage.canWrite())
{
appFolderPath = externalStorage.getAbsolutePath() + "/MyApp";
File dir = new File(appFolderPath);
if (!dir.exists())
{
dir.mkdirs();
}
}
else
{
showToast(" Storage media not found or is full ! ");
}
return appFolderPath;
}
private String getTimeStamp() {
final long timestamp = new Date().getTime();
final Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(timestamp);
final String timeString = new SimpleDateFormat("HH_mm_ss_SSS").format(cal.getTime());
return timeString;
}
Edit:
Add these to Manifest:
Starting Api 19 and above READ_EXTERNAL_STORAGE should be declared explicitly
*<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />*
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
to you manifest.
Try this one android.provider.MediaStore.EXTRA_OUTPUT hope will solve your bug. The following code works for me:
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
I was facing same problem, every time getting null while retrieving data on other activity with getIntent().getData() then solved by writting complete android.provider.MediaStore.EXTRA_OUTPUT this solved my bug.

Categories

Resources