Android - Store an image on device? - android

My application allows users to take a photo using the camera and save it as their profile picture. There can be only 1 image stored at a time?
Is it a bad idea to use SharedPrefertences for this purpose although I am only storing 1 image? (Converting image to Base64). What are the cons?
If storing the image using shared preferences is not a good idea, what are the alternatives?

I think storing binary data in SharedPreferences is not a good idea. Instead save it to the filesystem. Example for that, if the data is coming from an InputStream:
storeImage( new File(context.getFilesDir().getAbsolutePath() + fileDir),
is,
"profile.png" );
public static void storeImage(
File fileDir,
InputStream inputStream,
String fileName ) throws IOException {
File file = new File( fileDir,fileName );
FileOutputStream fos = new FileOutputStream( file );
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
inputStream.close();
fos.close();
bitmap.recycle();
bitmap = null;
}
Where context can be the Application/Activity context.

There is no reason why you can't use SharedPreferences to store a single image as a Base64 String, Of course this isn't really a scalable approach as when the SharedPreferences are loaded, every image would be loaded into memory at once, but that's not what your looking for.
The other possible approaches you can take is to store the images either using the internal or external storage APIs or to store them in a database
In general for this kind of thing you should be looking to use something other than shared preferences, however in this case, I can't see there been an actual issue to the approach your suggesting.

Related

storing reference to image on SD efficiently in DB

I'm pretty new to programming Android and I have a problem - I'm creating an app which stores "funny" images and enables user to view all of them, rate them (at least I want to make it so ;) ). I was trying to make a very simple database which stores images as BLOBs but someone on forum told me that this is a bad idea - so I decided to store images on SD like (this code is mainly from Stack although):
private void savePicToSD(){
Toast.makeText(getActivity(),"Saving...",Toast.LENGTH_SHORT).show();
//getting BitMap from ImageView
Bitmap imageToSave=((BitmapDrawable)preview.getDrawable()).getBitmap();
// getting env var representing path
String root= Environment.getExternalStorageDirectory().toString();
Toast.makeText(getActivity(),root,Toast.LENGTH_LONG).show();
File dir=new File(root+DIR_NAME_);
dir.mkdirs();
String fileNam="Image-"+FILE_COUNTER_+".jpg";
FILE_COUNTER_=FILE_COUNTER_.add(BigInteger.valueOf(1));
File fileSav=new File(dir,fileNam);
//I don't use try-with-resources because of API lvl
FileOutputStream out=null;
try{
out=new FileOutputStream(fileSav);
//saving compressed file ot the dir
imageToSave.compress(Bitmap.CompressFormat.JPEG,90,out);
out.flush();
out.close();
}catch(Exception ex) {
ex.printStackTrace();
Toast.makeText(getActivity(), "Error during saving.", Toast.LENGTH_SHORT).show();
}
Toast.makeText(getActivity(),"Image saved.",Toast.LENGTH_LONG).show();
}
after making it I now don't know how to store this "reference" and how to implement "fetching data from DB" - I was thinking about storing (with some sort of other data releated to specific photo) in DB string contatining path to the image and later while reading data from DB, read also the image - but how to do this efficiently? (I know that fetching data from DB has to be done as a Thread (AsyncTask ? ))?
I think the best you can do is storing the path of the image in BDD or a relative path and then access it
Store imagePath/fileName in your local database along with saving the image in the file system(SD card), and then when you want to get back that image just fetch that image from the file system by using imagePath/fileName stored in database.
I hope that you know how to create file and store in SD card.

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 to check for space in android when creating files or saving images?

In android, I create txt files and save images too. But I'm not sure it is safe because I don't really check for space before saving. Does anyone have code here or know a tutorial that checks for space?
I just have this when saving images. Can I assume that if there isn't any space, it will throw an IOException, or do I need other code to do this?
Thanks
private static void imageSaverHelper(File file, Bitmap bitmap) throws IOException {
file.getParentFile().mkdirs();
OutputStream fOut = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
}
If there is not enough space, you will get an exception. There's really no other sensible way to handle this. Since the image is being compressed, there's no way to accurately predict how much space it will take without actually doing the compression.
Even if you could get an accurate measurement of the space it would take, there might be something else going on in the background that uses up that space before you get a chance to write your file.
The best approach is to write your file but be prepared to handle exceptions.

Using downloaded images in an Android Application

I want to download PDF's and images into my app, essentially it will call a JSON web service that returns the link to the PDF, link to the image, and the title. It will download the image and PDF and save them. Then it will display the PDF's and images with the title. My only question is how do I deal with images? They cant be saved to APK since it is locked. The images are high enough resolution that they can scaled down to fit all the other densities, should I just use the large image, and let the activity scale it down when it uses it. Or should I implement an image scaler during the retrieval process?
Eventually the PDF's and images would be loaded into the APK. How would I check the assets folder to remove the images, would I just need to call a service that runs when the Application First starts to check for the files in the assets folder then remove them if they are present?
Sample code for your reference where u can download Images from the web.Its better to store Images in asset folder than Internal Memory and resize the images for good performance.U can delete the folder before making web service call and load new set images.
if (Utility.isWifiPresent()
|| Utility.isMobileConnectionPresent()) {
URL url = new URL(fileUrl);
InputStream iStream = url.openConnection().getInputStream();// .read(data)
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
byte[] tmpArray = new byte[1024];
int nRead;
while ((nRead = iStream.read(tmpArray, 0, tmpArray.length)) != -1) {
buffer.write(tmpArray, 0, nRead);
}
buffer.flush();
data = buffer.toByteArray();
FileOutputStream fOut = null;
//path to store
fOut = Utility.getFileOutputStreamForCloud(
sdcardFolderPath, fileUrl);
}
fOut.write(data);
fOut.flush();
fOut.close();

How to save images in 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
}
}

Categories

Resources