我想把PDF文件转换成图像。Docnet能够将pdf转换为bytes[]
,他们的示例展示了如何使用Bitmap
将这个byte[]
保存到图像文件中。文档
然而,该解决方案在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文件转换为图像。
这对ImageSharp来说很好,假设Docnet可以工作,那么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");