Save an Image in app folder - android

I'm new in Android development and I have an app that saves a 'jogador' (player) record with some attributes (name, birthday...) and a photo.
When the user picks the image from gallery, I populate an ImageView with the photo so that the user can see it before he saves the record. (It's working here).
My problem is that I want to save that photo in a folder created by me (Inside res/ folder). eg: res/myFolder.
I don't know how I will access that folder to put an image inside. Follow my code bellow:
Bitmap bmp = BitmapFactory.decodeFile(fotoPath); //---> It works
FileOutputStream fos;
try {
// 'fotos_jogador' is my folder inside res folder.
// I think that 'Environment.getExternalStorageDirectory()'
// gives me access to sdcard, but i don't want this, I want to save in a local app folder.
File file = new File(Environment.getExternalStorageDirectory() +
File.separator + "/fotos_jogador/" + ".png");
fos = new FileOutputStream(file);
//I want do store a low quality image, just for contact photo.
if(fos != null){
bmp.compress(CompressFormat.PNG, 20, fos);
fos.close();
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
Then, guys, my doubts:
How can I give a custom name for my Image?
How can I Save the image in my folder 'fotos_jogador'?
How can I retrieve the Image after it's saved?
I appreciate the help. Thanks!

no you can not save anything in resource folder here is the link of duplicate post Is it possible to save image in assets folder from application
you can save image in sd card or in internal memory.

Related

Where should I have users save the images that they made on my app

My users make custom images on my app and I am unsure what directory I should use when they save. Should I use MediaStore.Images.Media.EXTERNAL_CONTENT_URI?
Basically MediaStore.Images.Media.EXTERNAL_CONTENT_URI is part of Content Resolver which allow you to read and write resource from your user device. You need to ask yourself wether it is good to save their image into device. You could save your image in private or public which still decided by you. There is internal and external storage, wether you need all image to be deleted when your app is deleted or you don't want other app access the photo you user created use internal storage otherwise use external storage.Take a look on this link which take you step by step to understand why, which,how to save file into your app.
You can make a directory of your own app in the internal storage of the device and store all the pictures made from your app there.
You can make the directory using
File directory = new File(Environment.getExternalStorageDirectory() + File.separator + "<app name>");
if(!directory.exists){
directory.mkdirs;
}
And then store the pictures in this path
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String name = "<image name>"+n+".jpg";
File pictureFile = new File(directory, name);
pictureFile.createNewFile();
try {
FileOutputStream out = new FileOutputStream(pictureFile);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.close();
} catch (Exception e) {
e.printStackTrace();
}

Share screenshot in android

I don't have SD card in my mobile also was hoping people who use my app may or may not have it. Now when I tried to share my screenshot it works in few mobiles and does not work in few. In all these mobiles none of them have SD card. Also I want to make sure that the screenshots should not get saved anywhere so that it will not be visible in the gallery. I tried with the following methods:
getExternalStorageState()
getDatadirectory()
getFilesDir()
getDir()
getCacheDir()
But I still couldn't get the right approach in doing so. This is the present code that I'm working on :
view.setDrawingCacheEnabled(true);
view.measure(View.MeasureSpec.makeMeasureSpec(view.getWidth(), View.MeasureSpec.EXACTLY),
View.MeasureSpec.makeMeasureSpec(view.getHeight(), View.MeasureSpec.EXACTLY));
view.layout( view.getLeft(), view.getTop(), view.getLeft() + view.getMeasuredWidth(), view.getTop() + view.getMeasuredHeight());
bitmap = Bitmap.createBitmap(view.getDrawingCache());
view.setDrawingCacheEnabled(false);
view.destroyDrawingCache();
view.invalidate();
view.refreshDrawableState();
File path = new File(getApplicationContext().getDir("Default", Context.MODE_ENABLE_WRITE_AHEAD_LOGGING),"myapp");
File directory = new File(path.getAbsolutePath());
directory.mkdirs();
String filename = "myapp" + new Date() + ".png";
File yourFile = new File(directory, filename);
try
{
FileOutputStream out = new FileOutputStream(yourFile, true);
bitmap.compress(Bitmap.CompressFormat.PNG, 90,out);
out.flush();
out.close();
send(yourFile);
}catch (IOException e)
{
e.printStackTrace();
}
Now my focus is on sharing the screenshot in a mobile where it does not have SD card and it should not save anywhere so that the screenshots wouldn't keep dumping as I go on sharing. How to do it ?
EDIT :
Now I started working on getDir() method so that the files will be getting saved on Application data as noted by my friend Ashish Vora. I have found that the files are getting saved inside but it is not retrieved back for sharing. All I'm getting is a blank screen.
Best thing is to save it using getDir().
So it will be in your Application data and not visible in Gallery. Also you can share it using your Application.
So save it as:
File path = new File( getDir(YOUR_DEFAULT_DIRECTORY_NAME, Context.MODE_ENABLE_WRITE_AHEAD_LOGGING));
File directory = new File(path.getAbsolutePath()+ "/my app");
Else you can use as:
File directory = new File(getDir("my app", Context.MODE_ENABLE_WRITE_AHEAD_LOGGING));

Extract exif information of image in android

Im new to android development and trying to get metadata of image using ExifInterface. I stored the image under drawable and trying to get the metadata but getting null values for all fields(date, imagelength, imagewidth). I tried to access image path as this :
String path = "drawable://" + R.drawable.testimage;
and provided this path to ExifInterface.
ExifInterface exif = new ExifInterface(path);
I dont know if storing image under drawable is correct or not because when I run the app in emulator I get something like this :
E/JHEAD﹕ can't open 'drawable://2130837561'
So if this is wrong then please tell me where should I store the image and how to provide image path to ExifInterface.
Thank you in advance.
To get a drawable, you can you this snippet:
Drawable drawable = getResources().getDrawable(android.R.drawable.your_drawable);
I'm not sure if your way is correct, as I've never seen it like that. Do you really need the path to your image to use it on that ExifInterface class?
Ok, I did some digging and found this question, which led me to this one. As it seems, you can not get an absolute path from a resource inside your apk. A good solution would be for you to save it as a file on the external memory, and then you can get the path you want.
First of all, add this to your AndroidManifest.xml, so your app can write to the cellphone memory:
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Ok, to save it you can try this, first create a bitmap from your drawable resource:
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.your_drawable);
After that get the path you want to save your images, and put it on a String. More info on that here.
The Android docs have a good example on how to get the path. You can see it here.
To keep it simple, I'll copy and paste the snippet from the docs.
void createExternalStoragePrivateFile() {
// Create a path where we will place our private file on external
// storage.
File file = new File(getExternalFilesDir(null), "DemoFile.jpg");
try {
// Very simple code to copy a picture from the application's
// resource into the external file. Note that this code does
// no error checking, and assumes the picture is small (does not
// try to copy it in chunks). Note that if external storage is
// not currently mounted this will silently fail.
InputStream is = getResources().openRawResource(R.drawable.balloons);
OutputStream os = new FileOutputStream(file);
byte[] data = new byte[is.available()];
is.read(data);
os.write(data);
is.close();
os.close();
} catch (IOException e) {
// Unable to create file, likely because external storage is
// not currently mounted.
Log.w("ExternalStorage", "Error writing " + file, e);
}
}
void deleteExternalStoragePrivateFile() {
// Get path for the file on external storage. If external
// storage is not currently mounted this will fail.
File file = new File(getExternalFilesDir(null), "DemoFile.jpg");
if (file != null) {
file.delete();
}
}
boolean hasExternalStoragePrivateFile() {
// Get path for the file on external storage. If external
// storage is not currently mounted this will fail.
File file = new File(getExternalFilesDir(null), "DemoFile.jpg");
if (file != null) {
return file.exists();
}
return false;
}
After that, get the path of the file you saved on the external memory, and do as you wish.
I'll keep the old example as well. You can use the method getExternalStorageDirectory() to get the path, or getExternalCacheDir(). After that, you can use File method called getAbsolutePath() to get your String.
String path = (...) // (you can choose where to save here.)
File file = new File(path, "your_drawable.png");
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out); // You can change the quality from 0 to 100 here, and the format of the file. It can be PNG, JPEG or WEBP.
out.flush();
out.close();
For more info on the Bitmap class, check the docs.
If you need more info, let me know and I'll try to show more samples.
EDIT: I saw your link, and there was this snippet there:
//change with the filename & location of your photo file
String filename = "/sdcard/DSC_3509.JPG";
try {
ExifInterface exif = new ExifInterface(filename);
ShowExif(exif);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(this, "Error!",
Toast.LENGTH_LONG).show();
}
As you can see, if you really want to see the exif data of a internal image resource, you'll have to save it somewhere else, and then you can try to get the absolute path for that File, then, call the method to show the exif.

Takes images from gallery

My app takes images from gallery and copies to a subfolder. But, the images that are copied are comes to gallery as a copy of original one from different location.
How to prevent it? please help me.
this is my code to save to a pre defined folder....
protected String saveBitmap(Bitmap bm, String path) throws Exception {
String tempFilePath="/sdcard/AuFridis/Events/Images/"+System.currentTimeMillis()+"myEventImg.jpg";
File tempFile = new File(path+"/"+System.currentTimeMillis()+"myEventImg.jpg");
// File tempFile = new File("/sdcard/Notes");
tempFile.createNewFile();
if (!tempFile.exists()) {
if (!tempFile.getParentFile().exists()) {
tempFile.getParentFile().mkdirs();
}
}
//tempFile.delete();
//tempFile.createNewFile();
int quality = 100;
FileOutputStream fileOutputStream = new FileOutputStream(tempFile);
BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
bm.compress(CompressFormat.JPEG, quality, bos);
bos.flush();
bos.close();
//bm.recycle();
Log.i("On saveBitmap Function - retrieved file path", "---"+tempFilePath);
return tempFilePath;
}
Are you trying to hide the images from the gallery? Android by default scans the memory of the device and puts all photos it finds into the gallery. The device is most likely seeing the repeated name and labeling. Just change the image name.
By default, android scans the SD card and adds all images it finds to the gallery. If you copy an image from gallery to another folder, that folder will automatically be added to the gallery. To prevent this, add an empty file with name .nomedia to your destination folder - and your copied images will not show in the gallery.

Get R.drawable ID's dynamically in android

I have a folder with a few images, these images are added by user dynamically. So i need to get the R.drawable ID's of these images in android.... ???
Where are you saving these images too? When images are being added dynamically at runtime usually you need to store them on the phones storage. If you want the images to be stored in the external storage (SDCard) then you can use the following code to retrieve them and add them to your view (Which I assume your doing). This code assumes the images are being stored to your devices SDCard, which is where they will be pulled from.
//Get root directory of storage directory, pass in the name of the Folder if they are being stored farther down, i.e getExternalFilesDir("FolderName/FolderName2")
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// We can read and write the media
File dir = getExternalFilesDir(null);
Bitmap bmap = null;
try {
InputStream is = new FileInputStream(new File(dir,"image.jpg"));
bmap = BitmapFactory.decodeStream(is);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if (bmap!=null) {
ImageView view = new ImageView(this);
view.setImageBitmap(bmap);
}
}

Categories

Resources