3

我试图从 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);
 }
4

2 回答 2

0
img.Save("D:\\trial.png", System.Drawing.Imaging.ImageFormat.Jpeg);

那不应该是.Png吗?

于 2011-11-24T09:20:29.563 回答
0

我已经使用 iTextSharp 完成了这项工作。以下是我为 [filter.Equals(PdfName.FLATEDECODE)] 这个图像所做的代码。

添加using System.Runtime.InteropServices;访问元帅

Bitmap bmp = new Bitmap(width, height, pixelFormat);
var bmd = bmp.LockBits(new System.Drawing.Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, pixelFormat);
int length = (int)Math.Ceiling(Convert.ToInt32(width) * i_bpp / 8.0);
for (int j = 0; j < height; j++)
{
int offset = j * length;
int scanOffset = j * bmd.Stride;
Marshal.Copy(bytes, offset, new IntPtr(bmd.Scan0.ToInt32() + scanOffset), length);
}
bmp.UnlockBits(bmd);
using (FileStream fs = new FileStream(Server.MapPath("~/Temp") + "\\" + String.Format("Image{0}.png", page_i), FileMode.Create, FileAccess.Write))
{
bmp.Save(fs, System.Drawing.Imaging.ImageFormat.Png);
PdfImg_ = (System.Drawing.Image)bmp;
}
于 2017-08-04T12:44:03.913 回答