0

I'm used to setting background images to views from my drawables. What should I do If I want to set a background from a file?

In this code, I'm scanning a file directory, and I intend to add the first image file I find as a background. Should I convert the image file to a drawable first? Does the file extension matter?

File mFile = new File(stringPath);
File[] mFiles = mFile.listFiles();

for(File aFile : mFiles){

    // Test if aFile is a .jpg or a .png and convert to drawable?

    }
the_prole
  • 8,275
  • 16
  • 78
  • 163

1 Answers1

2

You can try this:

  public static Drawable foo(String stringPath) {
    File mFile = new File(stringPath);
    File[] mFiles = mFile.listFiles();

    for (File aFile : mFiles) {
        if (isImage(aFile)) {
            return Drawable.createFromPath(aFile.getPath());
        }
    }
    return mPlaceholder;
}


public static boolean isImage(File file) {
    if (file == null || !file.exists()) {
        return false;
    }
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(file.getPath(), options);
    return options.outWidth != -1 && options.outHeight != -1;
}

Or you can use another way:

public static Bitmap foo(String stringPath) {
    File mFile = new File(stringPath);
    File[] mFiles = mFile.listFiles();

    for (File aFile : mFiles) {

        BitmapFactory.Options bmOptions = new BitmapFactory.Options();
        bmOptions.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeFile(aFile.getAbsolutePath(),bmOptions);
        if(bmOptions.outWidth != -1 && bmOptions.outHeight != -1){
            return bitmap;
        }

    }
    return mPlaceholder;
}


public static void bar(View view, String stringPath) {
    Bitmap bitmap = foo(stringPath);
    BitmapDrawable drawable = new BitmapDrawable(view.getContext().getResources(), bitmap);
    view.setBackground(drawable);
}
ArtKorchagin
  • 4,801
  • 13
  • 42
  • 58
  • Thanks, but don't I have to check if `aFile` is an image file first? – the_prole Nov 17 '15 at 22:07
  • I guess I would have to to use something like [this](http://stackoverflow.com/questions/13760269/android-how-to-check-if-file-is-image) – the_prole Nov 17 '15 at 22:08
  • I used the former method. It's working but I noticed I get this message in the log cat `SkImageDecoder::Factory returned null` How do I get rid of it? – the_prole Nov 19 '15 at 03:47