"Image could not be read." 在 Xamarin Forms 上的 MigraDocCore 中

"Image could not be read." in MigraDocCore on Xamarin Forms

我正在使用 Xam.Plugin.Media 从相机拍摄照片,我想使用图像流将其打印成 pdf。我尝试了很多方法来做到这一点,但没有人在工作,并且总是打印一个灰色矩形,中间有“无法读取图像”。有人知道如何解决这个问题吗?

这是我的代码

            var paragraph = document.LastSection.AddParagraph();
            paragraph.Format.Alignment = ParagraphAlignment.Center;
            var iimage = DependencyService.Get<IImage>();
            
            using (Stream stream = MyImage.GetStream())
            {
                stream.Position = 0;
                MigraDocCore.DocumentObjectModel.MigraDoc.DocumentObjectModel.Shapes.ImageSource.ImageSourceImpl = iimage.Implementation;
                var foto = MigraDocCore.DocumentObjectModel.MigraDoc.DocumentObjectModel.Shapes.ImageSource.FromStream($"MyImage_{Id}.jpg", () => stream, 100)
                var image = paragraph.AddImage(foto);
                image.LockAspectRatio = false;
                image.Width = "15cm";
                image.Height = "10cm";
            }

感谢您的帮助。

编辑 1:我删除了依赖服务,我使用 MediaPicker 而不是 Plugin Media,并且在创建 ImageSource 时抛出 NullReferenceException。

代码如下:

            var paragraph = document.LastSection.AddParagraph();
            paragraph.Format.Alignment = ParagraphAlignment.Center;
            using (Stream stream = await MyImage.OpenReadAsync())
            {
                stream.Position = 0;
                var foto = MigraDocCore.DocumentObjectModel.MigraDoc.DocumentObjectModel.Shapes.ImageSource.FromStream($"{MyImageId}.jpg", () => stream, 100);
                var image = paragraph.AddImage(foto);
                image.LockAspectRatio = false;
                image.Width = "15cm";
                image.Height = "10cm";
            }

这里是堆栈跟踪:

System.NullReferenceException: 对象引用未设置为对象的实例。
at MigraDocCore.DocumentObjectModel.MigraDoc.DocumentObjectModel.Shapes.ImageSource.FromStream (System.String name, System.Func1[TResult] imageStream, System.Nullable1[T] quality) [0x00005] in <491d7d6ccaa64ee5ad963f480330f219>:0
在 Myproject.MyClass.MyMethod() '''

ImageSource Implementation默认为null,所以我添加了这段代码来设置 ImageSource.Impl,在创建图像源之前:

if(MigraDocCore.DocumentObjectModel.MigraDoc.DocumentObjectModel.Shapes.ImageSource.ImageSourceImpl == null)
{
   MigraDocCore.DocumentObjectModel.MigraDoc.DocumentObjectModel.Shapes.ImageSource.ImageSourceImpl = new ImageSharpImageSource<Rgba32>();
}