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

如何将Microsoft.Maui.Controls.Image转为字节数组用于SQL存储

解决Camera.MAUI捕获图片转字节数组的问题

你的错误根源在于直接将Microsoft.Maui.Controls.Image UI控件传给了ImageFormatConverter,但该转换器需要处理的是图片的原始数据,而非控件对象。cameraView.GetSnapShot()返回的是ImageSource,我们应该直接处理这个返回值,而非UI控件。

修正方案

1. 修改转换方法,直接处理ImageSource

替换原有的converterDemo方法,改为异步获取图片流并转换为字节数组:

public static async Task<byte[]> ConvertImageSourceToBytes(ImageSource imageSource)
{
    if (imageSource is StreamImageSource streamImageSource)
    {
        using var stream = await streamImageSource.Stream(CancellationToken.None);
        using var memoryStream = new MemoryStream();
        await stream.CopyToAsync(memoryStream);
        return memoryStream.ToArray();
    }
    return null;
}

2. 调整图片捕获逻辑,直接处理快照返回值

修改点击事件代码,不再传入Image控件,而是直接处理GetSnapShot的返回结果:

async void Photo_Button_Clicked(System.Object sender, System.EventArgs e)
{
    if (Image1.Source == null)
    {
        var snapshot = cameraView.GetSnapShot(Camera.MAUI.ImageFormat.PNG);
        Image1.Source = snapshot;
        Image1asBytes = await ImageConverter.ConvertImageSourceToBytes(snapshot);
    }
    else if (Image2.Source == null)
    {
        var snapshot = cameraView.GetSnapShot(Camera.MAUI.ImageFormat.PNG);
        Image2.Source = snapshot;
        Image2asBytes = await ImageConverter.ConvertImageSourceToBytes(snapshot);
    }
    else if (Image3.Source == null)
    {
        var snapshot = cameraView.GetSnapShot(Camera.MAUI.ImageFormat.PNG);
        Image3.Source = snapshot;
        Image3asBytes = await ImageConverter.ConvertImageSourceToBytes(snapshot);
    }
    else if (Image4.Source == null)
    {
        var snapshot = cameraView.GetSnapShot(Camera.MAUI.ImageFormat.PNG);
        Image4.Source = snapshot;
        Image4asBytes = await ImageConverter.ConvertImageSourceToBytes(snapshot);
    }
}

说明

  • cameraView.GetSnapShot()返回的ImageSource实际是StreamImageSource类型,包含了图片的原始流数据
  • 通过异步方式获取流,再将流复制到内存流并转换为字节数组,这是MAUI中处理图片源转字节数组的标准方式
  • 该方案避免了对UI控件的错误操作,直接处理图片数据,不会再出现类型转换异常

内容的提问来源于stack exchange,提问作者Paul S

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 19:12:33