How to convert list of Image file paths into list of bitmaps quickly?

房东的猫 提交于 2021-02-07 20:19:53

问题


ArrayList<String> imageFileList = new ArrayList<>();
ArrayList<RecentImagesModel> fileInfo = new ArrayList<>();

File targetDirector = new File(/storage/emulated/0/DCIM/Camera/);
if (targetDirector.listFiles() != null) {
    File[] files = targetDirector.listFiles();
    int i = files.length - 1;
    while (imageFileList.size() < 10) {
       File file = files[i];
       if (file.getAbsoluteFile().toString().trim().endsWith(".jpg")) {
          imageFileList.add(file.getAbsolutePath());
       } else if (file.getAbsoluteFile().toString().trim().endsWith(".png")) {
          imageFileList.add(file.getAbsolutePath());
       }
       i--;
    }
}

String file, filename;
Bitmap rawBmp, proBmp;
int length = imageFileList.size();

for (int i = 0; i < length; i++) {
   RecentImagesModel rim = new RecentImagesModel();
   file = imageFileList.get(i);
   rim.setFilepath(file);
   filename = file.substring(file.lastIndexOf("/") + 1);
   rim.setName(filename);
   rawBmp = BitmapFactory.decodeFile(file);
   proBmp = Bitmap.createScaledBitmap(rawBmp, rawBmp.getWidth() / 6, rawBmp.getHeight() / 6, false);
   rim.setBitmap(proBmp);
   fileInfo.add(rim);
}

When I am converting the file objects to bitmaps and rescaling them:

rawBmp = BitmapFactory.decodeFile(file);
proBmp = Bitmap.createScaledBitmap(rawBmp, rawBmp.getWidth() / 6, rawBmp.getHeight() / 6, false);

It takes a lot of time in processing. Is there a way to shorten the process?


回答1:


Is there a way to shorten the process?

With your current algorithm, have a smaller list of images.

You could save yourself a lot of time and a lot of memory by:

  • Switch from "1/6th of the original image" to either "1/4th of the original image" or "1/8th of the original image", then

  • Use the two-parameter decodeFile() that takes a BitmapFactory.Options, and supply an inSampleSize of 2 (for 1/4th) or 3 (for 1/8th)

In general, loading a whole bunch of images at once is not a good idea, and so I strongly encourage you to find a way to load images if and only if they are needed. For example, if the user has hundreds high-resolution photos in that directory, you will crash with an OutOfMemoryError, as you do not have enough heap space for holding hundreds of images.



来源:https://stackoverflow.com/questions/45494283/how-to-convert-list-of-image-file-paths-into-list-of-bitmaps-quickly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!