Is it possible to load a drawable from the assets folder? - android

Can you load a drawable from a sub directory in the assets (not the drawable folder) folder?

Hope this help:
Drawable d = Drawable.createFromStream(getAssets().open("Cloths/btn_no.png"), null);

I recommend to use this
Drawable.createFromResourceStream(resources,new TypedValue(), resources.getAssets().open(filename), null)
which returns properly scaled drawable thanks to resources ...

Here's a class with static method to get the drawable from the assets. It also closes the inputstream.
import android.content.Context;
import android.graphics.drawable.Drawable;
import java.io.IOException;
import java.io.InputStream;
/**
* Created by bartburg on 4-11-2015.
*/
public class AssetsReader {
public static Drawable getDrawableFromAssets(Context context, String url){
Drawable drawable = null;
InputStream inputStream = null;
try {
inputStream = context.getAssets().open(url);
drawable = Drawable.createFromStream(inputStream, null);
} catch (IOException e) {
e.printStackTrace();
} finally {
if(inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return drawable;
}
}

Yes you can create a Drawable object from an InputStream using the createFromStream() method.

Here is function that does this for you.
Check the returned Drawable variable for null as null may return if the path is invalid or there is an IOException.
public static Drawable getDrawableFromAssetFolder(String fullPath, Activity ctx) {
Drawable d =null;
try {
d = Drawable.createFromStream(ctx.getAssets().open(fullPath), null);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return d;
}

This helped getting the right density
private Drawable drawableFromAssetFilename(String filename) {
AssetManager assetManager = mApplicationContext.getAssets();
InputStream inputStream = null;
try {
inputStream = assetManager.open(filename);
} catch (IOException e) {
e.printStackTrace();
}
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
BitmapDrawable drawable = new BitmapDrawable(mApplicationContext.getResources(), bitmap);
return drawable;
}

I was working in a RecyclerView adapter and found that David's answer was not working for me, (for some reason asset.open remained Unresolved no matter what I imported )
so I found this to work for me (Kotlin code)
val d = Drawable.createFromStream(context?.assets?.open("imageData/${imageName}.png"), null)
here is my directory, as you can see the assets start from the assets folder and here is a link on how to create that assets folder

At this version you can't, if you make a sub folder within your drawable folder you can't use it in your xml file, it won't be recognized when you use android:src.
Take a look at this thread: Can the Android drawable directory contain subdirectories?

Related

imageView.setImageBitmap(bitmap) allways null while bitmap not null

i pass a String photo path to another activity, then i convert it to Uri (because photo path was converted from Uri), then i made the inputstream by uri, and made bitmap by that inputstream. bitmap is created and not null, but when i call imageView.setImagebitmap(bitmap), system give error that:
void android.widget.ImageView.setImageURI(android.net.Uri)' on a null object reference.
private void showImage(Uri mPath) {
PhotoPath=mPath.toString();
InputStream is = null;
try {
is = getContentResolver().openInputStream(mPath);
Bitmap bitmap = BitmapFactory.decodeStream(is);
is.close();
photo.setImageURI(mPath);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
what problem i met, please help me ! thank you
It sounds like your ImageView itself is null. Resolving that problem will probably fix your error.

Load images from assets folder ( error loading *.png )

I wrote the code loader images from assets folder following the example code
my code
I don't know why load *.png not work. JPG work.
JPG work
Bitmap bitmap = decodeStreamFromAssets("test.jpg", 64, 64);
if(bitmap != null){
imageViewTest.setImageBitmap(bitmap);
}
else {
Logs.e("error");
}
PNG not work ( is error )
Bitmap bitmap = decodeStreamFromAssets("test.png", 64, 64);
if(bitmap != null){
imageViewTest.setImageBitmap(bitmap);
}
else {
Logs.e("error");
}
There are two ways by which you can load image from assets folder.
Solution 1:
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.test, null);
imageViewTest.setImageBitmap(bitmap);
Solution 2:
InputStream ins = null;
try {
ins = getAssets().open("test.png");
Bitmap bitmap = BitmapFactory.decodeStream(ins);
imageViewTest.setImageBitmap(bitmap);
} catch (final IOException e) {
e.printStackTrace();
} finally {
if (ins != null)
try {
ins.close();
} catch (IOException e) { }
}
I suggest to use second one because good performance.
Running both functions 50 times to load a small PNG file (230*230) on Nexus
Galaxy running Android 4.2.2:
decodeResource: 1793ms
decodeStream: 188ms
where the decodeStreamFromAssets?
InputStream is = getAssets().open("ic_launcher.png");
Bitmap bitmap = BitmapFactory.decodeStream(is);
it work!

Image File not found exception android

Am trying to add icons to the grid dynamically based on the path provided by service,
i have added the icons inside the assets folder, am getting file not found exception, how can i fix it.
Below is my code,
try
{
InputStream im = context.getAssets().open(App.Path);
Drawable d = Drawable.createFromStream(im, null);
}
catch(IOException e)
{
e.printStackTrace();
}
I see you have "Profile Registration.png" -> rename the file so it does not contain spaces. Something like: "profile_registration.png"
Actually the problem is with prefix /assets/ :)
try {
String image = App.Path;
if (image.contains("/assets/")) {
image = image.replace("/assets/", "");
}
InputStream ims = getAssets().open(image);
Drawable d = Drawable.createFromStream(ims, null);
imageView.setImageDrawable(d);
} catch (IOException ex) {
return;
}
Please Check Your files availablity.
If Files there,do following instructions
Instead of
InputStream im = context.getAssets().open(App.Path);
please use this
InputStreamReader im = new InputStreamReader(getApplicationContext().getAssets().open("path name upto file")));
Please Use this.It will work
Try this:
try {
String image_path = App.Path;
String filepath = null;
if (image_path.contains("/ASSETS/")) {
filepath = image_path .replace(ASSETS, "");
}
InputStreamReader im = new InputStreamReader(getApplicationContext().getAssets().open(filepath)));
Drawable d = Drawable.createFromStream(ims, null);
imageView.setImageDrawable(d);
} catch (IOException ex) {
return;
}

Android : cannot read image in assets folder and assign to imageview

I have a file food.jpg in assets folder. I have try many ways. but I still cannot get this image into imageView. when run, instead of display image "food.jpg", it displays image that I have declared in xml file. (that image is in drawable folder).
The first way is:
int asset_id = context.getResources().getIdentifier("food", "drawable", context.getPackageName());
imageView.setImageResource(asset_id);
The second way is:
AssetManager assetManager = context.getAssets();
InputStream istr;
try {
istr = assetManager.open("food");
Bitmap bitmap = BitmapFactory.decodeStream(istr);
imageView.setImageBitmap(bitmap);
istr.close();
} catch (IOException e) {
e.printStackTrace();
}
Please teach me how to fix this problem.
thanks :)
Your code is working fine. just add image MIME-Type(.jpg,jpeg,.png... etc) in below line:
istr = assetManager.open("ceo.jpg");
full code for your refrance
AssetManager assetManager = getAssets();
InputStream istr;
try {
istr = assetManager.open("ceo.jpg");
Bitmap bitmap = BitmapFactory.decodeStream(istr);
imageView.setImageBitmap(bitmap);
istr.close();
} catch (IOException e) {
e.printStackTrace();
}
Try this Code...
try {
// get input stream
InputStream ims = getAssets().open("food.jpg");
// load image as Drawable
Drawable d = Drawable.createFromStream(ims, null);
// set image to ImageView
imgNews.setImageDrawable(d);
} catch (Exception ex) {
return;
}
}

