Read images in drawable as File - android

I want to read all the Images in drawable folder as File object and store them in an array of File.
Is there a way to get list of all images in drawable and read them as File?
Edit: I need to know the following..
How to collect all the images from drawable folder. My images have different meaningful name based on the content. There is no common pattern in the name.
How to read these images as File.

No, because they are not files on the device. They are only files on your development machine. Resources are entries in the APK itself at runtime.

First you need to convert all drawable to bitmap and save to Local Storage then read it as File
You can get all Drawables from this method
public Drawable[] getAllDrawables()
{
Field[] ID_Fields = R.drawable.class.getFields();
Drawable[] drawables = new Drawable[ID_Fields.length];
for(int i = 0; i < ID_Fields.length; i++) {
try {
drawables[i] = ContextCompat.getDrawable(this,ID_Fields[i].getInt(null));
} catch (IllegalArgumentException | IllegalAccessException ignored) {
return null;
}
}
return drawables;
}
Possible Duplicate
Here

Related

How I access asset folder?

I need to load image from assets in folder like this
my folder
and my code just check that how i can access my folder (sorry from poor coding)
public Bitmap test3(){
Bitmap bitmap = null;
AssetManager assManager = null;
try {
InputStream is = assManager.open("train/c00/Astb412_400_30_18_161.bmp");
bitmap = BitmapFactory.decodeStream(is);
return bitmap;
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
So, I just test debug to see but it didn't work
test debug
I don't know how I access file. please help
I should put my folder in res or asset which one is better?
Can I path folder by string path (I've tried it but didn't work for me)
Better and most suitable way is to put your asset in res folder. After that you can assess them like this.
Drawable image = getResources().getDrawable(R.drawable.your_file_name_goes_here);

How to get the extension of Files of resources?

In android, I need to load a set of images from res/drawable directory
I use the following code:
Field[] fields = R.drawable.class.getFields();
List<Picture> pictures = new ArrayList<>();
for (Field field : fields) {
String name = field.getName();
if (name.startsWith("img")) {
Picture picture = new Picture(name);
pictures.add(picture);
}
}
Among all files in 'drawable', it finds all files starting as a string 'img'.
For this code to work correctly, I have to manually change the names of image files by myself.
If I can get the extension of each resource in drawable (such as jpg, png, etc.), I don't need to change the file name like this.
Is there any way to achieve this?
I appreciate your help, thanks :D
I answer my question.
I moved all the image files into "asset/imgs"
and use the following code to load them
List<Picture> pictures = new ArrayList<>();
try {
String[] images = assetManager.list("imgs");
for (String name : images) {
Picture picture = new Picture(name);
pictures.add(picture);
}
} catch (IOException e) {
// you can print error or log.
throw new RuntimeException(e);
}

Getting ID of bitmap on SD card

My app has a section where some images are displayed in a gridview.
Before the gridview is set up, the following is done:
Download list of image file names from the internet
Compare this list to items already present in the Drawable folder
If the image is not present in the Drawable folder, download it and save it to the SD card.
When setting up the gridview I do it by using the drawable IDs, which are easy to get as they are in a resource folder ("drawable").
But if I need to include the SD card images as well in the gridview, how can I retrive their IDs?
Files anywhere other than those packaged with your app (downloaded to the internal or external storage, for instance) don't have resource ids.
Resource ids are a shorthand way of referencing the packaged resources such as strings, images, whatever. These ids are created at build-time and only have meaning for internal resources.
In order to use images obtained from an external source, you access them by filename and, I presume, you'll then create ImageViews which are added to your GridView.
If you need to discern between the different images of the grid (perhaps for touch/click purposes) then it's the ImageView that you deal with rather than being concerned with resource ids or filenames of the images they contain.
I was having a code to get images from sdcard and convert them into an array of URIs, the ids are like URIs, use them.
private void getData() {
File f = new File("/mnt/sdcard/");
File[] imagelist = f.listFiles(new FilenameFilter(){
public boolean accept(File dir, String name)
{
return ((name.endsWith(".jpg"))||(name.endsWith(".png")));
}
});
mFiles = new String[imagelist.length];
for(int i= 0 ; i< imagelist.length; i++)
{
mFiles[i] = imagelist[i].getAbsolutePath();
}
mUrls = new Uri[mFiles.length];
for(int i=0; i < mFiles.length; i++)
{
mUrls[i] = Uri.parse(mFiles[i]);
}
}
You can use the uri like this:-
ImageView imageView=new ImageView(this);
imageView.setImageURI(mUrls[i]);

Android Show image by path

i want to show image in imageview without using id.
i will place all images in raw folder and open
try {
String ss = "res/raw/images/inrax/3150-MCM.jpg";
in = new FileInputStream(ss);
buf = new BufferedInputStream(in);
Bitmap bMap = BitmapFactory.decodeStream(buf);
image.setImageBitmap(bMap);
if (in != null) {
in.close();
}
if (buf != null) {
buf.close();
}
} catch (Exception e) {
Log.e("Error reading file", e.toString());
}
but this is not working i want to access image using its path not by name
read a stream of bytes using openRawResource()
some thing like this should work
InputStream is = context.getResources().openRawResource(R.raw.urfilename);
Check this link
http://developer.android.com/guide/topics/resources/accessing-resources.html#ResourcesFromCode
It clearly says the following
While uncommon, you might need access your original files and directories. If you do, then saving your files in res/ won't work for you, because the only way to read a resource from res/ is with the resource ID
If you want to give a file name like the one mentioned in ur code probably you need to save it on assets folder.
You might be able to use Resources.getIdentifier(name, type, package) with raw files. This'll get the id for you and then you can just continue with setImageResource(id) or whatever.
int id = getResources().getIdentifier("3150-MCM", "raw", getPackageName());
if (id != 0) //if it's zero then its not valid
image.setImageResource(id);
is what you want? It might not like the multiple folders though, but worth a try.
try {
// Get reference to AssetManager
AssetManager mngr = getAssets();
// Create an input stream to read from the asset folder
InputStream ins = mngr.open(imdir);
// Convert the input stream into a bitmap
img = BitmapFactory.decodeStream(ins);
} catch (final IOException e) {
e.printStackTrace();
}
here image directory is path of assets
like
assest -> image -> somefolder -> some.jpg
then path will be
image/somefolder/some.jpg
now no need of resource id for image , you can populate image on runtime using this

How to get access to raw resources that I put in res folder?

In J2ME, I've do this like that:
getClass().getResourceAsStream("/raw_resources.dat");
But in android, I always get null on this, why?
For raw files, you should consider creating a raw folder inside res directory and then call getResources().openRawResource(resourceName) from your activity.
InputStream raw = context.getAssets().open("filename.ext");
Reader is = new BufferedReader(new InputStreamReader(raw, "UTF8"));
In some situations we have to get image from drawable or raw folder using image name instead if generated id
// Image View Object
mIv = (ImageView) findViewById(R.id.xidIma);
// create context Object for to Fetch image from resourse
Context mContext=getApplicationContext();
// getResources().getIdentifier("image_name","res_folder_name", package_name);
// find out below example
int i = mContext.getResources().getIdentifier("ic_launcher","raw", mContext.getPackageName());
// now we will get contsant id for that image
mIv.setBackgroundResource(i);
Android access to raw resources
An advance approach is using Kotlin Extension function
fun Context.getRawInput(#RawRes resourceId: Int): InputStream {
return resources.openRawResource(resourceId)
}
One more interesting thing is extension function use that is defined in Closeable scope
For example you can work with input stream in elegant way without handling Exceptions and memory managing
fun Context.readRaw(#RawRes resourceId: Int): String {
return resources.openRawResource(resourceId).bufferedReader(Charsets.UTF_8).use { it.readText() }
}
TextView txtvw = (TextView)findViewById(R.id.TextView01);
txtvw.setText(readTxt());
private String readTxt()
{
InputStream raw = getResources().openRawResource(R.raw.hello);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int i;
try
{
i = raw.read();
while (i != -1)
{
byteArrayOutputStream.write(i);
i = raw.read();
}
raw.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return byteArrayOutputStream.toString();
}
TextView01:: txtview in linearlayout
hello:: .txt file in res/raw folder (u can access ny othr folder as wel)
Ist 2 lines are 2 written in onCreate() method
rest is to be written in class extending Activity!!
getClass().getResourcesAsStream() works fine on Android. Just make sure the file you are trying to open is correctly embedded in your APK (open the APK as ZIP).
Normally on Android you put such files in the assets directory. So if you put the raw_resources.dat in the assets subdirectory of your project, it will end up in the assets directory in the APK and you can use:
getClass().getResourcesAsStream("/assets/raw_resources.dat");
It is also possible to customize the build process so that the file doesn't land in the assets directory in the APK.
InputStream in = getResources().openRawResource(resourceName);
This will work correctly. Before that you have to create the xml file / text file in raw resource. Then it will be accessible.
Edit Some times com.andriod.R will be imported if there is any error in layout file or image names. So You have to import package correctly, then only the raw file will be accessible.
This worked for for me: getResources().openRawResource(R.raw.certificate)

Categories

Resources