System.Drawing.Common.Bitmap 跨平台替代方案

System.Drawing.Common.Bitmap cross platform alternatives

我想将 PDF 文件转换成图像。 Docnet is able to convert the pdf into bytes[] and their samples show how to save this byte[] into an image file using Bitmap. Documentation

但是,该解决方案无法在 linux 机器上运行,因为 Bitmap 需要在系统上预安装一些库。

我试过 ImageSharp 使用 SixLabors.ImageSharp.Image.Load<Bgra32>(rawBytes) 转换 byte[],但是,它抛出 Unhandled exception. SixLabors.ImageSharp.InvalidImageContentException: PNG Image does not contain a data chunk

有谁知道实现此目的的任何替代方法。

PS - 我愿意探索任何其他跨平台免费支持的替代方法,将 PDF 文件转换为图像。

假定 Docnet 可以正常工作,ImageSharp 可以正常工作,那么 ImageSharp 也可以正常工作。

关键在于您要使用 Image.LoadPixelData<Bgra32>(rawBytes, width, height); API 而不是 Image.Load<Bgra32>(encodedBytes);

using Docnet.Core;
using Docnet.Core.Models;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;

using var docReader = DocLib.Instance.GetDocReader(
           "wikipedia_0.pdf",
           new PageDimensions(1080, 1920));

using var pageReader = docReader.GetPageReader(0);

var rawBytes = pageReader.GetImage();

var width = pageReader.GetPageWidth();
var height = pageReader.GetPageHeight();

// this is the important line, here you are taking a byte array that 
// represents the pixels directly where as Image.Load<Bgra32>()
// is expected an encoded image in png, jpeg etc format
using var img = Image.LoadPixelData<Bgra32>(rawBytes, width, height);
// you are likely going to want this as well otherwise you might end up with transparent parts.
img.Mutate(x => x.BackgroundColor(Color.White));

img.Save("wikipedia_0.png");