Giter Site home page Giter Site logo

Comments (4)

robertovaldesperez avatar robertovaldesperez commented on June 11, 2024 1

Hi, I had to create a recursive method to extract images, because some were inside other resources...

private static IEnumerable<PdfDictionary> GetXObjectImages(PdfDictionary pdfDictionary) { var resources = pdfDictionary.Elements.GetDictionary("/Resources"); if (resources != null) { var xObjects = resources.Elements.GetDictionary("/XObject"); if (xObjects != null) { foreach (var item in xObjects.Elements.Values) { if (item is PdfReference reference) { if (reference.Value is PdfDictionary xObject) { if (xObject.Elements.GetString(PdfImage.Keys.Subtype) == "/Image") { yield return xObject; } else { foreach (var xObject1 in GetXObjectImages(xObject)) { if (xObject1.Elements.GetString(PdfImage.Keys.Subtype) == "/Image") { yield return xObject1; } } } } } } } } }

from pdfsharpcore.

Bogdancev avatar Bogdancev commented on June 11, 2024

Hello, @robertovaldesperez

I'm not sure if it helps, but this is how I do it. I have a pdf-file which is produced by a scanner, that file contains several pages and each page has an image.
This image can be jpeg or tif (I think your format "FlatDecode" is png, if I'm not mistaken. And if so, the library probably doesn't have a straight way of converting it).

  1. File is already in memory stream, I go to specified page and extract the image:
public static MemoryStream ExtractPageImage(MemoryStream ms, int PageNumber)
{
     if (null == ms || 0 == ms.Length) return null;
     ms.Position = 0;

     PdfDocument document = PdfReader.Open(ms, PdfDocumentOpenMode.ReadOnly);
     if (document.Pages.Count <= PageNumber) return null;
     PdfPage pdfPage = document.Pages[PageNumber];

     PdfDictionary resources = pdfPage.Elements.GetDictionary("/Resources");
     if (resources != null)
     {
         PdfDictionary xObjects = resources.Elements.GetDictionary("/XObject");
         if (xObjects != null)
         {
             ICollection<PdfItem> items = xObjects.Elements.Values;
             foreach (PdfItem item in items)
             {
                 if (item is PdfReference reference)
                 {
                     if (reference.Value is PdfDictionary xObject && xObject.Elements.GetString("/Subtype") == "/Image")
                     {
                         var msImage = ExportImage(xObject);
                         return msImage;
                     }
                 }
             }
         }
     }
     throw new Exception("image not found inside pdf-file.");
 }
  1. Here is how I decide on the image format:
static MemoryStream ExportImage(PdfDictionary image)
{
     string filter = image.Elements.GetName("/Filter");
     MemoryStream msImage = filter switch
     {
         "/DCTDecode" => ExportJpegImage(image),
         "/CCITTFaxDecode" => ExportTifImage(image),
         _ => throw new Exception("\"" + filter + " is unsupported image format."),
     };

     Image img = Image.FromStream(msImage);
     if (img.Height > img.Width)
     {
         img.RotateFlip(RotateFlipType.Rotate90FlipNone); // Rotates the image clockwise 90 degrees
         var msRotated = new MemoryStream();
         img.Save(msRotated, System.Drawing.Imaging.ImageFormat.Jpeg);
         msImage.Dispose();
         return msRotated;
     }
     return msImage;
}
  1. And here is a methods for jpeg and tiff:
static MemoryStream ExportJpegImage(PdfDictionary image)
{
    try
    {
        // Fortunately JPEG has native support in PDF and exporting an image is just writing the stream to a file.
        byte[] stream = image.Stream.Value;
        var ms = new MemoryStream(stream);
        return ms;
    }
    catch
    {
        throw new Exception("failed converting JPEG image inside PDF-file.");
    }
}

static MemoryStream ExportTifImage(PdfDictionary image)
{
    try
    {
        MemoryStream ms = new MemoryStream();

        int width = image.Elements.GetInteger(PdfImage.Keys.Width);
        int height = image.Elements.GetInteger(PdfImage.Keys.Height);
        int bpp = image.Elements.GetInteger(PdfImage.Keys.BitsPerComponent);
        int K = 0;

        //https://github.com/gheeres/PDFSharp.Extensions/blob/master/Pdf/PdfDictionaryExtensions.cs - some explanations about DecodeParams and more
        PdfObject oDecodeParams = image.Elements.GetObject(PdfImage.Keys.DecodeParms);
        if (oDecodeParams is PdfDictionary)
            if (((PdfDictionary)oDecodeParams).Elements.ContainsKey("/K"))
                K = ((PdfDictionary)oDecodeParams).Elements.GetInteger("/K");

        byte[] data = image.Stream.Value;

        Tiff tiff = Tiff.ClientOpen("in-memory", "w", ms, new TiffStream());
        tiff.SetField(TiffTag.IMAGEWIDTH, (uint)(width));
        tiff.SetField(TiffTag.IMAGELENGTH, (uint)(height));
        if (0 > K)
            tiff.SetField(TiffTag.COMPRESSION, Compression.CCITTFAX4);
        if (0 <= K)
            tiff.SetField(TiffTag.COMPRESSION, Compression.CCITTFAX3);
        tiff.SetField(TiffTag.BITSPERSAMPLE, (uint)(bpp));
        tiff.SetField(TiffTag.SAMPLESPERPIXEL, 1);

        tiff.WriteRawStrip(0, data, data.Length);
        tiff.Flush();
        return ms;
    }
    catch
    {
        throw new Exception("failed converting TIFF image inside PDF-file.");
    }
}

I hope this helps, I did it 5 or 6 years ago and it still works perfectly.
Regards, Sergii

from pdfsharpcore.

robertovaldesperez avatar robertovaldesperez commented on June 11, 2024

Hi @Bogdancev, I'm going to try this code, Do you have an example of how to extract a PNG image?

from pdfsharpcore.

Bogdancev avatar Bogdancev commented on June 11, 2024

Hi @robertovaldesperez
Unfortunally not, I have a full control over the settings of the company scanners, so they are set up to produce jpegs or tiffs.

from pdfsharpcore.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.