枕上诗书闲处好,门前风景雨来佳。这篇文章主要讲述Xamarin:Android - 带有大位图的OutOfMemory异常 - 如何解决?相关的知识,希望能为你提供帮助。
我正在拍摄一张图像,解码由byte array
方法生成的TakePicture
然后旋转bitmap
270
度。问题是我似乎耗尽了内存,我不知道如何解决它。这是代码:
Bitmap image = BitmapFactory.DecodeByteArray (data, 0, data.Length);
data = https://www.songbingjia.com/android/null;
Bitmap rotatedBitmap = Bitmap.CreateBitmap (image, 0, 0, image.Width,
image.Height, matrix, true);
答案请查看官方Load Large Bitmaps Efficiently文档中的
Xamarin
,它解释了如何将大图像加载到内存中,而不会通过在内存中加载较小的子样本版本来投掷OutOfMemoryException
。读取位图尺寸和类型
async Task<
BitmapFactory.Options>
GetBitmapOptionsOfImageAsync()
{
BitmapFactory.Options options = new BitmapFactory.Options
{
InJustDecodeBounds = true
};
// The result will be null because InJustDecodeBounds == true.
Bitmap result=await BitmapFactory.DecodeResourceAsync(Resources, Resource.Drawable.someImage, options);
int imageHeight = options.OutHeight;
int imageWidth = options.OutWidth;
_originalDimensions.Text = string.Format("Original Size= {0}x{1}", imageWidth, imageHeight);
return options;
}
将缩小版本加载到内存中
public static int CalculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight)
{
// Raw height and width of image
float height = options.OutHeight;
float width = options.OutWidth;
double inSampleSize = 1D;
if (height >
reqHeight || width >
reqWidth)
{
int halfHeight = (int)(height / 2);
int halfWidth = (int)(width / 2);
// Calculate a inSampleSize that is a power of 2 - the decoder will use a value that is a power of two anyway.
while ((halfHeight / inSampleSize) >
reqHeight &
&
(halfWidth / inSampleSize) >
reqWidth)
{
inSampleSize *= 2;
}
}return (int)inSampleSize;
}
将图像加载为异步
public async Task<
Bitmap>
LoadScaledDownBitmapForDisplayAsync(Resources res, BitmapFactory.Options options, int reqWidth, int reqHeight)
{
// Calculate inSampleSize
options.InSampleSize = CalculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.InJustDecodeBounds = false;
return await BitmapFactory.DecodeResourceAsync(res, Resource.Drawable.someImage, options);
}
并将其称为加载图像,例如在
OnCreate
中protected async override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
_imageView = FindViewById<
ImageView>
(Resource.Id.resized_imageview);
BitmapFactory.Options options = await GetBitmapOptionsOfImageAsync();
Bitmap bitmapToDisplay = await LoadScaledDownBitmapForDisplayAsync (Resources,
options,
150,//for 150 X 150 resolution
150);
_imageView.SetImageBitmap(bitmapToDisplay);
}
【Xamarin(Android - 带有大位图的OutOfMemory异常 - 如何解决())】希望能帮助到你。
推荐阅读
- 我是否需要所有Android SDK以及如何安装它们()
- Xamarin Android Forms设计器无法识别GridLayout布局参数
- Zeppelin勒索软件指南
- 使用X-FRAME-OPTIONS保护Nginx免受点击劫持
- 保护和强化Apache Web服务器的10种最佳实践
- 如何(为什么)为WordPress创建暂临时站点()
- 9个很棒的服务可以启用来自WordPress的推送通知
- 如何将Yoast Sitemap的频率更改为”每日”()
- 使用PHP-FPM 7的WordPress与5相比有多快()