Android:扫描目录并显示图片(缩略图)(图片未存储在MediaStore中)

4
最近我使用自定义的画廊进行了一些显示图片的测试,使用了媒体查询和mediastore...它工作得非常好,但我真的需要做一些自定义的东西。
因此,我不希望这些图片被扫描或出现在媒体库中,因此我想让我的应用程序扫描一个目录并创建缩略图,然后显示这些缩略图。
但是我发现很难找到任何质量较高的示例来完成这个任务。有人能提供一个小例子帮忙吗?
这就是我要做的事情:
1. 图片存储在SD卡的一个目录中。
2. 使用我的自定义画廊扫描该目录,但不使用mediastore。
3. 我需要显示该目录的内容,但作为缩略图,我可以预想我需要先创建这些缩略图?
4. 单击缩略图会从我的自定义画廊显示全屏图像。
我想我只需要一点帮助来从目录获取这些图片,因为它们没有存储在mediastore中,所以我无法使用查询。另一件令我担心的事情是,我需要为这些图片创建缩略图(即时生成?),因为我认为在降低图片尺寸的同时显示图片性能可能会非常差。
请问有谁能帮帮我吗?谢谢。
1个回答

2

我之前也做过同样的事情。你需要传递一个包含图片的文件夹名称给setBaseFolder方法。这个方法会调用refresh(),使用一个FilenameFilter(代码未包含但很容易实现)从那个文件夹中获取所有名为orig_....jpg的图片,并将其保存在mFileList中。然后我们调用notifyDataSetChanged(),这将触发每个单元格的getView()

现在,在getView()中,如果我们已经有缩略图位图,则从缓存中获取它,否则我们会创建一个灰色占位符并启动一个ThumbnailBuilder来创建缩略图或获取位图。

我认为你需要稍微修改一下ThumbnailBuilder,因为我创建的“缩略图”相当大(500x500),因为我还需要调整大小的图像用于其他目的。此外,由于我使用相机拍摄的照片,所以还有一些内容,根据exif信息旋转图像。但基本上,ThumbnailBuilder只是检查是否已经有缩略图图像(我的缩略图图像与原始图像放置在同一个文件夹中,但前缀为small_而不是orig_)-如果缩略图图片已经存在,则我们将其作为Bitmap获取并完成,否则将生成图像。最后,在onPostExecute()中,位图被设置到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;
    }
}
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接