我正在尝试在 Xamarin.Android 应用程序的 GridView 中显示 sd 存储中的一些图片。
我发现的唯一文档是:http ://docs.xamarin.com/recipes/android/data/files/selecting_a_gallery_image
但它只适用于一张图片,打开两张或多张图片会给我一个Java.Lang.OutOfMemoryError
在这一行:
imageView.SetImageURI (bitmapList [position]);
在 SO 上找到了一些 Android 答案:
https://stackoverflow.com/a/823966/511299
翻译成C#:
public static Bitmap DecodeFile (String s)
{
try
{
s = s.Replace ("file://", "");
//Decode image size
BitmapFactory.Options o = new BitmapFactory.Options ();
o.InJustDecodeBounds = true;
BitmapFactory.DecodeStream (new System.IO.FileStream (s, System.IO.FileMode.Open), null, o);
//The new size we want to scale to
int REQUIRED_SIZE = 70;
//Find the correct scale value. It should be the power of 2.
int scale = 1;
while (o.OutWidth/scale/2>=REQUIRED_SIZE && o.OutHeight/scale/2>=REQUIRED_SIZE)
{
scale *= 2;
}
//Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options ();
o2.InSampleSize = scale;
return BitmapFactory.DecodeStream (new System.IO.FileStream (s, System.IO.FileMode.Open), null, o2);
}
catch (FileNotFoundException e)
{
}
return null;
}
这给了我一个
System.IO.IOException: Sharing violation on path storage/sdcard0/Pictures/MyAppPhotos/44cdbcf0-a488-40b8-98a9-79f3dc8d9deb.jpg
线上
return BitmapFactory.DecodeStream (new System.IO.FileStream (s, System.IO.FileMode.Open), null, o2);
我可以访问该文件两次吗?
或者可能是因为我使用FileStream
而不是FileInputStream
. 尝试使用BitmapFactory.DecodeStream
需要一个System.IO.Stream
as 参数,而不是需要一个字符串的示例:(
更详细,这里是安卓版本decodeStream
:
public static Bitmap decodeStream (InputStream is, Rect outPadding, BitmapFactory.Options opts)
虽然这是我能为 Xamarin.Android 找到的所有内容:
public static Bitmap DecodeStream (System.IO.Stream is, Rect outPadding, BitmapFactory.Options opts)