我试图从 pdf 中提取图像。图像是过滤器“FlateDecode”。我得到了图像,但它只是一条黑色的路径。我是新手,请帮助我。代码是:
int width = xObject.Elements.GetInteger(PdfImage.Keys.Width);
int height = xObject.Elements.GetInteger(PdfImage.Keys.Height);
int bitsPerComponent = xObject.Elements.GetInteger (PdfSharp.Pdf.Advanced.PdfImage.Keys.BitsPerComponent);
System.Drawing.Imaging.PixelFormat pixelFormat = new System.Drawing.Imaging.PixelFormat();
switch (bitsPerComponent)
{
case 1:
pixelFormat = System.Drawing.Imaging.PixelFormat.Format1bppIndexed;
break;
case 8:
pixelFormat = System.Drawing.Imaging.PixelFormat.Format8bppIndexed;
break;
case 24:
pixelFormat = System.Drawing.Imaging.PixelFormat.Format24bppRgb;
break;
default:
throw new Exception("Unknown pixel format " + bitsPerComponent);
}
Bitmap bitmap = new Bitmap(width, height, pixelFormat);
byte[] raw = xObject.Stream.Value;
BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, pixelFormat);
Marshal.Copy(raw, 0, bitmapData.Scan0, raw.Length);
bitmap.UnlockBits(bitmapData);
using (MemoryStream imageStream = new MemoryStream())
{
bitmap.Save(imageStream, ImageFormat.png);
System.Drawing.Image img = System.Drawing.Image.FromStream(imageStream);
img.Save("D:\\trial.png", System.Drawing.Imaging.ImageFormat.png);
}