issues to save and retrieve the image in android? - android

I have an application that uses a canvas function, I want to save and retrieve all images (whatever I saved).?
issues
I can save and retrieve the single image only
Dynamically I save the image,(image001,image002......)
update
try {
toDisk.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(new File("/mnt/sdcard/image00"+saveimageid+".jpg")));
saveimageid++;
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I retrieve the image from image001.
File imgFile = new File("/mnt/sdcard/image001.jpg");
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
ImageView myImage = (ImageView) findViewById(R.id.ImageView01);
myImage.setImageBitmap(myBitmap);

I'm guessing you want to load all the files that match imageXYZ.jpg.
I have no idea why you save the files like "00"+saveimageid+".jpg.
If you want to make sure the filename is equally long (or at least three positions) do something like
new File(String.format("/mnt/sdcard/image%03d.jpg", saveimageId))
To retrieve the files you might
File dir = new File("/mnt/sdcard/");
File[] images = dir.listFiles(new FilenameFilter() {
#Override
public boolean accept(final File dir, final String filename) {
return filename.matches("image[0-9]+\\.jpg");
}
});
Then you can use the images array however you please.
As a sidenote: If this is Android you should not assume that external storage is placed in /mnt/sdcard. Use Environment.getExternalStorageDirectory()

Related

How to make Glide use previously downloaded image as placeholder

Is it possible to show previously downloaded image in Glide as placeholder while downloading new image.
Like I have an image loaded in imageview using glide. Now the imageurl is changed, so while loading this new image is it possible to keep displaying the old image (might be from cache).
What I want is while the new image is being loaded from the URL, is it possible to keep the current image as placeholder.
I found the answer to this in the discussion here - https://github.com/bumptech/glide/issues/527#issuecomment-148840717.
Intuitively I also thought of using placeholder(), but the problem is that as soon as you load the second image, you loose the reference to the first one. You can still reference it but it is not safe as it may be reused by Glide or recycled.
The proposed solution from the discussion is to use thumbnail() and load the first image again. The load will return the first image immediately from the memory cache and it will look as if the image did not change until the second image is loaded:
String currentImageUrl = ...;
String newImageUrl = ...;
Glide.with(this)
.load(newImageUrl)
.thumbnail(Glide.with(this)
.load(currentImageUrl)
.fitCenter()
)
.fitCenter()
.into(imageView);
Glide have a capability of getting the bitmap of the image from that url, so just get it and then save it to a desired storage into your phone, and after that in your .placeholder() just use that bitmap when you are trying to get another image , take a look at this snippet
/** Download the image using Glide **/
Bitmap theBitmap = null;
theBitmap = Glide.
with(YourActivity.this).
asBitmap().
load("Url of your image").
into(-1, -1).
get(); //with this we get the bitmap of that url
saveToInternalStorage(theBitmap, getApplicationContext(), "your preferred image name");
/** Save it on your device **/
public String saveToInternalStorage(Bitmap bitmapImage, Context context, String name){
ContextWrapper cw = new ContextWrapper(context);
// path to /data/data/yourapp/app_data/imageDir
String name_="foldername"; //Folder name in device android/data/
File directory = cw.getDir(name, Context.MODE_PRIVATE);
// Create imageDir
File mypath=new File(directory,name_);
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();
}
Log.e("absolutepath ", directory.getAbsolutePath());
return directory.getAbsolutePath();
}
/** Method to retrieve image from your device **/
public Bitmap loadImageFromStorage(String path, String name)
{
Bitmap b;
String name_= name; //your folderName
try {
File f=new File(path, name_);
b = BitmapFactory.decodeStream(new FileInputStream(f));
return b;
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
return null;
}
/** Retrieve your image from device and set to imageview **/
//Provide your image path and name of the image your previously used.
Bitmap b= loadImageFromStorage(String path, String name)
ImageView img=(ImageView)findViewById(R.id.your_image_id);
img.setImageBitmap(b);

internal storage for app and uri

So I'm using the twitter api and I want to tweet with an image I use:
TweetUri = Uri.fromFile(saveIT);
TweetComposer.Builder builder = new TweetComposer.Builder(this)
.text("")
.image(TweetUri);
builder.show();
The original image is a bitmap, so what I did (not sure if this is the optimal way) was save in the internal storage:
private File 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
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmmss").format(new Date());
String mImageName="MI_"+ timeStamp +".jpg";
File mypath=new File(directory,mImageName);
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(Exception e)
{
e.printStackTrace();
}
}
return mypath;
}
The file it returns will be the "saveIT" in the TweetUri when it does the fromfile method. Of course this will overload the storage so what I plan to do is wipe the internal storage for the app when it is stopped (no other data is saved in the internal storage other than the temp images I save for the tweet):
#Override
protected void onStop() {
super.onStop();
File MSD = this.getApplicationContext().getFilesDir();
File [] lisFiles = MSD.listFiles();
for(int i=0;i<lisFiles.length;i++)
{
boolean deleted = lisFiles[i].delete();
}
}
None of this works... I can't seem to find any of the images when I save them to verify if the deleting is happening. Also, when the user clicks tweet no image is added to the tweet as well. No idea what I'm doing wrong here... In reality I don't want to save the image in the internal storage but I do because the tweet api uses a URI to tweet and not a bitmap.
I switched it to write to external storage and it worked fine. Also I switched it to delete at onDestroy. This is better because, when I invoke the Twitter API it switches activities so the onstop is invoked which would delete the temp picture too early. It's too early becuase if the user clicks cancel at the twitter api, comes back to my api and then invokes the twitter api again the uri will point to nothing since the picture was already deleted. THATS ALL FOLKS :)

