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();
}
Related
This is my code for camera(i am using File Provider)
This is MainActivityMainActivity.java MainActivity.java
This is my display ActivityDisplayActivity.java
Plz help i tried so may codes and make projects again and again.
I am trying to get high quality image from the camera and display it on the imageview.
Here was an demo that can help with your project...
On Button Click...
//photoFile is global variable File photoFile = null;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
try {
photoFile = createImageFile();
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".provider", photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, 501);
}
} catch (Exception e) {
e.printStackTrace();
}
Put this method in your class
private File createImageFile() throws IOException {
long timeStamp = Calendar.getInstance().getTimeInMillis();
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
return image;
}
Get Result from camera
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case 501:
if (photoFile != null) {
bitmap = BitmapFactory.decodeFile(photoFile.getAbsolutePath());
if (bitmap != null) {
// you got bitmap here
}
}
break;
}
}
super.onActivityResult(requestCode, resultCode, data);
}
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
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());
}
}
}
I made a class(ShowPhoto.java) which can make and save a photo. But nothing is happening when I click the "V" in my photo maker. So it makes the photo, but when you verify the photo, the app gives an error. When I press this button, the app should save the photo. Any idea what I forgot to add in my code?
package com.example.photoviewer;
//imports here
public class FotoMaker extends Activity
{
private static final String LOG_TAG = "debugger";
ImageView iv;
// Uri uriOfPicture;
static final int REQUEST_TAKE_PHOTO = 1;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.add_pic);
iv = (ImageView) findViewById(R.id.imageView);
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick (View v){
dispatchTakePictureIntent();
Log.i(LOG_TAG, "test5");
}
});
}
#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");
iv.setImageBitmap(imageBitmap);
}
}
String mCurrentPhotoPath;
private File createImageFile() throws IOException {
Log.i(LOG_TAG, "test3");
// 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 takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
Log.i(LOG_TAG, "test");
} catch (IOException ex) {
// Error occurred while creating the File
ex.printStackTrace();
Log.i(LOG_TAG, "test1");
}
// Continue only if the File was successfully created
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
Log.i(LOG_TAG, "test2");
}
}Log.i(LOG_TAG, "test4");
}
}
LogCat:
11-17 21:12:39.960: E/AndroidRuntime(15260): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=null} to activity {com.example.keyfinder/com.example.photoviewer.FotoMaker}: java.lang.NullPointerException
11-17 21:12:39.960: E/AndroidRuntime(15260): at com.example.photoviewer.FotoMaker.onActivityResult(FotoMaker.java:61)
I currently have a MainActitivty.java and want to make a PhotoActitivty.java to clean it up and allow for every button or action to have its own class. For some reason my new PhotoActivity class won't open up the camera intent.
I have something like this:
public class MainActivity extends AppCompatActivity {
private Button firstPictureButton;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= 23) {
requestPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 2);
}
firstPictureButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getApplicationContext(), PhotoActivity.class));
}
});
}
}
I started a new class and called it PhotoActivity.java to call this class every time a button for camera intent had been clicked.
What I currently have is:
public class PhotoActivity extends AppCompatActivity implements View.OnClickListener {
private final int REQUEST = 1;
private File image;
private String pathToFile;
private ImageView imageView;
#Override
public void onClick(View view) {
imageView = findViewById(R.id.imageView);
dispatchTakePictureIntent();
}
public void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Make sure there's camera activity to handle the camera intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create an empty File for the soon created File
File photoFile = null;
try {
photoFile = createImageFile();
} catch (Exception e) {
// Error when creating the File
e.printStackTrace();
}
// If File created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.inventorymanager.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST);
}
}
}
public File createImageFile() throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save the file's path for use with ACTION_VIEW intents
pathToFile = image.getAbsolutePath();
return image;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST && resultCode == RESULT_OK) {
Bitmap myBitmap = BitmapFactory.decodeFile(image.getAbsolutePath());
imageView.setImageBitmap(myBitmap);
}
}
}
The problem with this is that whenever it opens, onClickListener, the camera doesn't open even though my dispatchTakePictureIntent() method is there.