> For the complete documentation index, see [llms.txt](https://docs.apryse.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.apryse.com/ios/get-started/samples/imageextracttest.md).

# ImageExtract

Here is a sample showcasing how to extract image from pdf using Obj-C and Swift. Run the sample with Apryse iOS SDK free trial.

Sample code in Swift and Obj-C for using Apryse iOS SDK to extract images from PDF files, along with their positioning information and DPI. Instead of converting PDF images to a Bitmap, you can also extract uncompressed/compressed image data directly using element.GetImageData() (described in the [PDF Data Extraction](/ios/get-started/samples/elementreaderadvtest.md) code sample).

Learn more about our full [PDF Data Extraction SDK Capabilities](https://apryse.com/capabilities/extraction).

To start your free trial, [get stated with iOS SDK](/ios/get-started/get-started.md).

{% tabs %}
{% tab title="Obj-C" %}
{% code lineNumbers="true" %}

```objc
//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
// Consult legal.txt regarding legal and license information.
//---------------------------------------------------------------------------------------

#import <OBJC/PDFNetOBJC.h>
#import <Foundation/Foundation.h>

//-----------------------------------------------------------------------------------
// This sample illustrates one approach to PDF image extraction 
// using PDFNet.
// 
// Note: Besides direct image export, you can also convert PDF images 
// to GDI+ Bitmap, or extract uncompressed/compressed image data directly 
// using element.GetImageData() (e.g. as illustrated in ElementReaderAdv 
// sample project).
//-----------------------------------------------------------------------------------

int image_counter = 0;

void ImageExtract(PTElementReader* reader)
{
    PTElement *element; 
    while ((element = [reader Next]) != NULL)
    {
        switch ([element GetType]) 
        {
        case e_ptimage:
        case e_ptinline_image: 
            {
                NSLog(@"--> Image: %d", ++image_counter);
                NSLog(@"    Width: %d", [element GetImageWidth]);
                NSLog(@"    Height: %d", [element GetImageHeight]);
                NSLog(@"    BPC: %d", [element GetBitsPerComponent]);

                PTMatrix2D *ctm = [element GetCTM];
                double x2=1, y2=1;
                PTPDFPoint* p = [ctm Mult: [[PTPDFPoint alloc] initWithPx: x2 py: y2]];
                NSLog(@"    Coords: x1=%.2f, y1=%.2f, x2=%.2f, y2=%.2f", [ctm getM_h], [ctm getM_v], [p getX], [p getY]);

                if ([element GetType] == e_ptimage) 
                {
                    PTImage *image = [[PTImage alloc] initWithImage_xobject: [element GetXObject]];
                    
                    NSString *path = [@"../../TestFiles/Output/" stringByAppendingPathComponent:[NSString stringWithFormat:@"image_extract1_%d", image_counter]];
                    [image ExportToFile: path];
                }
            }
            break;
        case e_ptform: // Process form XObjects
            [reader FormBegin]; 
            ImageExtract(reader);
            [reader End]; 
            break;
        default:
            break;
        }
    }
}

int main(int argc, char *argv[])
{
    @autoreleasepool {
        int ret = 0;

        // Initialize PDFNet
        [PTPDFNet Initialize: 0];

        // Example 1: 
        // Extract images by traversing the display list for 
        // every page. With this approach it is possible to obtain 
        // image positioning information and DPI.
        @try  
        { 
            PTPDFDoc *doc = [[PTPDFDoc alloc] initWithFilepath: @"../../TestFiles/newsletter.pdf"];
            [doc InitSecurityHandler];
            PTElementReader *reader = [[PTElementReader alloc] init];
            //  Read every page
            PTPageIterator *itr;
            for (itr=[doc GetPageIterator: 1]; [itr HasNext]; [itr Next]) 
            {
                [reader Begin: [itr Current]];
                ImageExtract(reader);
                [reader End];
            }

            NSLog(@"Done.");
        }
        @catch(NSException* e)
        {
            NSLog(@"%@", e.reason);
            ret = 1;
        }

        NSLog(@"----------------------------------------------------------------");

        // Example 2: 
        // Extract images by scanning the low-level document.
        @try  
        { 
            PTPDFDoc *doc = [[PTPDFDoc alloc] initWithFilepath: @"../../TestFiles/newsletter.pdf"];
        
            [doc InitSecurityHandler];
            image_counter = 0;

            PTSDFDoc *cos_doc=[doc GetSDFDoc];
            int num_objs = [cos_doc XRefSize];
            int i;
            for(i=1; i<num_objs; ++i) 
            {
                PTObj * obj = [cos_doc GetObj: i];
                if((obj != NULL) && (![obj IsFree]) && ([obj IsStream])) 
                {
                    // Process only images
                    PTDictIterator *itr = [obj Find: @"Type"];
                    if((![itr HasNext]) || (![[[itr Value] GetName] isEqualToString: @"XObject"]))
                        continue;

                    itr = [obj Find: @"Subtype"];
                    if((![itr HasNext]) || (![[[itr Value] GetName] isEqualToString: @"Image"]))
                        continue;
                    
                    PTImage *image = [[PTImage alloc] initWithImage_xobject: obj];
                    NSLog(@"--> Image: %d", ++image_counter);
                    NSLog(@"    Width: %d", [image GetImageWidth]);
                    NSLog(@"    Height: %d", [image GetImageHeight]);
                    NSLog(@"    BPC: %d", [image GetBitsPerComponent]);
                
                    NSString *path = [@"../../TestFiles/Output/" stringByAppendingPathComponent:[NSString stringWithFormat:@"image_extract2_%d", image_counter]];
                    [image ExportToFile: path];
                }
            }
            NSLog(@"Done.");
        }
        @catch(NSException* e)
        {
        NSLog(@"%@", e.reason);
            ret = 1;
        }
        [PTPDFNet Terminate: 0];        
        return ret;
    }
}
```

{% endcode %}
{% endtab %}

{% tab title="Swift" %}
{% code lineNumbers="true" %}

```swift
//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2019 by PDFTron Systems Inc. All Rights Reserved.
// Consult legal.txt regarding legal and license information.
//---------------------------------------------------------------------------------------

import PDFNet
import Foundation

//-----------------------------------------------------------------------------------
// This sample illustrates one approach to PDF image extraction
// using PDFNet.
//
// Note: Besides direct image export, you can also convert PDF images
// to GDI+ Bitmap, or extract uncompressed/compressed image data directly
// using element.GetImageData() (e.g. as illustrated in ElementReaderAdv
// sample project).
//-----------------------------------------------------------------------------------

var image_counter: Int = 0

func ImageExtract(reader: PTElementReader) {
    while let element = reader.next() {
        switch element.getType() {
        case e_ptimage, e_ptinline_image:
            image_counter += 1
            print("--> Image: \(image_counter)")
            print("    Width: \(element.getImageWidth())")
            print("    Height: \(element.getImageHeight())")
            print("    BPC: \(element.getBitsPerComponent())")
            
            let ctm: PTMatrix2D = element.getCTM()
            let x2: Double = 1
            let y2: Double = 1
            ctm.mult(PTPDFPoint(px: x2, py: y2))
            print("    Coords: x1=\(ctm.getM_h()), y1=\(ctm.getM_v()), x2=\(x2), y2=\(y2)")
            
            if element.getType() == e_ptimage {
                let image: PTImage = PTImage(image_xobject: element.getXObject())
                let path: String = URL(fileURLWithPath: URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]).appendingPathComponent("").absoluteString).appendingPathComponent("image_extract1_\(image_counter)").path
                image.export(toFile: path)
            }
        case e_ptform:
            // Process form XObjects
            reader.formBegin()
            ImageExtract(reader: reader)
            reader.end()
        default:
            break
        }
    }
}

func runImageExtractTest() -> Int {
    return autoreleasepool {
        var ret: Int = 0
        
        // Initialize PDFNet
        
        
        // Example 1:
        // Extract images by traversing the display list for
        // every page. With this approach it is possible to obtain
        // image positioning information and DPI.
        do {
            try PTPDFNet.catchException {
                let doc: PTPDFDoc = PTPDFDoc(filepath: Bundle.main.path(forResource: "newsletter", ofType: "pdf"))
                doc.initSecurityHandler()
                
                let reader: PTElementReader = PTElementReader()
                //  Read every page
                let itr: PTPageIterator = doc.getPageIterator(1)
                while itr.hasNext() {
                    reader.begin(itr.current())
                    ImageExtract(reader: reader)
                    reader.end()
                    itr.next()
                }
                
                print("Done...")
            }
        } catch let e as NSError {
            print("\(e)")
            ret = 1
        }
        
        print("----------------------------------------------------------------")
        
        // Example 2:
        // Extract images by scanning the low-level document.
        do {
            try PTPDFNet.catchException {
                let doc: PTPDFDoc = PTPDFDoc(filepath: Bundle.main.path(forResource: "newsletter", ofType: "pdf"))
                doc.initSecurityHandler()
                
                image_counter = 0
                
                let cos_doc: PTSDFDoc = doc.getSDFDoc()
                let num_objs = cos_doc.xRefSize()
                for i in 1..<num_objs {
                    guard let obj: PTObj = cos_doc.getObj(i) else {
                        continue
                    }
                    if !obj.isFree() && obj.isStream() {
                        // Process only images
                        var itr: PTDictIterator = obj.find("Type")
                        if !itr.hasNext() || !(itr.value().getName() == "XObject") {
                            continue
                        }
                        
                        itr = obj.find("Subtype")
                        if !itr.hasNext() || !(itr.value().getName() == "Image") {
                            continue
                        }
                        
                        let image: PTImage = PTImage(image_xobject: obj)
                        image_counter += 1
                        print("-. Image: \(image_counter)")
                        print("    Width: \(image.getWidth())")
                        print("    Height: \(image.getHeight())")
                        print("    BPC: \(image.getBitsPerComponent())")
                        
                        let path: String = URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]).appendingPathComponent("image_extract2_\(image_counter)").path
                        image.export(toFile: path)
                    }
                }
                
                print("Done...")
            }
        } catch let e as NSError {
            print("\(e)")
            ret = 1
        }
        
        return ret
    }
}
```

{% endcode %}
{% endtab %}
{% endtabs %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.apryse.com/ios/get-started/samples/imageextracttest.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
