# Extract all images from a PDF in C#

> Save every image of a PDF in .NET, JPEGs as stored and other images as PNG, with size and resolution. MIT licensed, pure C#, no native code.

Available since 1.1.

Save the images every page draws, as JPEG or PNG files.

## Short answer

`GetImages` lists the images a page draws, with their placement and resolution. A JPEG
(`DCTDecode`) is written as stored with `GetEncodedData`, so nothing is recompressed. Other images
are decoded to 8 bit gray or RGB pixels with `Decode` and saved as PNG.

```csharp title="recipe-extract-images-from-pdf.cs"
#:package PdfNetStack@1.2.0
using PdfNetStack;

PdfDocument doc = PdfDocument.Open("manual.pdf");
for (int p = 0; p < doc.Pages.Count; p++)
{
    IReadOnlyList<PdfPageImage> images = doc.Pages[p].GetImages();
    for (int i = 0; i < images.Count; i++)
    {
        PdfPageImage image = images[i];
        string name = $"page{p + 1}-image{i + 1}";
        if (image.Encoding == "DCTDecode")
        {
            File.WriteAllBytes(name + ".jpg", image.GetEncodedData());   // the JPEG as stored
        }
        else if (image.Decode() is PdfBitmap bitmap)
        {
            bitmap.SavePng(name + ".png");                                // 8 bit gray or RGB pixels
        }
        Console.WriteLine($"{name}: {image.Width}x{image.Height}, {image.Encoding ?? "raw"}, {image.HorizontalResolution:0} dpi");
    }
}
```

## Notes

- An image drawn on several pages is listed on each of them. `HorizontalResolution` and
  `VerticalResolution` give the dots per inch at which it is drawn.
- `Decode` handles raw samples, JPEG, JPEG 2000, CCITT fax and JBIG2. Soft masks are not applied,
  and `Decode` returns null for an unsupported color space.

## Related

- [Extract images](https://www.jadev-corp.com/guides/extract-images/)
- [Extract text](https://www.jadev-corp.com/guides/extract-text/)
- API: [PdfPageImage](https://www.jadev-corp.com/api/pdfnetstack/pdfpageimage/), [PdfBitmap](https://www.jadev-corp.com/api/pdfnetstack/pdfbitmap/)

Source: https://www.jadev-corp.com/pdfnetstack/recipes/extract-images-from-pdf/
