How to save images in Android? - android

I'm very new to Android programming and I was wondering how can I make an app take a picture and save the image to the internal storage of a device, not to the SD card, because not everyone will have an SD card.

You can try saving it as an sqlite blob. This this thread for how to do the storage. Saying "not everyone will have external storage" is a bad excuse: you should handle both cases. If instead you want to implement it as a file (a perfectly good way to do it), you can look up an external storage directory using the Environment.getExternalStorageDir() call to determine a suitable directory in which to store your files. Read the API documentation here and heed the following note:
Note: don't be confused by the word "external" here. This directory can better be thought as media/shared storage. It is a filesystem that can hold a relatively large amount of data and that is shared across all applications (does not enforce permissions). Traditionally this is an SD card, but it may also be implemented as built-in storage in a device that is distinct from the protected internal storage and can be mounted as a filesystem on a computer.

Yes, you can try to save images in sqlite blob fields. It's just a java way: and let the whole world wait :)
It's a good practice to store all your files, cache etc into /Android/data/<package_name>/files/ directory on external storage. External storage is not the only SD cards and you can get external storage path and state by Environment.getExternalStorageDirectory() and Environment.getExternalStorageState() calls (reference). If you are using API 8 or greater, you can use Context.getExternalFilesDir().
If you would like to get user's hate-rays, you can try to store files and folders in the root of external storage.

Perhaps something like this
Bitmap largeBitmap ; // save your Bitmap from data[]
FileOutputStream fileOutputStream = null;
BufferedOutputStream bos = null;
int quality = 100;
String filePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + File.separator + "myImage.jpg"
File mediaFile = new File(filePath);
try {
fileOutputStream = new FileOutputStream(pictureFile);
bos = new BufferedOutputStream(fileOutputStream);
bitmap.compress(CompressFormat.JPEG, quality, bos);
return pictureFile;
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
// ignore close error
}
}

Related

Is this code outdated? getExternalStoragePublicDirectory()

Why this code is my white line drawing problem What is the problem
Is there a way to replace it?
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);
Exactly this line of code is drawn by the white line method
getExternalStoragePublicDirectory
getExternalStoragePublicDirectory() --> Deprecated in API level 29
To improve user privacy, direct access to shared/external storage
devices is deprecated. When an app targets Build.VERSION_CODES.Q, the
path returned from this method is no longer directly accessible to
apps. Apps can continue to access content stored on shared/external
storage by migrating to alternatives such as
Context#getExternalFilesDir(String), MediaStore, or
Intent#ACTION_OPEN_DOCUMENT.
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);
}
}

How can I export Layout or Views as images to visible gallery folder in Android?

After searching about "How to save Layout views as images", I've found some solution to save in Internal and External Storage. But It seems the image file created is going to save in some data/data/... folder that is not visible normally. Actually I want the image visible in gallery for the user. I've found some code like below, but I even can't check if the image is created or not:
View content = findViewById(R.id.relativeLayout);
String yourimagename = "MyImageFile";
content.setDrawingCacheEnabled(true);
Bitmap bitmap = content.getDrawingCache();
File file = new File("/" + yourimagename + ".png");
try {
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream ostream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 10, ostream);
ostream.close();
content.invalidate();
} catch (Exception e) {
e.printStackTrace();
} finally {
content.setDrawingCacheEnabled(false);
}
But It seems the image file created is going to save in some data/data/... folder that is not visible normally.
The file will be saved where the programmer elects to save it.
Actually I want the image visible in gallery for the user. I've found some code like below, but I even can't check if the image is created or not
That code will not work on any version of Android, as new File("/" + yourimagename + ".png") is not going to give you a usable File, as it points to a place that you can neither read nor write.
You are welcome to save the image to internal storage or external storage. Since you want this image to be picked up by "gallery"-type apps, you are best off choosing external storage, then using MediaScannerConnection and its scanFile() method to get the file indexed by the MediaStore, since gallery apps will tend to use the MediaStore as their source of images.
On the whole, I worry that getDrawingCache() will be unreliable. You may be better served telling your root View to draw to your own Bitmap-backed Canvas instead.

How do I get the external storage's path?

