Getting path of local image instead of URL Android - android

I am working with gif images at the moment and have followed the answer from the question here
From this I have the following line of code:
GifWebView view = new GifWebView(this, "http://cdn.lifebuzz.com/images/17487/lifebuzz-35df9a5ee351ae72711e5a293658e319-limit_2000.gif");
Now, I want to download this image, save it locally in the "drawable" folder or "assets" folder and then access it from there.
I have tried downloading the image into the "drawable" folder and trying :
GifWebView view = new GifWebView(this, "#drawable/myimg.gif");
I have also tried this:
int imageResource = R.drawable.myimg;
Drawable image = getResources().getDrawable(imageResource);
String imageUri = "drawable://" + R.drawable.myimg;
GifWebView view = new GifWebView(this, imageUri);
Still no luck.
I've tried accessing it from the assets folder but this seemed even more complicated.
I just would like to save it locally and access it locally, I don't really care where it is stored.
Thanks for any help.
EDIT
public GifWebView(Context context, String path) {
super(context);
loadUrl(path);
}

Related

Android studio fileFilter with assetManager

I have the following functionality to a desktop application with java and I want to do the same thing for a mobile application.
File f = new File(pathToFiles);
File[] files = f.listFiles(new FileFilter() {
#Override
public boolean accept(File pathname) {
return (pathname.getName().endsWith(".img") ? true : false);
}
});
Now in my android class I access the same files stored in a folder inside assets using the AssetManager with the following way:
AssetManager assetManager = context.getAssets();
String[] files = assetManager.list("folderInsideAssets");
List<String> it = new LinkedList<String>(Arrays.asList(files));
The problem here is that I get them as string in a list instead of a File class like in plain java.
Is a way to convert it to a File[] class and proceed with the same way or I should handle this differently?
Thank you in advance!
Stackoverflow Question on loading pictures from asset
Yes, create another folder in assets directory. use getAssets().list(<folder_name>) for getting all file names from assets:
String[] images =getAssets().list("images");
ArrayList<String> listImages = new ArrayList<String>(Arrays.asList(images));
Now to set image in imageview you first need to get bitmap using image name from assets :
InputStream inputstream=mContext.getAssets().open("images/"
+listImages.get(position));
Drawable drawable = Drawable.createFromStream(inputstream, null);
imageView.setImageDrawable(drawable);

How to show last taken image from specific folder?

I want to make a feature like default camera feature did. There are a left thumbnail image which show last taken image. When click to the photo, it show the photo and I can slide to view next photo.
My photos is put on "Abc/Pictures" folder.
To get the latest modified file in folder for specific extension
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.comparator.LastModifiedFileComparator;
import org.apache.commons.io.filefilter.WildcardFileFilter;
...
/* Get the newest file for a specific extension */
public File getTheNewestFile(String filePath, String ext) {
File theNewestFile = null;
File dir = new File(filePath);
FileFilter fileFilter = new WildcardFileFilter("*." + ext);
File[] files = dir.listFiles(fileFilter);
if (files.length > 0) {
/** The newest file comes first **/
Arrays.sort(files, LastModifiedFileComparator.LASTMODIFIED_REVERSE);
theNewestFile = files[0];
}
return theNewestFile;
}
Addition
To get all files or only png and jpeg use
new WildcardFileFilter("*.*");
new WildcardFileFilter(new String[]{"*.png", "*.jpg"});
Use below code find latest images from folder and I hope you are saving images with there time stamp which is standard appraoch.
File path = new File(Environment.getExternalStorageDirectory()
.getPath() + "/Abc/Pictures");
int imagesCount= path .listFiles().length; // get the list of images from folder
Bitmap bmp = BitmapFactory.decodeFile(sdcardPath.listFiles()[imagesCount - 1].getAbsolutePath());
eachImageView.setImageBitmap(bmp); // set bitmap in imageview

Read and load images from SDcard asynchronously - fail

I'd like to load image which is on SDCARD in folder to imageView of my cell in listView. I've tried different solutions but each of them fails. When I load images normally as it is in every base tutorial everything works. I've observed that, my application slows down when it has to load many images. Images are taken from photo camera of device. I'd like to load each of them asynchronously to avoid UI slow reaction. I've tried to use Thread, Asynctask but each of them throws error: "Only the oryginal thread that created a view hierarchy can touch its views". How to load images to avoid speed problems? SDImageLoader is a class which is possible to get from GITHUB. What I've tried is a standard code but is slows:
In a getView method in ListAdapter:
File imageFile = new File(Options.PATH_TO_FOLDER_PHOTOS_OF_APP + "test.png");
String imageFileString = Options.PATH_TO_FOLDER_PHOTOS_OF_APP + "test.png";
// "test.png" is a test file. Each cell will have different name of file to load.
if(imageFile.exists())
{
Bitmap myBitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
image.setImageBitmap(myBitmap);
// final SDImageLoader loader = new SDImageLoader(context);
// new SDImageLoader().load(imageFileString, image);
//UrlImageViewHelper.setUrlDrawable(image, url);
}
else
{
final SDImageLoader loader = new SDImageLoader();
Resources resources = context.getResources();
int resurceId;
resurceId = resources.getIdentifier("bad", "drawable",context.getPackageName());
loader.load(imageFileString, image);
image.setImageResource(resurceId);
}
Have you tried to refresh your project after adding an external library to your project? It doesn't matter with the fragment. You send exact context to the List Adapter - which should be fragment.this.getActivity().

