How do I detect and extract RAW JBIG2 streams from PDF?

Q:
How do I detect and extract RAW JBIG2 streams from PDF?
-------
A:

Third party JBIG2 images can be extracted as follows:

// using C++
AutoPtr<Filters::Filter> flt(image.GetSDFObj()->GetRawStream());
Filters::FilterReader flt_rd(*flt);
ULong bytes_read;
UChar tmp_buf[1024];
while (bytes_read = flt_rd.Read(tmp_buf, 1024)) {
  fwrite(tmp_buf, 1, bytes_read, file);
}

This will save the embedded JBIG stream in an external file.

JBIG2 images created using PDFNet as well as images utilising other
compression methods can be extracted using image.Export(...).

You can identify if the image is JBIG2 as follows:

bool IsJBIG2(Image& img)
{
  SDF::Obj* im = img.GetSDFObj();
  DictIterator itr = im->Find("Filter");
  if (itr != im->DictEnd()) {
    Obj* val = itr->second;
    if (val->IsName() && strcmp(val->GetName(), "JBIG2Decode")==0) {
      return true;
    }
  }
  return false;
}