【问题标题】:"Image could not be read." in MigraDocCore on Xamarin Forms“无法读取图像。”在 Xamarin 表单上的 MigraDocCore
【发布时间】:2022-01-06 09:44:02
【问题描述】:

我正在使用 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:对象引用未设置为对象的实例。
在 MigraDocCore.DocumentObjectModel.MigraDoc.DocumentObjectModel.Shapes.ImageSource.FromStream (System.String 名称,System.Func1[TResult] imageStream, System.Nullable1[T] 质量)[0x00005] 在 :0
在 Myproject.MyClass.MyMethod() '''

【问题讨论】:

  • MediaPicker 可以返回一个流,为什么要使用 DependencyService 来做到这一点?
  • 只是这个例子中的一个实现github.com/icebeam7/PDFDemo
  • 我删除了依赖服务和插件媒体并添加了媒体选择器,现在当我从 MigraDoc 创建 ImageSource 时抛出 NullReferenceException
  • 您确实应该在开始尝试读取之前检查您正在打开的流是否不为空。例如,如果您只是简单地取消了媒体选择器,那么它将为空,然后您在上面发布的代码就会崩溃。

标签: c# xamarin.forms pdfsharp migradoc


【解决方案1】:

ImageSource 实现默认为空,所以我添加了这段代码来设置 ImageSource.Impl,在创建 Image Source 之前:

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

【讨论】:

    猜你喜欢
    • 2022-01-11
    • 2020-05-12
    • 2020-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-06
    • 2020-11-20
    相关资源
    最近更新 更多