Jev*_*rlo 9 android gridview uri android-sdcard bitmapfactory
我正在尝试创建一个gridview,它载有来自SDCard上的特定文件夹的图像.该文件夹的路径是已知的,("/ sdcard/pictures"),但在我在网上看到的示例中,我不确定如何或在何处指定图片文件夹的路径,我想从中加载图像.我已经阅读了几十个教程,甚至是developer.android.com上的HelloGridView教程,但这些教程并没有教会我正在寻找什么.
我到目前为止阅读的每个教程都有:
A)从/ res文件夹中将图像称为Drawable,并将它们放入要加载的数组中,而不是使用SDCard.
B)使用MediaStore 访问SDCard上的所有图片,但未指定如何设置我想要显示图像表单的文件夹的路径
要么
C)建议使用BitmapFactory,我没有丝毫的线索如何使用.
如果我以错误的方式解决这个问题,请告诉我,并指导我采取正确的方法来做我想做的事情.
小智 15
好的,经过多次迭代尝试后,我终于有了一个有效的例子,我想我会分享它.我的示例查询图像MediaStore,然后获取要在视图中显示的每个图像的缩略图.我将我的图像加载到Gallery对象中,但这不是此代码的工作要求:
确保在类级别定义的列索引具有Cursor和int,以便Gallery的ImageAdapter可以访问它们:
private Cursor cursor;
private int columnIndex;
Run Code Online (Sandbox Code Playgroud)
首先,获取位于文件夹中的图像ID的光标:
Gallery g = (Gallery) findViewById(R.id.gallery);
// request only the image ID to be returned
String[] projection = {MediaStore.Images.Media._ID};
// Create the cursor pointing to the SDCard
cursor = managedQuery( MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection,
MediaStore.Images.Media.DATA + " like ? ",
new String[] {"%myimagesfolder%"},
null);
// Get the column index of the image ID
columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID);
g.setAdapter(new ImageAdapter(this));
Run Code Online (Sandbox Code Playgroud)
然后,在Gallery的ImageAdapter中,获取要显示的缩略图:
public View getView(int position, View convertView, ViewGroup parent) {
ImageView i = new ImageView(context);
// Move cursor to current position
cursor.moveToPosition(position);
// Get the current value for the requested column
int imageID = cursor.getInt(columnIndex);
// obtain the image URI
Uri uri = Uri.withAppendedPath( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, Integer.toString(imageID) );
String url = uri.toString();
// Set the content of the image based on the image URI
int originalImageId = Integer.parseInt(url.substring(url.lastIndexOf("/") + 1, url.length()));
Bitmap b = MediaStore.Images.Thumbnails.getThumbnail(getContentResolver(),
originalImageId, MediaStore.Images.Thumbnails.MINI_KIND, null);
i.setImageBitmap(b);
i.setLayoutParams(new Gallery.LayoutParams(150, 100));
i.setScaleType(ImageView.ScaleType.FIT_XY);
i.setBackgroundResource(mGalleryItemBackground);
return i;
}
Run Code Online (Sandbox Code Playgroud)
我想这段代码中最重要的部分是managedQuery,它演示了如何使用MediaStore查询来过滤特定文件夹中的图像文件列表.
阅读此链接:http://androidsamples.blogspot.com/2009/06/how-to-display-thumbnails-of-images.html
它展示了如何使用 mediastore 和 bitmapfactory。
你应该选择什么方式取决于你到底需要什么。如果你有一组静态图像,我认为最好将它们放入可绘制对象中,因为这样速度更快,而且你不依赖 SD 卡,SD 卡可以被删除、损坏或文件可以被重命名/删除
如果图像是动态的,则使用媒体存储或位图工厂。但请记住,将图像放入数组或其他非常消耗内存的东西,因此最终可能会出现内存不足异常
| 归档时间: |
|
| 查看次数: |
33521 次 |
| 最近记录: |