I'm trying to write a file to my phone.
I used Environment.getDataDirectory() to know the internal storage's path and Environment.getExternamStorageDirectory() to know the external storage's path.
But when I use Environment.getExternalStorageDirectory() as path, the file is created in internal storage. And when I use Environment.GetDataStorage() as the path, the file is not created. (I am not sure, but I can't find it in the explorer app, at least.)
I think my phone's internal storage is perceived as external storage.(In my case, it has 32 GB amount of storage)
I want to know removable storage(e.g. micro SD card) path. What should I do?
From the official documentation for getExternalStorageDirectory()
Don't be confused by the word "external" here. This directory
can better be thought as media/shared storage. It is a filesystem that
can hold a relatively large amount of data and that is shared across
all applications (does not enforce permissions). Traditionally this is
an SD card, but it may also be implemented as built-in storage in a
device that is distinct from the protected internal storage and can be
mounted as a filesystem on a computer.
So, it can be different from built-in storage in a device.
For your case, you could use getExternalStoragePublicDirectory(java.lang.String)
This is where the user will typically place and manage their own
files
The path here should be one of DIRECTORY_MUSIC, DIRECTORY_PODCASTS,
DIRECTORY_RINGTONES, DIRECTORY_ALARMS, DIRECTORY_NOTIFICATIONS,
DIRECTORY_PICTURES, DIRECTORY_MOVIES, DIRECTORY_DOWNLOADS, or
DIRECTORY_DCIM. May not be null.
Or if you want your data to be deleted whenever the user uninstalls your app, you could use getExternalFilesDir().
As these files are internal to the applications, and not typically visible to the user as media.
Also there are some differences between getFilesDir() and getExternalFilesDir()
External files are not always available: they will disappear if the user mounts the external storage on a computer or removes it. See the APIs on environment for information in the storage state.
There is no security enforced with these files. For example, any application holding WRITE_EXTERNAL_STORAGE can write to these files.
Try this...
static String storagestate = Environment.getExternalStorageState();
private static FileOutputStream outStream;
private static File imageFilepath;
public static String saveImage(Bitmap bitmap) {
File folder = null;
// Check for SD card
if (storagestate.equals(Environment.MEDIA_MOUNTED)) {
folder = new File(Environment.getExternalStorageDirectory(),
"*YourStorageNameInDevice");
if (!folder.exists()) {
folder.mkdir();
}
outStream = null;
String timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS")
.format(new Date());
// Getting filepath
imageFilepath = new File(folder.getPath() + File.separator
+ timestamp + ".PNG");
try {
outStream = new FileOutputStream(imageFilepath);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return imageFilepath.getAbsolutePath();
}
}

Android saving file to SD Card, not internal storage

I know there have been questions about this, but for some reason nothing seems to work for me.
I'm trying to get 2 text files to save to the SD card from my app. It correctly creates the directory and the files, but always to the Internal Storage, never the External Storage. I do have the permissions in place as well in the Manifest.
try {
File sdCard = Environment.getExternalStorageDirectory();
File myFile = new File(sdCard.getAbsolutePath() + "/rlgl");
myFile.mkdir();
// myFile.createNewFile();
String newLine = System.getProperty("line.separator");
File file = new File(myFile, "rlgls.txt");
if(file.exists()) {
} else if (!file.exists()){
FileOutputStream fOut = new FileOutputStream(file);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
for (int i = 0; i < 30; i++) {
myOutWriter.append("0.0" + newLine);
}
myOutWriter.close();
fOut.close();
}
} catch (IOException e) {
e.printStackTrace();
}
This is the code that I am using. I've followed directions from other Stackoverflow responses but it never goes to the SD Card. Is there something I'm doing wrong? Also a follow up question is there a way for me to use the above code in order to make the files invisible to the user. They should have no reason to open them. Thanks in advance.
It correctly creates the directory and the files, but always to the Internal Storage, never the External Storage
No, it places them on external storage. What the user sees as internal storage is what the developer sees as external storage. Internal storage is accessed via methods like getFilesDir(). And none of those are removable storage, such as some form of SD card.
Also a follow up question is there a way for me to use the above code in order to make the files invisible to the user. They should have no reason to open them.
Then put them on internal storage.
my app can't read/write from/to the files when there is a "." in front of their names
I find that very difficult to believe. The . prefix makes them not show up by default in some file browsers, but that's it. Users can get to them (if they are on external storage), and apps can get to them (subject to the same rules as any other files, those without a leading .).

where to store xml updates in packaged android app?

I guess I'm a little confused as to how files are stored on an actual machine (or emulator even).
While programming, I can save my xml file in the assets folder manually, but how to write an app that will have to connect to the network and download the file,save it somewhere and then manipulate it ? where will it store said file ?
I want to create a new file, but I read on another post that the assets folder as such is not available once packaged; So where are they created and stored ? How can they be transferred. Its just, I'm new to this platform and the file system is a little confusing.
If you want to use XML that is updated, you should think of copying the file(s) from assets to device storage. You can take a look at How to copy files from 'assets' folder to sdcard? to know how this can be done.
Another alternative is to use the database where you can store the parsed data from the XML. So that you need not parse the file whenever you need to access the contents.
You have two options: call getFilesDir() from your activity to obtain a path to the internal data folder that can only be read/write from your app.
Or, you can write/read your xml file to external storage (SD Card). Use the method Environment.getExternalStorageDirectory() to get the root path of the external storage, then create your own folder as you see fit.
Note that if you write to external storage, every app in the phone will have access to it.
Even I faced this issue. Now I have a xml file which is has application properties.This is packaged in the assets folder.Once packaged we cannot edit a file in assets folder.
Now on app load I just copy this file to path returned by
context.getFilesDir().getAbsolutePath();
And the application edit it from the same place. You can see if the file is modified in the FileExplorer panel of DDMS view. The file is stored in the folder named same as your application package name for eg: com.abhi.maps
Alternatively you can also copy it to SD card.However it is risky because, sd card may bot be available all the time.
You can use the following code to copy file from assets folder:
private static void copyFile(String filename, Context context) {
AssetManager assetManager = context.getAssets();
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
String newFileName = context.getFilesDir() + "/" + filename;
out = new FileOutputStream(newFileName);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e) {
Log.e("tag", e.getMessage());
}
}
Hope it helps! :)

Categories

Resources