Android: Scanning a directory and displaying pictures (thumbnails) (pictures are not stored in the mediastore)

丶灬走出姿态 提交于 2019-12-06 05:48:20

问题


I have recently done some tests with display pictures using a custom gallery that i designed using the media queries and mediastore... It worked great but i really need to do something custom.

I don't wish the pictures to be scanned or available in the mediastore hence i would like to have my app scan a directory and create thumbnails and display these thumbnails.

I am finding it really thin on the ground to find any good quality examples to do this.

Can anyone help with a small example.

Here is what i am looking to do.

  1. Pictures are stored in a directory of the sdcard.
  2. Using my custom gallery it would scan this directory but "NOT" using the mediastore
  3. I need to display the contents of the directory but as thumbnails i presume i would need to create this thumbnails first?
  4. Clicking on a thumnail would should the full screen image from my custom gallery.

I suppose i just need a little help in getting the pictures from the the directory considering there are not stored int eh mediastore so i can't use a query. THe other thing that concerns me is that i would need to create the thumbnails for each of the these images (on the fly??) because display the images but at a reduced size i would suspect would be pretty bad for the performance.

Can anyone lend a helping hand?

Thanks in advance


回答1:


I did exactly the same a while ago. You have to pass a folder name where your images are to setBaseFolder. This method in turn invokes refresh() which - using a FilenameFilter (code not included but is very easy to implement) gets all images named orig_....jpg from that folder and holds it in mFileList. Then we call notifyDataSetChanged() which in turn will trigger getView() for every cell.

Now, in getView() we either fetch a thumbnail bitmap from a cache if we already have it there, otherwise we make a gray placeholder and start a ThumbnailBuilder to create thumbnail resp. get a bitmap from it.

I think you'll have to change the ThumbnailBuilder a bit, because I create quite large "thumbnails" (500x500) as I need the resized images for other purposes too. Also, as I work with photos taken by the camera there is some stuff there, rotating the image according to the exif information. But basicly, ThumbnailBuilder just checks if there already is a thumbnail image (my thumbnail images are placed the same folder but have prefix small_ instead of orig_) - if the thumbnail picture already exists, we get it as a Bitmap and are done, otherwise the image is generated. Finally, in onPostExecute() the bitmap is set to the ImageView.

public class PhotoAdapter extends BaseAdapter {

private Context mContext;
private int mCellSize;
private File mFolder;
private File[] mFileList;
private Map<Object, Bitmap> mThumbnails = new HashMap<Object, Bitmap>();
private Set<Object> mCreatingTriggered = new HashSet<Object>(); // flag that creating already triggered

public PhotoAdapter(Context context, int cellSize) {
    mContext = context;
    mCellSize = cellSize;
}

@Override
public int getCount() {
    if (mFolder == null) {
        return 0;   // don't do this
    } else {
        return mFileList.length;
    }
}

@Override
public Object getItem(int position) {
    return mFileList[position];
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ImageView view = (ImageView)convertView;
    if (view == null) {
        view = new ImageView(mContext);
        view.setLayoutParams(new GridView.LayoutParams(mCellSize, mCellSize));
        view.setScaleType(ImageView.ScaleType.CENTER_CROP);
        view.setPadding(8, 8, 8, 8);
        view.setBackgroundColor(0xFFC6CCD3);
    }
    Object item = getItem(position);
    Bitmap bm = mThumbnails.get(item);
    if (bm == null) {
        view.setImageBitmap(null);
        if (!mCreatingTriggered.contains(item)) {
            mCreatingTriggered.add(item);
            new ThumbnailBuilder(view, (File)item).execute();
        }
    } else {
        view.setImageBitmap(bm);
    }
    return view;
}

public void setBaseFolder(File baseFolder) {
    if (baseFolder == null) return;
    if (!baseFolder.equals(mFolder)) {
        releaseThumbnails();
        mFolder = baseFolder;
    }
    refresh();
}

public void refresh() {
    if (mFolder == null) {
        return;
    }
    mFileList = mFolder.listFiles(EtbApplication.origImageFilenameFilter);
    if (mFileList == null) mFileList = new File[0];
    notifyDataSetChanged();
}

public void releaseThumbnails() {
    for (Bitmap bm : mThumbnails.values()) {
        bm.recycle();
    }
    mThumbnails.clear();
}

// ------------------------------------------------------------------------------------ Asynchronous Thumbnail builder

private class ThumbnailBuilder extends AsyncTask<Void, Integer, Bitmap> {

    private ImageView mView;
    private File mFile;

    public ThumbnailBuilder(ImageView view, File file) {
        mView = view;
        mFile = file;
    }

    @Override
    protected Bitmap doInBackground(Void... params) {
        Log.d("adapter", "make small image and thumbnail");
        try {
            return createThumbnail(mFile.getAbsolutePath());
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    protected void onPostExecute(Bitmap result) {
        if (result != null) {
            mView.setImageBitmap(result);
            mThumbnails.put(mFile, result);
        } else {
            mView.setImageResource(R.drawable.ic_launcher);
        }
    }

    /**
     * Creates Thumbnail (also rotates according to exif-info)
     * @param file
     * @return
     * @throws IOException
     */
    private Bitmap createThumbnail(String file) throws IOException {

        File thumbnailFile = new File(file.replace("orig_", "small_"));

        // If a small image version already exists, just load it and be done.
        if (thumbnailFile.exists()) {
            return BitmapFactory.decodeFile(thumbnailFile.getAbsolutePath());
        }

        // Decode image size
        BitmapFactory.Options bounds = new BitmapFactory.Options();
        bounds.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(file, bounds);

        if ((bounds.outWidth == -1) || (bounds.outHeight == -1))
            return null;

        int w, h;

        if (bounds.outWidth > bounds.outHeight) {   // Querformat
            w = 500;
            h = 500 * bounds.outHeight / bounds.outWidth;
        } else {    // Hochformat
            h = 500;
            w = 500 * bounds.outWidth / bounds.outHeight;
        }

        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inSampleSize = 4;  // resample -- kleiner aber noch nicht die 500 Pixel, die kommen dann unten
        Bitmap resizedBitmap = BitmapFactory.decodeFile(file, opts);
        resizedBitmap = Bitmap.createScaledBitmap(resizedBitmap, w, h, true);

        ExifInterface exif = new ExifInterface(file);
        String orientString = exif.getAttribute(ExifInterface.TAG_ORIENTATION);
        int orientation = orientString != null ? Integer.parseInt(orientString) : ExifInterface.ORIENTATION_NORMAL;
        int rotationAngle = 0;
        if (orientation == ExifInterface.ORIENTATION_ROTATE_90) rotationAngle = 90;
        if (orientation == ExifInterface.ORIENTATION_ROTATE_180) rotationAngle = 180;
        if (orientation == ExifInterface.ORIENTATION_ROTATE_270) rotationAngle = 270;

        Matrix matrix = new Matrix();
        matrix.setRotate(rotationAngle, (float) resizedBitmap.getWidth() / 2, (float) resizedBitmap.getHeight() / 2);
        Bitmap rotatedBitmap = Bitmap.createBitmap(resizedBitmap, 0, 0, w, h, matrix, true);
        resizedBitmap.recycle();
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);

        thumbnailFile.createNewFile();
        FileOutputStream fo = new FileOutputStream(thumbnailFile);
        fo.write(bytes.toByteArray());
        fo.close();

        //new File(file).delete();  // Originalbild löschen

        return rotatedBitmap;
    }
}
}


来源:https://stackoverflow.com/questions/12190181/android-scanning-a-directory-and-displaying-pictures-thumbnails-pictures-are

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