How create Custom gallery by reading all images stored in android internal storage

I am developing an android app in which i am saving images in a specified folder after some editing.Now i want to show all these stored images in my activity. I m able to show a particular image by specifying a particular name.But i want to show all images together.. Thank in advance.
I m using Following code to show single image......
File myDir=new File("/sdcard/MyCollection");
myDir.mkdirs();
try {
File f=new File(myDir, "My Image name.jpg");
Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
ImageView img=(ImageView)findViewById(R.id.imageView);
img.setImageBitmap(b);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
if i follow your question, than you can retrieve the list of file with .jpg extension run a loop on list and show in imageview.
File root = new File("/sdcard/MyCollection");
final String files[] = root.list(imageFilter);
FilenameFilter imageFilter = new FilenameFilter() {
File f;
public boolean accept(File dir, String name) {
if(name.endsWith(".jpg")) {
return true;
}
f = new File(dir.getAbsolutePath()+"/"+name);
return f.isDirectory();
}
};
files will return an array of files.You can loop on it.

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);
}
}

creating a drawable from sd card to set as a background in android

I am trying to use an image from the sd card and set it as the background for a relativelayout. I have tried other solutions that i have found here and elsewhere but they havent seemed to work for me. here is my code. I have commented out other ways that i have tried and didnt work. the only thing that worked for me was using setBackgroudnResource and using a resource from the app, but this was just to test to make sure mRoot was set up correctly. when I have tried all the other ways, it just doesn't set anything. Anyone know what I am doing wrong, or if there is a better way to do this?
//one way i tired...
//String extDir = Environment.getExternalStorageDirectory().toString();
//Drawable d = Drawable.createFromPath(extDir + "/pic.png");
//mRoot.setBackgroundDrawable(d);
//another way tried..
//Drawable d = Drawable.createFromPath("/sdcard/pic.png");
//mRoot.setBackgroundDrawable(d);
//last way i tried...
mRoot.setBackgroundDrawable(Drawable.createFromPath(new File(Environment.getExternalStorageDirectory(), "pic.png").getAbsolutePath()));
//worked, only to verify mRoot was setup correctly and it could be changed
//mRoot.setBackgroundResource(R.drawable.bkg);
You do not load a drawable from SD card but a bitmap. Here is a method to load it with the reduced sampling (quality) so the program will not complain if the image is too large. Then I guess you need to process this bitmap i.e. crop it and resize for the background.
// Read bitmap from Uri
public Bitmap readBitmap(Uri selectedImage) {
Bitmap bm = null;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2; //reduce quality
AssetFileDescriptor fileDescriptor =null;
try {
fileDescriptor = this.getContentResolver().openAssetFileDescriptor(selectedImage,"r");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
finally{
try {
bm = BitmapFactory.decodeFileDescriptor(fileDescriptor.getFileDescriptor(), null, options);
fileDescriptor.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return bm;
}
The Uri here can be supplied from a gallery picker activity.
The image then can be saved into application resources and loaded into an imageView
private void saveBackground(Bitmap Background) {
String strBackgroundFilename = "background_custom.jpg";
try {
Background.compress(CompressFormat.JPEG, 80, openFileOutput(strBackgroundFilename, MODE_PRIVATE));
} catch (Exception e) {
Log.e(DEBUG_TAG, "Background compression and save failed.", e);
}
Uri imageUriToSaveCameraImageTo = Uri.fromFile(new File(BackgroundSettings.this.getFilesDir(), strBackgroundFilename));
// Load this image
Bitmap bitmapImage = BitmapFactory.decodeFile(imageUriToSaveCameraImageTo.getPath());
Drawable bgrImage = new BitmapDrawable(bitmapImage);
//show it in a view
ImageView backgroundView = (ImageView) findViewById(R.id.BackgroundImageView);
backgroundView.setImageURI(null);
backgroundView.setImageDrawable(bgrImage);
}
File file = new File( url.getAbsolutePath(), imageUrl);
if (file.exists()) {
mDrawable = Drawable.createFromPath(file.getAbsolutePath());
}
I suggest checking that the drawable is being loaded correctly. Some things to try:
Try using a different image on the sd card
Put pic.png in R.drawable and make sure mRoot.setBackgroundResource() does what you expect
After loading the drawable, check d.getBounds() to make sure it is what you expect

Categories

Resources