You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

编译Xamarin项目遇Mono.Linker.MarkException,图片转字节数组失败

解决Xamarin.Forms.Image转字节数组时的编译链接错误

错误原因

编译时出现的Mono.Linker.MarkException核心问题是:链接器无法解析System.Drawing.ImageConverter的构造函数。System.Drawing命名空间主要针对桌面环境设计,在Xamarin移动端(Android/iOS)中存在兼容性问题,直接使用ImageConverter会导致链接阶段无法找到对应依赖。

正确转换方案

Xamarin.Forms.Image的图片数据来自ImageSource,需通过原生流的方式获取并转换为字节数组,以下是通用实现:

using System.IO;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Xamarin.Forms;

public async Task<byte[]> ConvertImageToByteArray(Image targetImage)
{
    if (targetImage?.Source == null)
        return null;

    byte[] resultBytes = null;
    var imageSource = targetImage.Source;

    // 处理流类型图片源
    if (imageSource is StreamImageSource streamSource)
    {
        using (var imageStream = await streamSource.Stream(CancellationToken.None))
        using (var memoryStream = new MemoryStream())
        {
            await imageStream.CopyToAsync(memoryStream);
            resultBytes = memoryStream.ToArray();
        }
    }
    // 处理本地文件图片源
    else if (imageSource is FileImageSource fileSource)
    {
        // 注意:移动端文件路径需根据平台适配(如Android的Assets、iOS的Bundle)
        resultBytes = File.ReadAllBytes(fileSource.File);
    }
    // 处理网络Uri图片源
    else if (imageSource is UriImageSource uriSource)
    {
        using (var httpClient = new HttpClient())
        {
            resultBytes = await httpClient.GetByteArrayAsync(uriSource.Uri);
        }
    }

    return resultBytes;
}

临时兼容方案(不推荐长期使用)

若需保留ImageConverter的使用方式,需在Android项目中配置链接器保留对应类:

  1. 在Android项目中添加Linker.xml文件,设置其生成操作为LinkDescription
  2. 文件内容如下:
<linker>
  <assembly fullname="System.Drawing.Common">
    <type fullname="System.Drawing.ImageConverter" preserve="all"/>
  </assembly>
</linker>

注意:System.Drawing.Common在.NET 6及以上版本的移动端已被标记为不支持,此方案仅作为临时过渡,建议优先使用原生流处理方案。

内容的提问来源于stack exchange,提问作者Samuel Montoya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 23:50:17