> 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/jbig2test.md).

# JBIGTest

Sample Obj-C code for using Apryse SDK to recompress bitonal (black and white) images in existing PDF documents using JBIG2 compression (lossless or lossy). The sample is intended to show how to speci

Sample Obj-C code for using Apryse SDK to recompress bitonal (black and white) images in existing PDF documents using JBIG2 compression (lossless or lossy). The sample is intended to show how to specify hint information for the image encoder and is not meant to be a generic PDF optimization tool. To demonstrate the possible compression rates, we recompressed a document containing 17 scanned pages. The original input document is \~1.4MB and is using standard CCITT Fax compression. Lossless JBIG2 compression shrunk the filesize to 641KB, while lossy JBIG2 compression shrunk it to 176KB. Learn more about our [iOS SDK](/ios/guides.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 project illustrates how to recompress bi-tonal images in an 
// existing PDF document using JBIG2 compression. The sample is not intended 
// to be a generic PDF optimization tool.
//
// You can download the entire document using the following link:
//   http://www.pdftron.com/net/samplecode/data/US061222892.pdf
//
int main(int argc, char *argv[]) 
{
    @autoreleasepool {

        [PTPDFNet Initialize: 0];
        
        @try 
        {
            PTPDFDoc *pdf_doc = [[PTPDFDoc alloc] initWithFilepath: @"../../TestFiles/US061222892-a.pdf"];
            [pdf_doc InitSecurityHandler];

            PTSDFDoc *cos_doc = [pdf_doc GetSDFDoc];
            int num_objs = [cos_doc XRefSize];
            int i=1;
            for(; i<num_objs; ++i) 
            {
                PTObj * obj = [cos_doc GetObj: i];
                if(obj && ![obj IsFree] && [obj IsStream]) 
                {
                    // Process only images
                    PTDictIterator *itr = [obj Find: @"Subtype"];
                    if(![itr HasNext] || !([[[itr Value] GetName] isEqualToString:@"Image"]))
                        continue;
                    
                    PTImage *input_image = [[PTImage alloc] initWithImage_xobject: obj];
                    // Process only gray-scale images
                    if([input_image GetComponentNum] != 1)
                        continue;
                    int bpc = [input_image GetBitsPerComponent];
                    if(bpc != 1) // Recompress only 1 BPC images
                        continue;

                    // Skip images that are already compressed using JBIG2
                    itr = [obj Find: @"Filter"];
                    if ([itr HasNext] && [[itr Value] IsName] && 
                        [[[itr Value] GetName] isEqualToString:@"JBIG2Decode"]) continue;

                    PTFilter *filter=[obj GetDecodedStream];
                    PTFilterReader *reader = [[PTFilterReader alloc] initWithFilter: filter];


                    PTObjSet *hint_set = [[PTObjSet alloc] init]; // A hint to image encoder to use JBIG2 compression
                    PTObj * hint=[hint_set CreateArray];
                
                    [hint PushBackName: @"JBIG2"];
                    [hint PushBackName: @"Lossless"];

                    PTImage *new_image = [PTImage CreateWithFilterData: cos_doc image_data: reader width: [input_image GetImageWidth] height: [input_image GetImageHeight] bpc: 1 color_space: [PTColorSpace CreateDeviceGray] encoder_hints: hint];

                    PTObj * new_img_obj = [new_image GetSDFObj];
                    itr = [obj Find: @"Decode"];
                    if([itr HasNext])
                        [new_img_obj Put: @"Decode" obj: [itr Value]];
                    itr = [obj Find: @"ImageMask"];
                    if ([itr HasNext])
                        [new_img_obj Put: @"ImageMask" obj: [itr Value]];
                    itr = [obj Find: @"Mask"];
                    if ([itr HasNext])
                        [new_img_obj Put: @"Mask" obj: [itr Value]];

                    [cos_doc Swap: i obj_num2: [new_img_obj GetObjNum]];
                }
            }

            [pdf_doc SaveToFile: @"../../TestFiles/Output/US061222892_JBIG2.pdf" flags: e_ptremove_unused];
        }
        @catch(NSException *e)
        {
            NSLog(@"%@", e.reason);
            NSLog(@"Please make sure that the pathname to the test file is correct.");
        }
        
        NSLog(@"Done.");
        [PTPDFNet Terminate: 0];
        return 0;
    }
}
```

{% 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 project illustrates how to recompress bi-tonal images in an
// existing PDF document using JBIG2 compression. The sample is not intended
// to be a generic PDF optimization tool.
//
// You can download the entire document using the following link:
//   http://www.pdftron.com/net/samplecode/data/US061222892.pdf
//
func runJBIG2Test() -> Int {
    return autoreleasepool {
        
        
        do {
            try PTPDFNet.catchException {
                let pdf_doc: PTPDFDoc = PTPDFDoc(filepath: Bundle.main.path(forResource: "US061222892-a", ofType: "pdf"))
                pdf_doc.initSecurityHandler()
                
                let cos_doc: PTSDFDoc = pdf_doc.getSDFDoc()
                let num_objs = cos_doc.xRefSize()
                for i in 1..<num_objs {
                    guard let obj: PTObj = cos_doc.getObj(UInt32(i)) else {
                        continue
                    }
                    if !obj.isFree() && obj.isStream() {
                        // Process only images
                        var itr: PTDictIterator = obj.find("Subtype")
                        if !itr.hasNext() || !(itr.value().getName() == "Image") {
                            continue
                        }
                        
                        let input_image: PTImage = PTImage(image_xobject: obj)
                        // Process only gray-scale images
                        if input_image.getComponentNum() != 1 {
                            continue
                        }
                        let bpc: Int32 = input_image.getBitsPerComponent()
                        if bpc != 1 {
                            // Recompress only 1 BPC images
                            continue
                        }
                        
                        // Skip images that are already compressed using JBIG2
                        itr = obj.find("Filter")
                        if itr.hasNext() && itr.value().isName() && (itr.value().getName() == "JBIG2Decode") {
                            continue
                        }
                        
                        let filter: PTFilter = obj.getDecodedStream()
                        let reader = PTFilterReader(filter: filter)
                        
                        let hint_set: PTObjSet = PTObjSet()   // A hint to image encoder to use JBIG2 compression
                        let hint: PTObj = hint_set.createArray()
                        
                        hint.pushBackName("JBIG2")
                        hint.pushBackName("Lossless")
                        
                        let new_image: PTImage = PTImage.create(withFilterData: cos_doc, image_data: reader, width: input_image.getWidth(), height: input_image.getHeight(), bpc: 1, color_space: PTColorSpace.createDeviceGray(), encoder_hints: hint)
                        
                        let new_img_obj: PTObj = new_image.getSDFObj()
                        itr = obj.find("Decode")
                        if itr.hasNext() {
                            new_img_obj.put("Decode", obj: itr.value())
                        }
                        itr = obj.find("ImageMask")
                        if itr.hasNext() {
                            new_img_obj.put("ImageMask", obj: itr.value())
                        }
                        itr = obj.find("Mask")
                        if itr.hasNext() {
                            new_img_obj.put("Mask", obj: itr.value())
                        }
                        
                        cos_doc.swap(UInt32(i), obj_num2: new_img_obj.getNum())
                    }
                }
                
                pdf_doc.save(toFile: URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]).appendingPathComponent("US061222892_JBIG2.pdf").path, flags: e_ptremove_unused.rawValue)
            }
        } catch let e as NSError {
            print("\(e)")
            print("Please make sure that the pathname to the test file is correct.")
        }
        
        print("Done.")
        
        return 0
    }
}
```

{% 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/jbig2test.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.
