I want to capture image and save it to specific folder in internal storage. Currently i am able to open intent and get thumbnail of captured image. I dont want to user extrnal stotage as now mostly users use their internal storage and not sd card.
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getPackageManager()) != null){
startActivityForResult(intent,1);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (requestCode == 1 && resultCode == RESULT_OK){
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
LayoutInflater inflater = LayoutInflater.from(LeaveApplicationCreate.this);
final View view = inflater.inflate(R.layout.item_image,attachView, false);
ImageView img = view.findViewById(R.id.img);
AppCompatImageView btnRemove = view.findViewById(R.id.btnRemove);
img.setImageBitmap(imageBitmap);
btnRemove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
attachView.removeView(view);
}
});
attachView.addView(view);
File directory = new File(Environment.getExternalStorageDirectory(),"/Digimkey/Camera/");
if (!directory.exists()) {
directory.mkdir();
}
File file = new File(directory, System.currentTimeMillis()+".jpg");
try (FileOutputStream out =new FileOutputStream(file)) {
imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
} catch (IOException e) {
e.printStackTrace();
}
}
}
First gain Write Permissions.
File directory = new File(Environment.getExternalStorageDirectory(), dirName);
if (!directory.exists()) {
directory.mkdirs();
}
File file = new File(directory, fileName);
if (!file.exists()) {
file.createNewFile();
}
try (FileOutputStream out =new FileOutputStream(file)) {
bmp.compress(Bitmap.CompressFormat.PNG, 100, out);
} catch (IOException e) {
e.printStackTrace();
}
There are two types of storage.
1) Internal ex. "/root/.."
Unless you have rooted device, we can't access. this path.
2) External ex. "/storage/emuated/0"
Environment.getExternalStorageDirectory()
By using this path, we are able to create a directory/file.
Use to method to save your bimap in local storage. Pass bimap image as parameter i.e saveToInternalStorage(imageBitmap)
private String saveToInternalStorage(Bitmap bitmapImage){
//set image saved path
File storageDir = new File(Environment.getExternalStorageDirectory()
+ "MyApp"+ "/Files");
if (!storageDir.exists()) {
storageDir.mkdirs();
}
File mypath=new File(storageDir,"bitmap_image.jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return directory.getAbsolutePath();
}
Required permissions in Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Related
Hi I am trying to make the images captured from my app inaccessible to the user. First I tried to save these images to internal storage which didnt work. Then I tried to hide them using "." infront of the folder name.I am not sure what the correct way to do this is. I also tried creating a file called .nomedia to bypass media scanner. I am very confused about the proper way to do this. Here's my code:
public String getImageUri(Context inContext, Bitmap inImage) {
/* *//* ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, ".title", null);
return Uri.parse(path);*//*
*/
File file = new File(Environment.getExternalStorageDirectory()
+ File.separator + "/.myFolder");
file.mkdirs();
File mFile = new File(Environment.getExternalStorageDirectory()
+ File.separator + "/.nomedia");
mFile.mkdirs();
FileOutputStream fOut = null;
try {
fOut = new FileOutputStream(file);
inImage.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
fOut.flush();
fOut.close();
uri = MediaStore.Images.Media.insertImage(getContentResolver(), file.getAbsolutePath(), file.getName(), file.getName());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return uri;
}
If I use file.mkdirs() I get filenotfoundexception. If i remove that line I get no errors but my uri is empty.
Does the above function return the file path as well? I need the file path and the uri later on. Any help is appreciated.
I guess you don't have to add another extension or something else just save them in external cache dir of your app and gallery app won't able to read your private directory until unless you notify about them.
so store your camera images here and no gallery app can detect it.
context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
sample code
public static File createPictureFile(Context context) throws IOException {
Locale locale = Locale.getDefault();
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", locale).format(new Date());
String fileName = "JPEG_" + timeStamp + "_";
// Store in normal camera directory
File storageDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
return File.createTempFile(fileName, ".jpg", storageDir);
}
Save your image to internal storage instead. Other applications like MediaScanner or Gallery do not have permission to read from your own application memory. Sample code:
private String saveToInternalStorage(Bitmap bitmapImage){
ContextWrapper cw = new ContextWrapper(getApplicationContext());
// path to /data/data/yourapp/app_data/imageDir
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
// Create imageDir
File mypath=new File(directory,"profile.jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
// Use the compress method on the BitMap object to write image to the OutputStream
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return directory.getAbsolutePath();
}
Save the image with different extension.
For example: .jpg can be saved as .ttj.
Try this code. Set where you want to save the photo. Once you receive response on onActivityResult(), in the desired URI, you will get the photo.
public void captureImageFromCamera() {
fileUri = FileUtils.getInstance().getOutputMediaFile(null);
if(fileUri == null){
Utilities.displayToastMessage(ApplicationNekt.getContext(),
context.getString(R.string.unable_to_access_image));
return;
}
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, TAKE_PICTURE);
}
Following function will give you desired path. Change it based on your project need.
public Uri getOutputMediaFile(String imageNameWithExtension) {
if (imageNameWithExtension == null)
imageNameWithExtension = "image_" + System.currentTimeMillis() + ".jpg";
String extPicDir = getExtDirPicturesPath();
if (!Utilities.isNullOrEmpty(extPicDir)) {
File mediaFile = new File(extPicDir, imageNameWithExtension);
return Uri.fromFile(mediaFile);
} else {
Log.d("tag", "getOutputMediaFile." +
"Empty external path received.");
return null;
}
}
public String getExtDirPicturesPath() {
File file = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
if (file != null)
return file.getPath();
else
Log.d("", "getExtDirPicturesPath failed. Storage state: "
+ Environment.getExternalStorageState());
return null;
}
To get the resultant photo.
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != Activity.RESULT_OK)
return;
switch (requestCode) {
case TAKE_PICTURE:
//fileuri variable has the path to your image.
break;
}
I'm trying to save a bitmap to my directory but haven't a little trouble.
What my applications does is:
1.Opens the inbuilt camera application by an Intent.
public void openCamera() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = new File(Environment.getExternalStorageDirectory()+ File.separator + "image.jpg");
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
2.It then stores the picture intent into 'REQUEST_IMAGE_CAPTURE' and saves the image into a temp directory.
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
3.Which is then converted into a bitmap and loaded from the tmp directory into an image view
protected void onActivityResult(int requestCode, int resultCode, Intent data){
//Check that request code matches ours:
if (requestCode == REQUEST_IMAGE_CAPTURE){
//Get our saved file into a bitmap object:
File file = new File(Environment.getExternalStorageDirectory()+File.separator + "image.jpg");
Bitmap image = decodeSampledBitmapFromFile(file.getAbsolutePath(), 1000, 700);
imageView.setImageBitmap(image);
}
}
Now, how do i save the bitmap which in the imageview into the picture directory?
I have inputted the permissions into my manifest
<uses-feature android:name="android.hardware.camera"
android:required="true" />
...
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
...
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
use bitmap.compress in order to direct the bitmap into an OutputStream.
for example:
FileOutputStream fo = new FileOutputStream(filename);
bmp.compress(Bitmap.CompressFormat.PNG, 100, fo); // bmp is your Bitmap
private void saveImage(Bitmap bmp, String filePath){
File file = new File(filePath);
FileOutputStream fo = null;
try {
boolean result = file.createNewFile(); // true if created, false if exists or failed
fo = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.JPEG, IMAGE_QUALITY_PERCENT, fo);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fo != null) {
try {
fo.flush();
fo.close();
} catch (Exception ignored) {
}
}
}
}
Note that filePath is directory + filename e.g. /sdcard/iamges/1.jpg
i am using the API21 SlidingTabLayout and SlidingTabStrips for my application.
I am saving an .tmp file of my intent camera photo. that works fine and i can see it on my phone package directory but i can store this .tmp file as .png ( i want to change the resolution because i need <1mb files instead of the 3mb files from the photo API intent)
i tried so many things in the last two hours and i can't solve it.
here is my code:
starting the intent with: takeAPicture
private void takeAPicture(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(getTempFile(getView().getContext())));
startActivityForResult(intent, TAKE_PHOTO_CODE);
}
the path of my .tmp file: getTempFile
private File getTempFile(Context context){
final File path = new File(Environment.getExternalStorageDirectory(), getView().getContext().getPackageName());
if(!path.exists()){
path.mkdir();
}
return new File(path, "test.tmp");
}
at least i handle the ActivityResult:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.i(TAG, "onActivityResult: Joined");
if(resultCode == Activity.RESULT_OK){
switch (requestCode){
case TAKE_PHOTO_CODE:
final File file = getTempFile(getView().getContext());
Toast.makeText(getActivity().getApplicationContext(), "Uri: " + Uri.fromFile(file), Toast.LENGTH_LONG);
try{
Bitmap captureBmp = MediaStore.Images.Media.getBitmap(getActivity().getApplicationContext().getContentResolver(), Uri.fromFile(file));
FileOutputStream fos = new FileOutputStream(new File(new File(Environment.getExternalStorageDirectory(), getView().getContext().getPackageName()),"done.png"));
captureBmp.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
}
The fact is, the .tmp file is stored and the uri for
Bitmap captureBmp = MediaStore.Images.Media.getBitmap(getActivity().getApplicationContext().getContentResolver(), Uri.fromFile(file));
is correct.
hope someone can help me
You can use my code:
public static boolean saveImage(Context context, byte[] image, String filename) {
Bitmap bitmapImage = BitmapFactory.decodeByteArray(image, 0, image.length);
return saveImage(context, bitmapImage, filename);
}
public static boolean saveImage(Context context, Bitmap image, String filename) {
try {
FileOutputStream fos = context.openFileOutput(filename,Context.MODE_PRIVATE);
imagem.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.close();
File file = context.getFileStreamPath(filename);
} catch (Exception e) {
return false;
}
return true;
}
I have captured image through camera intent and image are saved to internal memory.But my images are also stored in gallary .I don't want to save the images into gallary for private purpose.
Here is my code:-
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);#SuppressLint("NewApi")
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
FileOutputStream mFileOutStream1;
try {
mFileOutStream1 = openFileOutput("IMG" + counter + ".png", Context.MODE_PRIVATE);
photo.compress(CompressFormat.JPEG, 100, mFileOutStream1);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Try this code
private String saveToInternalSorage(Bitmap bitmapImage){
ContextWrapper cw = new ContextWrapper(getApplicationContext());
// path to /data/data/yourapp/app_data/imageDir
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
// Create imageDir
File mypath=new File(directory,"profile.jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
// Use the compress method on the BitMap object to write image to the OutputStream
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
return directory.getAbsolutePath();
}
Hope this help you..!!!
this is my code I and I want to save this bitmap on my internal storage. The public boolean saveImageToInternalStorage is a code from google but I don't know how to use it. when I touch button2 follow the button1 action.
public class MainActivity extends Activity implements OnClickListener {
Button btn, btn1;
SurfaceView sv;
Bitmap bitmap;
Canvas canvas;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn=(Button)findViewById(R.id.button1);
btn1=(Button)findViewById(R.id.button2);
sv=(SurfaceView)findViewById(R.id.surfaceView1);
btn.setOnClickListener(this);
btn1.setOnClickListener(this);
bitmap=BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
}
#Override
public void onClick(View v) {
canvas=sv.getHolder().lockCanvas();
if(canvas==null) return;
canvas.drawBitmap(bitmap, 100, 100, null);
sv.getHolder().unlockCanvasAndPost(canvas);
}
public boolean saveImageToInternalStorage(Bitmap image) {
try {
// Use the compress method on the Bitmap object to write image to
// the OutputStream
FileOutputStream fos = openFileOutput("desiredFilename.png", Context.MODE_PRIVATE);
// Writing the bitmap to the output stream
image.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
return true;
} catch (Exception e) {
Log.e("saveToInternalStorage()", e.getMessage());
return false;
}
}
}
To Save your bitmap in sdcard use the following code
Store Image
private void storeImage(Bitmap image) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
Log.d(TAG,
"Error creating media file, check storage permissions: ");// e.getMessage());
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
image.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
To Get the Path for Image Storage
/** Create a File for saving an image or video */
private File getOutputMediaFile(){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
+ "/Android/data/"
+ getApplicationContext().getPackageName()
+ "/Files");
// 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()){
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
File mediaFile;
String mImageName="MI_"+ timeStamp +".jpg";
mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
return mediaFile;
}
EDIT
From Your comments i have edited the onclick view in this the button1 and button2 functions will be executed separately.
public onClick(View v){
switch(v.getId()){
case R.id.button1:
//Your button 1 function
break;
case R.id. button2:
//Your button 2 function
break;
}
}
private static void SaveImage(Bitmap finalBitmap) {
String root = Environment.getExternalStorageDirectory().getAbsolutePath();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
String fname = "Image-"+ o +".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();
}
}
Modify onClick() as follows:
#Override
public void onClick(View v) {
if(v == btn) {
canvas=sv.getHolder().lockCanvas();
if(canvas!=null) {
canvas.drawBitmap(bitmap, 100, 100, null);
sv.getHolder().unlockCanvasAndPost(canvas);
}
} else if(v == btn1) {
saveBitmapToInternalStorage(bitmap);
}
}
There are several ways to enforce that btn must be pressed before btn1 so that the bitmap is painted before you attempt to save it.
I suggest that you initially disable btn1, and that you enable it when btn is clicked, like this:
if(v == btn) {
...
btn1.setEnabled(true);
}
To save file into directory
public static Uri saveImageToInternalStorage(Context mContext, Bitmap bitmap){
String mTimeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
String mImageName = "snap_"+mTimeStamp+".jpg";
ContextWrapper wrapper = new ContextWrapper(mContext);
File file = wrapper.getDir("Images",MODE_PRIVATE);
file = new File(file, "snap_"+ mImageName+".jpg");
try{
OutputStream stream = null;
stream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG,100,stream);
stream.flush();
stream.close();
}catch (IOException e)
{
e.printStackTrace();
}
Uri mImageUri = Uri.parse(file.getAbsolutePath());
return mImageUri;
}
required permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
You might be able to use the following for decoding, compressing and saving an image:
#Override
public void onClick(View view) {
onItemSelected1();
InputStream image_stream = null;
try {
image_stream = getContentResolver().openInputStream(myUri);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap image= BitmapFactory.decodeStream(image_stream );
// path to sd card
File path=Environment.getExternalStorageDirectory();
//create a file
File dir=new File(path+"/ComDec/");
dir.mkdirs();
Date date=new Date();
File file=new File(dir,date+".jpg");
OutputStream out=null;
try{
out=new FileOutputStream(file);
image.compress(format,size,out);
out.flush();
out.close();
MediaStore.Images.Media.insertImage(getContentResolver(), image," yourTitle "," yourDescription");
image=null;
}
catch (IOException e)
{
e.printStackTrace();
}
Toast.makeText(SecondActivity.this,"Image Save Successfully",Toast.LENGTH_LONG).show();
}
});