首页 > 解决方案 > 从 DB 到 BitmapImageSource 的 Byte[] -- 一个接一个的错误

问题描述

我正在为我工​​作的公司创建一个 UWP 应用程序,部分过程是上传身份证照片。当用户单击以上传选择器时,它将显示图像并将图像加载到图像元素中。这很好用,问题是当拉出已经附有照片的现有记录时。该文件存储为 byte[],我在 .Net Web 应用程序上使用的代码在这里不起作用。即使在无数网站上阅读了一周后的帖子后,我也无法让它工作。

using (SqlDataReader reader = cmd.ExecuteReader())
                            {
                                while (reader.Read())
                                {
                                    photo.ID = reader.GetGuid(0);
                                    photo.AttachmentType = reader.GetString(1);
                                    photo.AttachmentSize = reader.GetInt32(2);
                                    photo.Attachment = (byte[])reader.GetValue(3);
                                }
                            }
                            RemoveBtn.Visibility = Visibility.Visible;

                        }
                    }
                }
            }
        }
        catch (Exception eSql)
        {
            var err = eSql.Message.ToString();
        }

        if (photo.Attachment != null && photo.Attachment.Length > 0)
        {
            //StorageFolder folder = Windows.ApplicationModel.Package.Current.InstalledLocation;
            //StorageFile file = await folder.CreateFileAsync($"tempImg{photo.AttachmentType}");
            //string path = @"D:\DOT2";
            //string fileName = "tempImg.png";
            //string pathStr = Path.Combine(path, fileName);

            using (Stream stream = new MemoryStream())
            {
                await stream.WriteAsync(photo.Attachment, 0, photo.Attachment.Length);

                using (IRandomAccessStream fileStream = stream.AsRandomAccessStream())
                {

                    BitmapImage img = new BitmapImage();
                    await img.SetSourceAsync(fileStream); //Error Occurs here.
                    CIPhoto.Source = img;
                }

            }

            UploadBtn.Visibility = Visibility.Collapsed;
            RemoveBtn.Visibility = Visibility.Visible;
        }

预期的结果是将 byte[] 转换为我可以设置为 Image UI 元素的 BitmapImageSource。我收到一个又一个错误,目前我收到一条错误消息:'尝试读取或写入受保护的内存。这通常表明其他内存已损坏。'。评论部分告诉我,我被拒绝访问。我被卡住了,请帮忙。

标签: c#uwpbitmap

解决方案


推荐阅读