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

Camera.MAUI拍摄图片后无法正确保存为PNG文件求助

解决Camera.MAUI快照无法正确保存为PNG文件的问题

你当前的错误在于将NewImage.Source的字符串表示(即类型名称)写入文件,而不是快照的实际二进制数据。GetSnapShot返回的IImageSource本质是StreamImageSource,需要从中提取图片流并转换为字节数组才能正确保存。

修改步骤及代码

  1. 在页面类中添加私有字段存储捕获的图片字节:
private byte[] _capturedPhotoBytes;
  1. 修改拍照按钮点击事件,捕获图片实际字节:
private async void TakePhotoButton_Clicked(object sender, EventArgs e)
{
    var imageSource = cameraView.GetSnapShot(Camera.MAUI.ImageFormat.PNG) as StreamImageSource;
    if (imageSource == null)
    {
        await DisplayAlert("Error", "Failed to capture photo", "OK");
        return;
    }

    // 从StreamImageSource提取字节数组
    using (var stream = await imageSource.Stream(CancellationToken.None))
    using (var memoryStream = new MemoryStream())
    {
        await stream.CopyToAsync(memoryStream);
        _capturedPhotoBytes = memoryStream.ToArray();
    }

    NewImage.Source = imageSource;
    SavePhoto.IsEnabled = true;
    FileNameEntry.IsEnabled = true;
}
  1. 修改保存按钮点击事件,使用预存字节数组写入文件:
private async void SavePhotoButton_Clicked(object sender, EventArgs e)
{
    if (string.IsNullOrEmpty(FileNameEntry.Text))
    {
         await DisplayAlert("Missing Info", "Enter File Name", "OK");
        return;
    }

    if (_capturedPhotoBytes == null || _capturedPhotoBytes.Length == 0)
    {
        await DisplayAlert("Error", "No photo captured to save", "OK");
        return;
    }

    string photoFileName = $"{FileNameEntry.Text.ToLower()}.png";
    string myPicPath = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
    var folderPath = Path.Combine(myPicPath, "CapsnPins");

    if (!Directory.Exists(folderPath))
    {
        Directory.CreateDirectory(folderPath);
    }

    string filePath = Path.Combine(folderPath, photoFileName);

    await File.WriteAllBytesAsync(filePath, _capturedPhotoBytes, CancellationToken.None);
    await DisplayAlert("Saved Photo", $"Successfully saved {photoFileName}", "OK");
}

关键修改说明

  • 新增_capturedPhotoBytes字段直接存储图片二进制数据,避免从UI控件Source中错误提取内容
  • 拍照时将StreamImageSource转换为字节数组,确保获取到真实图片数据
  • 保存阶段直接使用预存的字节数组写入文件,不再处理Source的字符串表示
  • 增加空值检查,避免无图片时执行无效保存操作
  • 简化文件名拼接逻辑,修正了"Succssfully"的拼写错误

内容的提问来源于stack exchange,提问作者Michael Amarello

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 21:23:09