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

# ImageExtract

Here is a sample showcasing how to extract image from pdf using Java or Kotlin. Run the sample with Apryse Android SDK free trial.

Sample Java, Kotlin code for using Apryse Android 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](/android/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 started with Android SDK](/android/get-started/get-started.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.common.Matrix2D;
import com.pdftron.common.PDFNetException;
import com.pdftron.pdf.Element;
import com.pdftron.pdf.ElementReader;
import com.pdftron.pdf.Image;
import com.pdftron.pdf.PDFDoc;
import com.pdftron.pdf.PageIterator;
import com.pdftron.sdf.DictIterator;
import com.pdftron.sdf.Obj;
import com.pdftron.sdf.SDFDoc;

import java.util.ArrayList;

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

public class ImageExtractTest extends PDFNetSample {

	private static OutputListener mOutputListener;

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

    public ImageExtractTest() {
        setTitle(R.string.sample_imageextract_title);
        setDescription(R.string.sample_imageextract_description);

        // The standard library does not support exporting to
        // PNG/TIFF formats, thus trying to export the PDF to
        // PNG or TIFF will fail. Please, comment out this call
        // if using the full library.
        // DisableRun();
    }

	@Override
	public void run(OutputListener outputListener) {
		super.run(outputListener);
		mOutputListener = outputListener;
		mFileList.clear();
		printHeader(outputListener);
        // 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.
        try (PDFDoc doc = new PDFDoc((Utils.getAssetTempFile(INPUT_PATH + "newsletter.pdf").getAbsolutePath()))) {
            doc.initSecurityHandler();
            ElementReader reader = new ElementReader();
            //  Read every page
            for (PageIterator itr = doc.getPageIterator(); itr.hasNext(); ) {
                reader.begin(itr.next());
                ImageExtract(reader);
                reader.end();
            }
            mOutputListener.println("Done.");
        } catch (Exception e) {
            mOutputListener.printError(e.getStackTrace());
        }

        mOutputListener.println("----------------------------------------------------------------");

        // Example 2:
        // Extract images by scanning the low-level document.
        try (PDFDoc doc = new PDFDoc((Utils.getAssetTempFile(INPUT_PATH + "newsletter.pdf").getAbsolutePath()))) {
            doc.initSecurityHandler();
            image_counter = 0;
            SDFDoc cos_doc = doc.getSDFDoc();
            long num_objs = 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("Type");
                    if (!itr.hasNext() || !itr.value().getName().equals("XObject"))
                        continue;

                    itr = obj.find("Subtype");
                    if (!itr.hasNext() || !itr.value().getName().equals("Image"))
                        continue;

                    Image image = new Image(obj);

                    mOutputListener.println("--> Image: " + (++image_counter));
                    mOutputListener.println("    Width: " + image.getImageWidth());
                    mOutputListener.println("    Height: " + image.getImageHeight());
                    mOutputListener.println("    BPC: " + image.getBitsPerComponent());

                    String fname = "image_extract2_" + image_counter;
                    String path = Utils.createExternalFile(fname, mFileList).getAbsolutePath();
                    image.export(path);

                    //String path= Utils.createExternalFile(fname + ".tif", mFileList).getAbsolutePath();
                    //image.exportAsTiff(path);

                    //String path = Utils.createExternalFile(fname + ".png", mFileList).getAbsolutePath();
                    //image.exportAsPng(path);
                }
            }
            
            mOutputListener.println("Done.");
        } catch (Exception e) {
            mOutputListener.printError(e.getStackTrace());
        }

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

    // Relative paths to folders containing test files.

    static int image_counter = 0;

    static void ImageExtract(ElementReader reader) throws PDFNetException {
        Element element;
        while ((element = reader.next()) != null) {
            switch (element.getType()) {
                case Element.e_image:
                case Element.e_inline_image: {
                    mOutputListener.println("--> Image: " + (++image_counter));
                    mOutputListener.println("    Width: " + element.getImageWidth());
                    mOutputListener.println("    Height: " + element.getImageHeight());
                    mOutputListener.println("    BPC: " + element.getBitsPerComponent());

                    Matrix2D ctm = element.getCTM();
                    double x2 = 1, y2 = 1;
                    com.pdftron.pdf.Point p = ctm.multPoint(x2, y2);
                    mOutputListener.println(String.format("    Coords: x1=%.2f, y1=%.2f, x2=%.2f, y2=%.2f", ctm.getH(), ctm.getV(), p.x, p.y));

                    if (element.getType() == Element.e_image) {
                        Image image = new Image(element.getXObject());

                        String fname = "image_extract1_" + image_counter;

                        String path = Utils.createExternalFile(fname, mFileList).getAbsolutePath();
                        image.export(path);

                        //String path2 = Utils.createExternalFile(fname + ".tif", mFileList).getAbsolutePath();
                        //image.exportAsTiff(path2);

                        //String path3 = Utils.createExternalFile(fname + ".png", mFileList).getAbsolutePath();
                        //image.exportAsPng(path3);
                    }
                }
                break;
                case Element.e_form:        // Process form XObjects
                    reader.formBegin();
                    ImageExtract(reader);
                    reader.end();
                    break;
            }
        }
    }

}
```

{% 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.common.PDFNetException
import com.pdftron.pdf.Element
import com.pdftron.pdf.ElementReader
import com.pdftron.pdf.Image
import com.pdftron.pdf.PDFDoc
import java.util.*

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

class ImageExtractTest : PDFNetSample() {
    init {
        setTitle(R.string.sample_imageextract_title)
        setDescription(R.string.sample_imageextract_description)

        // The standard library does not support exporting to
        // PNG/TIFF formats, thus trying to export the PDF to
        // PNG or TIFF will fail. Please, comment out this call
        // if using the full library.
        // DisableRun();
    }

    override fun run(outputListener: OutputListener?) {
        super.run(outputListener)
        mOutputListener = outputListener
        mFileList.clear()
        printHeader(outputListener!!)
        // 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.
        // 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.
        try {
            PDFDoc(Utils.getAssetTempFile(INPUT_PATH + "newsletter.pdf")!!.absolutePath).use { doc ->
                doc.initSecurityHandler()
                val reader = ElementReader()
                //  Read every page
                val itr = doc.pageIterator
                while (itr.hasNext()) {
                    reader.begin(itr.next())
                    ImageExtract(reader)
                    reader.end()
                }
                mOutputListener!!.println("Done.")
            }
        } catch (e: Exception) {
            mOutputListener!!.printError(e.stackTrace)
        }

        mOutputListener!!.println("----------------------------------------------------------------")

        // Example 2:
        // Extract images by scanning the low-level document.

        // Example 2:
        // Extract images by scanning the low-level document.
        try {
            PDFDoc(Utils.getAssetTempFile(INPUT_PATH + "newsletter.pdf")!!.absolutePath).use { doc ->
                doc.initSecurityHandler()
                image_counter = 0
                val cos_doc = doc.sdfDoc
                val num_objs = cos_doc.xRefSize()
                for (i in 1 until num_objs) {
                    val obj = cos_doc.getObj(i)
                    if (obj != null && !obj.isFree && obj.isStream) {
                        // Process only images
                        var itr = obj.find("Type")
                        if (!itr.hasNext() || itr.value().name != "XObject") continue
                        itr = obj.find("Subtype")
                        if (!itr.hasNext() || itr.value().name != "Image") continue
                        val image = Image(obj)
                        mOutputListener!!.println("--> Image: " + ++image_counter)
                        mOutputListener!!.println("    Width: " + image.imageWidth)
                        mOutputListener!!.println("    Height: " + image.imageHeight)
                        mOutputListener!!.println("    BPC: " + image.bitsPerComponent)
                        val fname = "image_extract2_$image_counter"
                        val path = Utils.createExternalFile(fname, mFileList).absolutePath
                        image.export(path)

                        //String path= Utils.createExternalFile(fname + ".tif", mFileList).getAbsolutePath();
                        //image.exportAsTiff(path);

                        //String path = Utils.createExternalFile(fname + ".png", mFileList).getAbsolutePath();
                        //image.exportAsPng(path);
                    }
                }
                mOutputListener!!.println("Done.")
            }
        } 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>()

        // Relative paths to folders containing test files.

        internal var image_counter = 0

        @Throws(PDFNetException::class)
        fun ImageExtract(reader: ElementReader) {
            var element: Element
            while (reader.next().also { element = it } != null) {
                when (element.type) {
                    Element.e_image, Element.e_inline_image -> {
                        mOutputListener!!.println("--> Image: " + ++image_counter)
                        mOutputListener!!.println("    Width: " + element.imageWidth)
                        mOutputListener!!.println("    Height: " + element.imageHeight)
                        mOutputListener!!.println("    BPC: " + element.bitsPerComponent)
                        val ctm = element.ctm
                        val x2 = 1.0
                        val y2 = 1.0
                        val p = ctm.multPoint(x2, y2)
                        mOutputListener!!.println(String.format("    Coords: x1=%.2f, y1=%.2f, x2=%.2f, y2=%.2f", ctm.h, ctm.v, p.x, p.y))
                        if (element.type == Element.e_image) {
                            val image = Image(element.xObject)
                            val fname = "image_extract1_$image_counter"
                            val path = Utils.createExternalFile(fname, mFileList).absolutePath
                            image.export(path)

                            //String path2 = Utils.createExternalFile(fname + ".tif", mFileList).getAbsolutePath();
                            //image.exportAsTiff(path2);

                            //String path3 = Utils.createExternalFile(fname + ".png", mFileList).getAbsolutePath();
                            //image.exportAsPng(path3);
                        }
                    }
                    Element.e_form -> {
                        reader.formBegin()
                        ImageExtract(reader)
                        reader.end()
                    }
                }
            }
        }
    }

}
```

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