我正在开发一个应用程序,需要从Android设备的内置图片库中获取随机图片,然后将其显示在屏幕上。这是我必须要做的事情:
- 一个名为picture的ImageView对象 - 我想要显示的图片的ID,TITLE,DATA,MIME_TYPE和SIZE
我认为问题是我不知道我需要在这一行中提供哪些信息:
picture.setImageResource(???);
以下是我的所有代码,可以让您了解我正在尝试做的事情:
public void generateImage() {
// Get list of images accessible by cursor
ContentResolver cr = getActivity().getContentResolver();
String[] columns = new String[] {
ImageColumns._ID,
ImageColumns.TITLE,
ImageColumns.DATA,
ImageColumns.MIME_TYPE,
ImageColumns.SIZE };
Cursor cursor = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
columns, null, null, null);
// Collect Picture IDs
cursor.moveToFirst();
ArrayList<Integer> picList = new ArrayList<Integer>();
while (!cursor.isAfterLast()) {
picList.add(cursor.getInt(0));
cursor.moveToNext();
}// end for
// Generate random number
int imageCount = picList.size() - 1;
Log.d("NUMBER OF IMAGES", "Image Count = " + imageCount);
Random random = new Random();
int randomInt = random.nextInt(imageCount);
// Extract the image
int picID = picList.get(randomInt);
picture.setImageResource(picID);
}// end Generate Image
任何人都知道我需要做什么才能将图片对象设置为我从图库中获得的图片(最好使用我已经获得的信息)?
答案 0 :(得分:0)
看起来你正在保存一个光标位置的数组......这可能不会给你很多工作。我想你宁愿使用ImageColumns._ID填充ArrayList,然后使用该字符串作为URI来打开图像。
答案 1 :(得分:0)
//Extracting the image
columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToPosition(randomInt);
filePath = cursor.getString(columnIndex);
imageView.setImageBitmap(decodeSampledBitmapFromResource(filePath,width,height));
为了有效地使用位图,这样你就不会遇到OutOfMemory Exceptions这里有两个函数从androids开发者页面开始[link http://developer.android.com/training/displaying-bitmaps/load-bitmap.html]
public Bitmap decodeSampledBitmapFromResource(String path, int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds = true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path,options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(path, options);
}
public static int calculateInSampleSize( BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
// Calculate ratios of height and width to requested height and width
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// Choose the smallest ratio as inSampleSize value, this will guarantee
// a final image with both dimensions larger than or equal to the
// requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
}