Populate Android Gallery from image file paths?

I have some images that are saved to a directory on the Android device when the application starts--I would like to be able to display these images in a Gallery, but so far I haven't been able to do it.
I was following the sample Gallery code here, but it uses drawable resource IDs instead of file paths. I found this solution that is similar to what I'm looking for, except it uses ImageView instead of Gallery.
So the code using ImageView would look something like this:
File imgFile = new File(“/data/data/com.myproject.example/files/someImage.png”);
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
ImageView myImage = (ImageView) findViewById(R.id.imageviewTest);
myImage.setImageBitmap(myBitmap);
}
The above code works, but I'm not sure how to do it with a Gallery. I have been searching for answers and trying different things, but I'm v new to Android development and I feel like I'm in a bit over my head.
Any help is appreciated. Thank you in advance.
Basically I think you just need to put your two examples together.
Use the HelloGallery example as a start, however you want to change the code inside the getView() method of the ImageAdapter to call setImageBitmap() on the ImageView instead of setImageResource().
You will need an array/collection of file paths of images you want to load.
What you need to do is something like this:
public ImageAdapter(Context c, int itemId) {
context = c;
imgArr = GlobalStore.getItem(itemId).getPhotos();
TypedArray attr = context.obtainStyledAttributes(R.styleable.HelloGallery);
mGalleryItemBackground = attr.getResourceId(R.styleable.HelloGallery_android_galleryItemBackground, 0);
attr.recycle();
}
as you can see this is basically a copy from Gallery tutorial. In the constructor imgArr variable is loaded with an array of JPG file names. These were for example read from a database.
Then in the getView function you have something like this...
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(context);
String tmpStr = appContext.getFilesDir() + File.separator + "photos" + File.separator + imgArr.get(position);
Bitmap bitmap = BitmapFactory.decodeFile(tmpStr);
imageView.setImageBitmap(bitmap);
imageView.setLayoutParams(new Gallery.LayoutParams(350, 300));
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setBackgroundResource(mGalleryItemBackground);
return imageView;
}
As you can see getFilesDir() gets your applications data location where it stores files, then let's imagine all photos are in "photos" directory, you build a path and attach a file name from the imgArr array. Since this is called for every photo you just use the passed position variable.
If you don't have an array of photos then maybe the way is to build it by reading the directory where you store photos, load all of the filenames in an array and then do this.
Then you do the rest on the gallery side as in the gallery tutorial.

Android get image path from drawable as string

Is there any way that I can get the image path from drawable folder in android as String. I need this because I implement my own viewflow where I'm showing the images by using their path on sd card, but I want to show a default image when there is no image to show.
Any ideas how to do that?
These all are ways:
String imageUri = "drawable://" + R.drawable.image;
Other ways I tested
Uri path = Uri.parse("android.resource://com.segf4ult.test/" + R.drawable.icon);
Uri otherPath = Uri.parse("android.resource://com.segf4ult.test/drawable/icon");
String path = path.toString();
String path = otherPath .toString();
based on the some of above replies i improvised it a bit
create this method and call it by passing your resource
Reusable Method
public String getURLForResource (int resourceId) {
//use BuildConfig.APPLICATION_ID instead of R.class.getPackage().getName() if both are not same
return Uri.parse("android.resource://"+R.class.getPackage().getName()+"/" +resourceId).toString();
}
Sample call
getURLForResource(R.drawable.personIcon)
complete example of loading image
String imageUrl = getURLForResource(R.drawable.personIcon);
// Load image
Glide.with(patientProfileImageView.getContext())
.load(imageUrl)
.into(patientProfileImageView);
you can move the function getURLForResource to a Util file and make it static so it can be reused
If you are planning to get the image from its path, it's better to use Assets instead of trying to figure out the path of the drawable folder.
InputStream stream = getAssets().open("image.png");
Drawable d = Drawable.createFromStream(stream, null);
I think you cannot get it as String but you can get it as int by get resource id:
int resId = this.getResources().getIdentifier("imageNameHere", "drawable", this.getPackageName());
First check whether the file exists in SDCard. If the file doesnot exists in SDcard then you can set image using setImageResource() methodand passing default image from drawable folder
Sample Code
File imageFile = new File(absolutepathOfImage);//absolutepathOfImage is absolute path of image including its name
if(!imageFile.exists()){//file doesnot exist in SDCard
imageview.setImageResource(R.drawable.defaultImage);//set default image from drawable folder
}

Categories

Resources