I currently save images that I download from the internet to disk. I want to be able to delete the images when the user closes the app. I want the images all saved in one folder so it will be easy to delete them. I did getActivity().getCacheDir().getAbsolutePath()+ File.separator + "newfoldername" to get a path to a folder. Not sure how to add the images into the folder.
public void saveImage(Context context, Bitmap b, String name_file, String path) {
FileOutputStream out;
try {
out = context.openFileOutput(name_file, Context.MODE_PRIVATE);
b.compress(Bitmap.CompressFormat.JPEG,90, out);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public Bitmap getImageBitmap(Context context, String name) {
try {
FileInputStream fis = context.openFileInput(name);
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 1;
Bitmap b = BitmapFactory.decodeStream(fis,null, options);
b.getAllocationByteCount());
fis.close();
return b;
} catch (Exception e) {}
return null;
}
You shouldn't save the images on your cache folder as you can't rely on it as per the documentation. A better approach would be to store them on your SD Card. As per the documentation :
public abstract File getCacheDir()
Returns the absolute path to the application specific cache directory on the filesystem. These files will be ones that get deleted first when the device runs low on storage. There is no guarantee when these files will be deleted. Note: you should not rely on the system deleting these files for you; you should always have a reasonable maximum, such as 1 MB, for the amount of space you consume with cache files, and prune those files when exceeding that space.
FOR SAVING
private String saveToInternalSorage(Bitmap bitmapImage){
File directory = getApplicationContext().getDir("MY_IMAGE_FOLDER"
,Context.MODE_PRIVATE);
File mypath=new File(directory,"profile.jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
return directory.getAbsolutePath();
}
FOR READING
private void loadImageFromStorage(String path)
{
try {
File file = new File(path, "Image.jpg");
Bitmap bitmap = BitmapFactory.decodeStream(new FileInputStream(file));
ImageView img = (ImageView)findViewById(R.id.my_imgView);
img.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
FOR DELETING :
String dir = getApplicationContext().getDir("MY_IMAGE_FOLDER"
,Context.MODE_PRIVATE);
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
new File(dir, children[i]).delete();
}
}
Related
I have images in my drawables folder. Activity opens them, I choose the needed images and click on button. They must be saved on my SD Card through ImageSavingTask class instance execution which extends AsyncTask.
Here is my onClick code:
#Override
public void onClick(View v) {
for (int i = 0; i < 26; i++)
if (checkBoxes[i].isChecked()) {
imageIndex = new ImageIndex(); //ImageIndex-a class with single index field which reserves the checked checkbox indexes.
imageIndex.index = i;
Bitmap bitmap = ((BitmapDrawable) (images[i].getDrawable())).getBitmap();
SaveImageTask saveImageTask = new SaveImageTask();
saveImageTask.execute(bitmap); //The class SaveImageTask extends AsyncTask<Bitmap, Void, Void>
}
}
Then the selected images are handled in doInBackground method.
#Override
protected Void doInBackground(Bitmap... params) {
FileOutputStream outStream = null;
try {
Bitmap bitmap = params[0];
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] imageBytes = stream.toByteArray();
File sdCard = Environment.getExternalStorageDirectory();
Drawable drawable = new BitmapDrawable(getResources(), bitmap);
File dir = new File(sdCard.getAbsolutePath());
dir.mkdirs();
String fileName = "Saved image " + imageIndex.index; //The reserved index of checkbox creates a name for the new file.
File outFile = new File(dir, fileName);
outStream = new FileOutputStream(outFile);
outStream.write(imageBytes);
outStream.flush();
outStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
The <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> line is added in my manifest.
After I connect the USB to my phone, no error happens, but no images are saved to my SD Card. And I can't find images on my phone using windows search. Debugging doesn't give any answer. What kind of problem this could be?
It seems you have not asked runtime permissions for writing file on SD Card. From Android M and above you need to ask write permission at runtime to save any file on external sd card.
Check this link on how to request runtime permissions- https://developer.android.com/training/permissions/requesting.html
Also you can use google library - https://github.com/googlesamples/easypermissions
to request permissions.
I add the selected indexes into 2 ArrayLists of indexes and bitmaps. In the doInBackground method I created a loop.
For appearing the images on the card immediately I used the MediaScannerConnection.scanFile method.
for (int i = 0; i < 26; i++)
if (checkBoxes[i].isChecked()) {
index.add(i);
bitmap.add(bitmaps[i]);
}
if (bitmap.size() > 0)
new SaveImageTask().execute();
The doInBackground method:
protected Void doInBackground(Void... params) {
for (int i = 0; i < bitmap.size(); i++) {
try {
fname = "Saved image " + (index.get(i)) + ".jpg";
file = new File(myDir, fname);
if (file.exists()) file.delete();
FileOutputStream out = new FileOutputStream(file);
bitmap.get(i).compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
MediaScannerConnection.
scanFile(getApplicationContext(), new String[]{file.getPath()}, new String[]{"image/jpeg"}, null);
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
I left the ImageSavingTask without fields and parameters.
I think problem where you try to write bytes.
Use Following Solution..
#Override
protected Void doInBackground(Bitmap... params) {
Bitmap bitmap = params[0];
saveToInternalStorage(bitmap, "MyImage"); // pass bitmap and ImageName
return null;
}
//Method to save Image in InternalStorage
private void saveToInternalStorage(Bitmap bitmapImage, String imageName) {
File mypath = new File(Environment.getExternalStorageDirectory(), imageName + ".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.JPEG, 100, fos);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
NOTE : Make sure you have added storage read/write permission and don't forget to ask permission on Marshmallow and higher version.
I have a task in which I want to get drawable GIF image path but i am not getting correct path I tried below code to set path.
int resId = R.drawable.temp;
String imagePath2 = "android.resource://"+getPackageName()+"/"+resId;
String imagePath2 = ("android.resource://my.package.name/drawable/temp.gif");
but It's not working it's not giving me correct image but when i tried to get path from SD Card with below code
String inputPath = Environment.getExternalStorageDirectory()+ "/temp.gif";
it's working.
So now I am trying to store gif images from drawable or assets from SD card or internal memory. I found below code to copy PNG or JPEG to SD card.
Bitmap bm = BitmapFactory.decodeResource( getResources(), R.drawable.ic_launcher);
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File file = new File(extStorageDirectory, "ic_launcher.PNG");
outStream = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
but not getting any way to copy GIF image.
Any suggestions welcome.
Indeed you will not get a path from such a resource id. Instead you can get an InputStream from such a resource and use that stream to read the contents and copy for instance to a real file or whatever.
InputStream is = getResources().openRawResource(R.drawable.temp);
The type of the file does not matter. And as soon as you have this 'copy file' working you can throw away the code for copying jpg and png as it uses an intermediate Bitmap which is a bad idea and will change the file content and you end up with a different file -size-.
I made below method for getting image path and it's working perfect.
int resId = R.drawable.temp;
public String getFilePath(int resId){
// AssetManager assetManager = getAssets();
String fileName = "emp.gif";
InputStream in = null;
OutputStream out = null;
File outFile = null;
try {
//in = assetManager.open(fileName);
in = getResources().openRawResource(resId);
outFile = new File(getExternalFilesDir(null), fileName);
out = new FileOutputStream(outFile);
copyFile(in, out);
} catch(IOException e) {
Log.e("tag", "Failed to copy asset file: " + fileName, e);
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// NOOP
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
// NOOP
}
}
}
return outFile.getAbsolutePath();
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}
I'm making an android application that requires me to download all of the images from a remote directory locally in the /files path of the app. I need to know how to get a list of all of the files (all images) in that directory so I can download them all to the phone. I found the code to list the files in a local directory, but I need to know how to do the same thing for a remote directory (the directory is an http directory that requires no login)
String path = ".";
String files;
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++)
{
if (listOfFiles[i].isFile())
{
files = listOfFiles[i].getName();
System.out.println(files);
}
}
Also, I'm using this working code to download the images once I get the name of them in the directory.
private void storeImage(String filename)
{
FileOutputStream out = null;
try
{
URL url = new URL(Consts.IMAGES_BASE_URL + filename);
InputStream is = (InputStream) url.getContent();
Bitmap bm = BitmapFactory.decodeStream(is);
out = context.openFileOutput(filename, Context.MODE_WORLD_READABLE);
File file = new File(context.getFilesDir().toString(), filename);
out = new FileOutputStream(file);
if(isPNG(filename))//isPNG just parses out the extension
bm.compress(Bitmap.CompressFormat.PNG, 85, out);
else if(isJPG(filename))
bm.compress(Bitmap.CompressFormat.JPEG, 85, out);
} catch (MalformedURLException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
out.flush();
out.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
Any help is appreciated
I have stored some images in res folder of my app. But the user can download this image to their sdcard using the download option. How can I copy the image in res folder to sdcard. Can anyone help me.
You can do something like this,
if (isSdPresent()) { // to check is sdcard mounted
BitmapFactory.Options bmOptions;
bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
Bitmap bbicon = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
String extStorageDirectory = Environment.getExternalStorageDirectory()+ File.separator + "FolderName";
File wallpaperDirectory = new File(extStorageDirectory);
wallpaperDirectory.mkdirs();
OutputStream outStream = null;
File file = new File(wallpaperDirectory,"icon.png");
//to get resource name getResources().getResourceEntryName(R.drawable.icon);
try {
outStream = new FileOutputStream(file);
bbicon.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
}
to check SDCard
public boolean isSdPresent() {
return android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED);
}
Maybe this could help you getting a stream from your image and posting it to the user to download...
in my android application,I want to save some photos uploaded from a server on my database and then reuse them later. I think I should save them in a binary format and save their links into the database. Is it the better solution? Can you give some code or an example? Thanks.
PS: now I only uploaded the image and display it directly using an ImageView but I want to make it available in my application when the user is offline.
for my experience the best way to do achieve this is savin my images from internet to the sdcard cause the file access is faster.
function to create my images directory in my sdcard...
public static File createDirectory(String directoryPath) throws IOException {
directoryPath = Environment.getExternalStorageDirectory().getAbsolutePath() + directoryPath;
File dir = new File(directoryPath);
if (dir.exists()) {
return dir;
}
if (dir.mkdirs()) {
return dir;
}
throw new IOException("Failed to create directory '" + directoryPath + "' for an unknown reason.");
}
example:: createDirectory("/jorgesys_images/");
I use this functions to save my images from internet to my own folder into the sdcard
private Bitmap ImageOperations(Context ctx, String url, String saveFilename) {
try {
String filepath=Environment.getExternalStorageDirectory().getAbsolutePath() + "/jorgesys_images/";
File cacheFile = new File(filepath + saveFilename);
cacheFile.deleteOnExit();
cacheFile.createNewFile();
FileOutputStream fos = new FileOutputStream(cacheFile);
InputStream is = (InputStream) this.fetch(url);
BitmapFactory.Options options=new BitmapFactory.Options();
options.inSampleSize = 8;
Bitmap bitmap = BitmapFactory.decodeStream(is);
bitmap.compress(CompressFormat.JPEG,80, fos);
fos.flush();
fos.close();
return bitmap;
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public Object fetch(String address) throws MalformedURLException,IOException {
URL url = new URL(address);
Object content = url.getContent();
return content;
}
you will use this Bitmpap into your imageView, and when you are offline you will get the images directly from your sdcard.