> 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/android/get-started/samples/jbig2test.md).

# JBIGTest

Sample Java 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 specif

Sample Java 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 [Android SDK](/core/get-started/languages/java.md).

{% tabs %}
{% tab title="Java" %}
{% code lineNumbers="true" %}

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

package com.pdftron.android.pdfnetsdksamples.samples;

import com.pdftron.android.pdfnetsdksamples.OutputListener;
import com.pdftron.android.pdfnetsdksamples.PDFNetSample;
import com.pdftron.android.pdfnetsdksamples.R;
import com.pdftron.android.pdfnetsdksamples.util.Utils;
import com.pdftron.filters.Filter;
import com.pdftron.filters.FilterReader;
import com.pdftron.pdf.ColorSpace;
import com.pdftron.pdf.Image;
import com.pdftron.pdf.PDFDoc;
import com.pdftron.sdf.DictIterator;
import com.pdftron.sdf.Obj;
import com.pdftron.sdf.ObjSet;
import com.pdftron.sdf.SDFDoc;

import java.util.ArrayList;

//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.

public class JBIG2Test extends PDFNetSample {

	private static OutputListener mOutputListener;

	private static ArrayList<String> mFileList = new ArrayList<>();

    public JBIG2Test() {
        setTitle(R.string.sample_jbig_title);
        setDescription(R.string.sample_jbig_description);
    }

	@Override
	public void run(OutputListener outputListener) {
		super.run(outputListener);
		mOutputListener = outputListener;
		mFileList.clear();
		printHeader(outputListener);

        try (PDFDoc pdf_doc = new PDFDoc(Utils.getAssetTempFile(INPUT_PATH + "US061222892-a.pdf").getAbsolutePath())) {
            pdf_doc.initSecurityHandler();

            SDFDoc cos_doc = pdf_doc.getSDFDoc();
            int num_objs = (int) cos_doc.xRefSize();
            for (int i = 1; i < num_objs; ++i) {
                Obj obj = cos_doc.getObj(i);
                if (obj != null && !obj.isFree() && obj.isStream()) {
                    // Process only images
                    DictIterator itr = obj.find("Subtype");
                    if (!itr.hasNext() || !itr.value().getName().equals("Image"))
                        continue;

                    Image input_image = new Image(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().equals("JBIG2Decode")) continue;

                    Filter filter = obj.getDecodedStream();
                    FilterReader reader = new FilterReader(filter);

                    ObjSet hint_set = new ObjSet();
                    Obj hint = hint_set.createArray(); // A hint to image encoder to use JBIG2 compression
                    hint.pushBackName("JBIG2");
                    hint.pushBackName("Lossless");

                    Image new_image = Image.create(cos_doc, reader,
                            input_image.getImageWidth(),
                            input_image.getImageHeight(), 1, ColorSpace.createDeviceGray(), hint);

                    Obj new_img_obj = new_image.getSDFObj();
                    itr = obj.find("Decode");
                    if (itr.hasNext())
                        new_img_obj.put("Decode", itr.value());
                    itr = obj.find("ImageMask");
                    if (itr.hasNext())
                        new_img_obj.put("ImageMask", itr.value());
                    itr = obj.find("Mask");
                    if (itr.hasNext())
                        new_img_obj.put("Mask", itr.value());

                    cos_doc.swap(i, new_img_obj.getObjNum());
                }
            }

            pdf_doc.save(Utils.createExternalFile("US061222892_JBIG2.pdf", mFileList).getAbsolutePath(), SDFDoc.SaveMode.REMOVE_UNUSED, null);
        } catch (Exception e) {
            mOutputListener.printError(e.getStackTrace());
        }

		for (String file : mFileList) {
			addToFileList(file);
		}
		printFooter(outputListener);
	}


}
```

{% endcode %}
{% endtab %}

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

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

package com.pdftron.android.pdfnetsdksamples.samples

import com.pdftron.android.pdfnetsdksamples.OutputListener
import com.pdftron.android.pdfnetsdksamples.PDFNetSample
import com.pdftron.android.pdfnetsdksamples.R
import com.pdftron.android.pdfnetsdksamples.util.Utils
import com.pdftron.filters.FilterReader
import com.pdftron.pdf.ColorSpace
import com.pdftron.pdf.Image
import com.pdftron.pdf.PDFDoc
import com.pdftron.sdf.ObjSet
import com.pdftron.sdf.SDFDoc
import java.util.*

//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.

class JBIG2Test : PDFNetSample() {
    init {
        setTitle(R.string.sample_jbig_title)
        setDescription(R.string.sample_jbig_description)
    }

    override fun run(outputListener: OutputListener?) {
        super.run(outputListener)
        mOutputListener = outputListener
        mFileList.clear()
        printHeader(outputListener!!)

        try {
            PDFDoc(Utils.getAssetTempFile(PDFNetSample.INPUT_PATH + "US061222892-a.pdf")!!.absolutePath).use { pdf_doc ->
                pdf_doc.initSecurityHandler()

                val cos_doc = pdf_doc.sdfDoc
                val num_objs = cos_doc.xRefSize().toInt()
                for (i in 1 until num_objs) {
                    val obj = cos_doc.getObj(i.toLong())
                    if (obj != null && !obj.isFree && obj.isStream) {
                        // Process only images
                        var itr = obj.find("Subtype")
                        if (!itr.hasNext() || itr.value().name != "Image")
                            continue

                        val input_image = Image(obj)
                        // Process only gray-scale images
                        if (input_image.componentNum != 1)
                            continue
                        val bpc = input_image.bitsPerComponent
                        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().name != "JBIG2Decode")
                            continue

                        val filter = obj.decodedStream
                        val reader = FilterReader(filter)

                        val hint_set = ObjSet()
                        val hint = hint_set.createArray() // A hint to image encoder to use JBIG2 compression
                        hint.pushBackName("JBIG2")
                        hint.pushBackName("Lossless")

                        val new_image = Image.create(cos_doc, reader,
                            input_image.imageWidth,
                            input_image.imageHeight, 1, ColorSpace.createDeviceGray(), hint)

                        val new_img_obj = new_image.sdfObj
                        itr = obj.find("Decode")
                        if (itr.hasNext())
                            new_img_obj.put("Decode", itr.value())
                        itr = obj.find("ImageMask")
                        if (itr.hasNext())
                            new_img_obj.put("ImageMask", itr.value())
                        itr = obj.find("Mask")
                        if (itr.hasNext())
                            new_img_obj.put("Mask", itr.value())

                        cos_doc.swap(i.toLong(), new_img_obj.objNum)
                    }
                }

                pdf_doc.save(Utils.createExternalFile("US061222892_JBIG2.pdf", mFileList).absolutePath, SDFDoc.SaveMode.REMOVE_UNUSED, null)
            }
        } catch (e: Exception) {
            mOutputListener!!.printError(e.stackTrace)
        }

        for (file in mFileList) {
            addToFileList(file)
        }
        printFooter(outputListener)
    }

    companion object {

        private var mOutputListener: OutputListener? = null

        private val mFileList = ArrayList<String>()
    }

}
```

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