图片添加相册中显示 缩放bitmap展示

将照片添加到相册中

由于我们通过Intent创建了一张照片,因此图片的存储位置我们是知道的。对其他人来说,也许查看我们的照片最简单的方式是通过系统的Media Provider。

Note: 如果将图片存储在getExternalFilesDir()提供的目录中,Media Scanner将无法访问到我们的文件,因为它们隶属于应用的私有数据。

下面的例子演示了如何触发系统的Media Scanner,将我们的照片添加到Media Provider的数据库中,这样就可以使得Android相册程序与其他程序能够读取到这些照片。

private void galleryAddPic() {
    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    File f = new File(mCurrentPhotoPath);
    Uri contentUri = Uri.fromFile(f);
    mediaScanIntent.setData(contentUri);
    this.sendBroadcast(mediaScanIntent);
}

解码一幅缩放图片

在有限的内存下,管理许多全尺寸的图片会很棘手。如果发现应用在展示了少量图片后消耗了所有内存,我们可以通过缩放图片到目标视图尺寸,之后再载入到内存中的方法,来显著降低内存的使用,下面的例子演示了这个技术:

private void setPic() {
    // Get the dimensions of the View
    int targetW = mImageView.getWidth();
    int targetH = mImageView.getHeight();

    // Get the dimensions of the bitmap
    BitmapFactory.Options bmOptions = new BitmapFactory.Options();
    bmOptions.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
    int photoW = bmOptions.outWidth;
    int photoH = bmOptions.outHeight;

    // Determine how much to scale down the image
    int scaleFactor = Math.min(photoW/targetW, photoH/targetH);

    // Decode the image file into a Bitmap sized to fill the View
    bmOptions.inJustDecodeBounds = false;
    bmOptions.inSampleSize = scaleFactor;
    bmOptions.inPurgeable = true;

    Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
    mImageView.setImageBitmap(bitmap);
}

猜你喜欢

转载自blog.csdn.net/android_zhengyongbo/article/details/80048742
今日推荐