使用PdfSharp从pdf中提取“FLATEDECODE”类型的图像

时间:2011-11-24 09:11:49

标签: image extract pdfsharp

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

2 个答案:

答案 0 :(得分:0)

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

那应该不是.Png?

答案 1 :(得分:0)

I have done this using iTextSharp. Following is the code I have done for [filter.Equals(PdfName.FLATEDECODE)] this image.

add using System.Runtime.InteropServices; to access Marshal

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;
}