https://github.com/thombrink/itext7.pdfimage
新建asp.net core8项目,安装itext7和system.drawing.common
引入itext.pdfimage核心代码
imageListener下有一段不安全的代码
unsafe
{
for (int y = 0; y < image.Height; y++)
{
byte* ptrMask = (byte*)bitsMask.Scan0 + y * bitsMask.Stride;
byte* ptrInput = (byte*)bitsInput.Scan0 + y * bitsInput.Stride;
byte* ptrOutput = (byte*)bitsOutput.Scan0 + y * bitsOutput.Stride;
for (int x = 0; x < image.Width; x++)
{
ptrOutput[4 * x] = ptrInput[4 * x]; // blue
ptrOutput[4 * x + 1] = ptrInput[4 * x + 1]; // green
ptrOutput[4 * x + 2] = ptrInput[4 * x + 2]; // red
ptrOutput[4 * x + 3] = ptrMask[4 * x]; // alpha
}
}
}
修改为安全代码
// 遍历每一行
for (int y = 0; y < image.Height; y++)
{
// 计算每行的起始字节位置
int scanOffsetInput = y * bitsInput.Stride;
int scanOffsetMask = y * bitsMask.Stride;
int scanOffsetOutput = y * bitsOutput.Stride;
// 获取当前行的字节数组
byte[] scanlineInput = new byte[bitsInput.Stride];
byte[] scanlineMask = new byte[bitsMask.Stride];
byte[] scanlineOutput = new byte[bitsOutput.Stride];
Marshal.Copy(bitsInput.Scan0 + scanOffsetInput, scanlineInput, 0, scanlineInput.Length);
Marshal.Copy(bitsMask.Scan0 + scanOffsetMask, scanlineMask, 0, scanlineMask.Length);
// 遍历每一列(或每一像素)
for (int x = 0; x < image.Width; x++)
{
// 计算当前像素在字节数组中的位置(基于每个像素4个字节)
int pixelOffsetInput = x * 4;
int pixelOffsetMask = x * 4;
int pixelOffsetOutput = x * 4;
// 读取输入图像的RGB值
byte blue = scanlineInput[pixelOffsetInput];
byte green = scanlineInput[pixelOffsetInput + 1];
byte red = scanlineInput[pixelOffsetInput + 2];
// 读取遮罩图像的alpha值
byte alpha = scanlineMask[pixelOffsetMask];
// 将值写入输出图像的对应位置
scanlineOutput[pixelOffsetOutput] = blue;
scanlineOutput[pixelOffsetOutput + 1] = green;
scanlineOutput[pixelOffsetOutput + 2] = red;
scanlineOutput[pixelOffsetOutput + 3] = alpha;
}
// 将处理过的行复制回输出图像的BitmapData中
Marshal.Copy(scanlineOutput, 0, bitsOutput.Scan0 + scanOffsetOutput, scanlineOutput.Length);
}
调用
using System.Drawing.Imaging;
using iText.Kernel.Pdf;
using itext.pdfimage.Extensions;
namespace pdf2image02;
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Start Bliep");
var pdfPath = "D:\\ChatFiles\\WechatWorkFile\\WXWork\\1688853272898895\\Cache\\File\\2024-04\\wave.pdf";
var pdf = File.Open(pdfPath, FileMode.Open);
var reader = new PdfReader(pdf);
var pdfDocument = new PdfDocument(reader);
var bitmaps = pdfDocument.ConvertToBitmaps();
foreach (var bitmap in bitmaps)
{
bitmap.Save(Path.Combine("F:\\Desktop\\test\\aa", $"wave-{DateTime.Now.Ticks}.png"), ImageFormat.Png);
bitmap.Dispose();
}
var page1 = pdfDocument.GetPage(1);
var bitmap1 = page1.ConvertPageToBitmap();
bitmap1.Save(Path.Combine("F:\\Desktop\\test\\aa", $"wave-page1-{DateTime.Now.Ticks}.png"), ImageFormat.Png);
bitmap1.Dispose();
Console.WriteLine("End Bliep!");
}
}
20240413接入最新版的itext7也是可以的