Xamarin安卓项目中如何获取drawable文件夹内图片为byte array或bitmap
Xamarin.Android Drawable资源转Bitmap/Byte数组解决方案
前置检查
首先确认以下配置正确,否则所有调用都会返回空:
- 图片
stupidshit.png已存放在安卓项目的Resources/drawable目录下 - 右键图片选择「属性」,生成操作设置为
AndroidResource - 资源名称不要包含大写字母、空格或特殊符号,安卓资源系统会自动将资源名转为小写存储
方案1:Xamarin.Forms ContentPage 跨平台调用(推荐)
由于ContentPage的Code Behind通常位于共享项目中,无法直接访问安卓平台API,需通过依赖服务实现调用:
步骤1:共享项目定义接口
public interface IResourceLoader { /// <summary> /// 根据drawable名称获取byte数组 /// </summary> byte[] GetDrawableBytes(string drawableName); /// <summary> /// 根据drawable名称获取Bitmap /// </summary> Android.Graphics.Bitmap GetDrawableBitmap(string drawableName); }
步骤2:安卓项目实现接口
[assembly: Dependency(typeof(ResourceLoader))] namespace YourAppNamespace.Droid { public class ResourceLoader : IResourceLoader { public byte[] GetDrawableBytes(string drawableName) { // 自动去除后缀匹配资源id string cleanName = Path.GetFileNameWithoutExtension(drawableName).ToLowerInvariant(); int resId = Android.App.Application.Context.Resources.GetIdentifier( cleanName, "drawable", Android.App.Application.Context.PackageName); if (resId == 0) return null; var bitmap = Android.Graphics.BitmapFactory.DecodeResource( Android.App.Application.Context.Resources, resId); using var ms = new MemoryStream(); bitmap.Compress(Android.Graphics.Bitmap.CompressFormat.Png, 100, ms); return ms.ToArray(); } public Android.Graphics.Bitmap GetDrawableBitmap(string drawableName) { string cleanName = Path.GetFileNameWithoutExtension(drawableName).ToLowerInvariant(); int resId = Android.App.Application.Context.Resources.GetIdentifier( cleanName, "drawable", Android.App.Application.Context.PackageName); return resId == 0 ? null : Android.Graphics.BitmapFactory.DecodeResource( Android.App.Application.Context.Resources, resId); } } }
步骤3:ContentPage Code Behind 调用
// 获取byte数组 byte[] imgBytes = DependencyService.Get<IResourceLoader>().GetDrawableBytes("stupidshit.png"); // 获取Bitmap Android.Graphics.Bitmap imgBitmap = DependencyService.Get<IResourceLoader>().GetDrawableBitmap("stupidshit.png");
方案2:安卓平台代码直接调用
如果你的代码逻辑本身就在安卓项目中(如自定义渲染、平台服务),可直接调用原生API:
// 获取Bitmap int resId = Resources.GetIdentifier("stupidshit", "drawable", PackageName); Android.Graphics.Bitmap bitmap = Android.Graphics.BitmapFactory.DecodeResource(Resources, resId); // Bitmap转byte数组 using var ms = new MemoryStream(); bitmap.Compress(Android.Graphics.Bitmap.CompressFormat.Png, 100, ms); byte[] bytes = ms.ToArray();
内容的提问来源于stack exchange,提问作者Kajot
相关产品推荐
相关产品推荐

