title: How to extract FlateDecoded Images from PDF with PDFSharp
body: <p>how do I extract Images, which are FlateDecoded (such like PNG) out of a PDF-Document with PDFSharp?</p>
  
  <p>I found that comment in a Sample of PDFSharp:</p>
  
  <pre><code>// TODO: You can put the code here that converts vom PDF internal image format to a
  // Windows bitmap
  // and use GDI+ to save it in PNG format.
  // [...]
  // Take a look at the file
  // PdfSharp.Pdf.Advanced/PdfImage.cs to see how we create the PDF image formats.
  </code></pre>
  
  <p>Does anyone have a solution for this problem?</p>
  
  <p>Thanks for your replies.</p>
  
  <p><strong>EDIT:</strong> Because I'm not able to answer on my own Question within 8 hours, I do it on that way:</p>
  
  <p>Thanks for your very fast reply.</p>
  
  <p>I added some Code to the Method "ExportAsPngImage", but I didn't get the wanted results. It is just extracting a few more Images (png) and they don't have the right colors and are distorted.</p>
  
  <p>Here's my actual Code:</p>
  
  <pre><code>PdfSharp.Pdf.Filters.FlateDecode flate = new PdfSharp.Pdf.Filters.FlateDecode();
          byte[] decodedBytes = flate.Decode(bytes);
  
          System.Drawing.Imaging.PixelFormat pixelFormat;
  
          switch (bitsPerComponent)
          {
              case 1:
                  pixelFormat = PixelFormat.Format1bppIndexed;
                  break;
              case 8:
                  pixelFormat = PixelFormat.Format8bppIndexed;
                  break;
              case 24:
                  pixelFormat = PixelFormat.Format24bppRgb;
                  break;
              default:
                  throw new Exception("Unknown pixel format " + bitsPerComponent);
          }
  
          Bitmap bmp = new Bitmap(width, height, pixelFormat);
          var bmpData = bmp.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, pixelFormat);
          int length = (int)Math.Ceiling(width * bitsPerComponent / 8.0);
          for (int i = 0; i &lt; height; i++)
          {
              int offset = i * length;
              int scanOffset = i * bmpData.Stride;
              Marshal.Copy(decodedBytes, offset, new IntPtr(bmpData.Scan0.ToInt32() + scanOffset), length);
          }
          bmp.UnlockBits(bmpData);
          using (FileStream fs = new FileStream(@"C:\Export\PdfSharp\" + String.Format("Image{0}.png", count), FileMode.Create, FileAccess.Write))
          {
              bmp.Save(fs, System.Drawing.Imaging.ImageFormat.Png);
          }
  </code></pre>
  
  <p>Is that the right way? Or should I choose another way? Thanks a lot!</p>