How to Load a Image from Assets?

i need to load a image from assets to avoid a froyo 2.2.2 bug resizing POT images in some particular cases. The way to avoid it is loading the image files from assets dir.

I'm trying to do with this:

String imagePath = "radiocd5.png";
AssetManager mngr = context.getAssets();
// Create an input stream to read from the asset folder
InputStream is = null;
try {
    is = mngr.open(imagePath);
} catch (IOException e1) { e1.printStackTrace();}
    
//Get the texture from the Android resource directory
//InputStream is = context.getResources().openRawResource(R.drawable.radiocd5);
Bitmap bitmap = null;
try {
    //BitmapFactory is an Android graphics utility for images
    bitmap = BitmapFactory.decodeStream(is);

} finally {
    //Always clear and close
    try {
        is.close();
        is = null;
    } catch (IOException e) {}
}

But i am getting NullPointerException on the line is.close();

i capture a FileNotFoundException: radiocd5.png, but that file is on my assets directory :S

What am i doing bad? The file is called radiocd5.png and it is on the assets directory

6 Answers

You can follow my tutorials on displaying data from Assets:
The sample with loading image and text to display.

I now added the relevant part of the provided link (in case of earthquake or something) ;-) Taifun

// load image
try {
    // get input stream
    InputStream ims = getAssets().open("avatar.jpg");
    // load image as Drawable
    Drawable d = Drawable.createFromStream(ims, null);
    // set image to ImageView
    mImage.setImageDrawable(d);
}
catch(IOException ex) {
    return;
}
5

Instead of using the assets dir, put the file into /res/raw, and you can then access it using the following URI: android.resource://" + R.raw.radiocd5

1
try {
    InputStream istr = this.context.getAssets().open(P.strImage);
    //set drawable from stream
    this.imgProduct.setImageDrawable(Drawable.createFromStream(istr, null));
} catch (IOException e) {
    e.printStackTrace();
}
protected String openImageInAssets(String imageName) {
    String encodedImageBase64 = "";
    AssetManager assetManager = getAssets();
    InputStream fileStream = null;
    try {
        fileStream = assetManager.open(imageName);
        if (fileStream != null) {
            // BitmapFactory.Options bfo = new BitmapFactory.Options();
            // bfo.inPreferredConfig = Bitmap.Config.ARGB_8888;
            // Bitmap bitmap = BitmapFactory.decodeStream(fileStream, null, bfo);

            Bitmap bitmap = BitmapFactory.decodeStream(fileStream);
            // Convert bitmap to Base64 encoded image for web
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

            // to get image extension file name split the received
            int fileExtensionPosition = imageName.lastIndexOf('.');
            String fileExtension = imageName.substring(fileExtensionPosition+1);
            // Log.d(IConstants.TAG,"fileExtension: " + fileExtension);

            if (fileExtension.equalsIgnoreCase("png")) {
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
                // Log.d(IConstants.TAG,"fileExtension is PNG");
            } else if (fileExtension.equalsIgnoreCase("jpg") || fileExtension.equalsIgnoreCase("jpeg")) {
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
                // Log.d(TAG,"fileExtension is JPG");
            }

            byte[] byteArray = byteArrayOutputStream.toByteArray();
            String imgageBase64 = Base64.encodeToString(byteArray, Base64.DEFAULT);
            encodedImageBase64 = "data:image/png;base64," + imgageBase64;
        }
    } catch (IOException e) {
        e.printStackTrace();
        return encodedImageBase64="";
    } finally {
        //Always clear and close
        try {
            if (fileStream != null) {
                fileStream.close();
                fileStream = null;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // Log.d(TAG,"encodedImageBase64: " + encodedImageBase64);
    return encodedImageBase64;
}

Here is an alternative way

setImageBitmap(BitmapFactory.decodeStream(assets.open("photo.jpg")))

Another version, inside a fragment:

@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    root = inflater.inflate(R.layout.createrestaurant_layout, container, false);
    Resources res = getResources();
    img = (ImageView) root.findViewById(R.id.img);
    AssetManager amanager = res.getAssets();
    try {
        InputStream imageStream = amanager.open("restaurant.jpg");
        Drawable drawable = new BitmapDrawable(res, imageStream);
        img.setImageDrawable(drawable);
    }  catch (Exception e) {
        e.printStackTrace();
    }
}

This process seems much simpler in iOS/UIKit or iOS/SwiftUI.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Marcus Vance

Marcus Vance

Cybersecurity & Digital Privacy Researcher

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.

Share this article
Twitter Facebook Pinterest