Loading images from cache but return a blank screen

i try the example i gotten from here. The example shows how to display a image that is larger then the screen and the screen acting like a window, allowing user to look at the images via scrolling. However, what i want to achieved is similar just that, instead of one single image, i tried to combining 18 smaller images (171X205) into one single image. I am able to did that but to save loading time on downloading of images from the server, i cached the images. Heres the problem, i cant seems to display the images out on screen even though the images are indeed cached. Thus, i tried something else by fetching image from the drawable folder but still the same issue arise. Does anyone have any idea how to go about solving this problem?
A snippets of code to load images from cache:
for(int i =0; i<18; i++)
File cacheMap = new File(context.getCacheDir(), smallMapImageNames.get(i).toString());
if(cacheMap.exists()){
//retrieved from cached
try {
FileInputStream fis = new FileInputStream(cacheMap);
Bitmap bitmap = BitmapFactory.decodeStream(fis)
puzzle.add(bitmap);
}catch(...){}
}else{
Drawable smallMap = LoadImageFromWebOperations(mapPiecesURL.get(i).toString());
if(i==0){
height1 = smallMap.getIntrinsicHeight();
width1 = smallMap.getIntrinsicWidth();
}
if (smallMap instanceof BitmapDrawable) {
Bitmap bitmap = ((BitmapDrawable)smallMap).getBitmap();
FileOutputStream fos = null;
try {
cacheMap.createNewFile();
fos = new FileOutputStream(cacheMap);
bitmap.compress(CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
puzzle.add(bitmap);
}
}
}
The function where it retrieved images from the server
private Drawable LoadImageFromWebOperations(String url) {
// TODO Auto-generated method stub
try
{
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
}catch (Exception e) {
System.out.println("Exc="+e);
return null;
}
}
I am drawing onto a canvas and so no ImageView is use to display the images.
For all of my lazy image loading I use Prime.

Categories

Resources