Csharp android/graphics/Bitmap存储到手机

在C#中应用Android.Graphics.Bitmap的完整指南:

适用场景适用场景
主要用于Xamarin.Android或.NET MAUI跨平台开发,实现Android原生图像处理功能。

核心步骤核心步骤

添加必要权限
在AndroidManifest.xml中添加:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

基础图像加载
使用BitmapFactory类:

using Android.Graphics; // 从资源加载 Bitmap bitmap = BitmapFactory.DecodeResource(Resources, Resource.Drawable.my_image); // 从文件加载(需处理运行时权限) string path = "/sdcard/DCIM/image.jpg"; Bitmap bitmap = BitmapFactory.DecodeFile(path);

图像处理操作
缩放缩放:

Bitmap scaledBitmap = Bitmap.CreateScaledBitmap(originalBitmap, newWidth, newHeight, true);

旋转旋转:

Csharp

Matrix matrix = new Matrix(); matrix.PostRotate(90); Bitmap rotatedBitmap = Bitmap.CreateBitmap(originalBitmap, 0, 0, originalBitmap.Width, originalBitmap.Height, matrix, true);

裁剪裁剪:

Bitmap croppedBitmap = Bitmap.CreateBitmap(originalBitmap, x, y, width, height);

内存优化策略
重要重要:Android默认使用ARGB_8888格式(每像素4字节),可通过以下方式优化:

Csharp

BitmapFactory.Options options = new BitmapFactory.Options { InSampleSize = 2, // 降低采样率 InPreferredConfig = Bitmap.Config.Rgb565 // 每像素2字节 }; Bitmap bitmap = BitmapFactory.DecodeFile(path, options);

显示处理结果
在ImageView中显示:

Csharp

imageView.SetImageBitmap(bitmap);

资源回收
必须手动回收Native内存:

bitmap.Recycle(); // 或使用Dispose模式 using (Bitmap bitmap = ...) { // 操作代码 }

性能注意事项性能注意事项

大图处理建议在后台线程进行
使用Android Profiler监控内存使用
重复使用Bitmap时考虑LruCache
优先使用异步加载库(如Glide.Xamarin)
.NETMAUI优化方案.NETMAUI优化方案
推荐使用图像处理扩展:

Csharp

using Microsoft.Maui.Graphics.Platform; IImage image = PlatformImage.FromStream(stream); IImage resized = image.Resize(800, 600); // 自动内存管理

常见问题处理常见问题处理

OutOfMemoryError:
添加largeHeap="true"到Application标签
检查未回收的Bitmap实例
图像方向错误:

ExifInterface exif = new ExifInterface(path); int orientation = exif.GetAttributeInt(ExifInterface.TagOrientation, 1); // 根据orientation值应用旋转
建议:对于复杂图像处理需求,可结合SkiaSharp库实现跨平台统一API调用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值