PDFBOX CMYK Support

I’m using PDFBOX to generate images from PDFs.
I’ve added a few modifications to PDJpeg so that PDFs with CMYK JPEGs are exported correctly.
Some images still have a wrong background (black).

@Override
public BufferedImage getRGBImage() throws IOException { // TODO PKOCH
File imgFile = null;
BufferedImage bi = null;
boolean readError = false;
try {
imgFile = File.createTempFile("pdjpeg", ".jpeg");
write2file(imgFile);
try {
bi = ImageIO.read(imgFile);
} catch (IIOException iioe) {
// try CMYK
try {
Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName("JPEG");
ImageReader reader = null;
while (readers.hasNext()) {
reader = readers.next();
if (reader.canReadRaster()) {
break;
}
}
// Stream the image file (the original CMYK image)
ImageInputStream input = ImageIO.createImageInputStream(imgFile);
reader.setInput(input);
try {
bi = reader.read(0);
} catch (Exception e) {
Raster raster = reader.readRaster(0, null);
// ...and hope thats a CMYK, take a CMYK-Profile,
// there exists lots of, look at:
// http://www.eci.org/eci/de/060_downloads.php
// if you don't know take: ISOcoated.icc ...
String cmykProfile = "c:\\temp\\ISOcoated_v2_eci.icc";
ICC_Profile p = ICC_Profile.getInstance(new FileInputStream(cmykProfile));
// ... and convert it to sRGB
bi = cmykRasterToSRGB(raster, p);
}
} catch (IIOException iioe2) {
// cannot read jpeg
readError = true;
} catch (Exception ignore) {
}
}

// 2. try to read jpeg again. some jpegs have some strange header
// containing
// “Adobe ” at some place. so just replace the header with a valid
// jpeg header.
// TODO : not sure if it works for all cases
if (bi == null && readError) {
byte[] newImage = replaceHeader(imgFile);

ByteArrayInputStream bai = new ByteArrayInputStream(newImage);

// persist file temporarely, because i was not able to manage
// to call the ImageIO.read(InputStream) successfully.
FileOutputStream o = new FileOutputStream(imgFile);
byte[] buffer = new byte[512];
int read;
while ((read = bai.read(buffer)) > 0) {
o.write(buffer, 0, read);
}

bai.close();
o.close();

bi = ImageIO.read(imgFile);
}
} finally {
if (imgFile != null) {
imgFile.delete();
}
}

// If there is a ‘soft mask’ image then we use that as a transparency
// mask.
PDXObjectImage smask = getSMaskImage();
if (smask != null) {
BufferedImage smaskBI = smask.getRGBImage();

COSArray decodeArray = smask.getDecode();
CompositeImage compositeImage = new CompositeImage(bi, smaskBI);
BufferedImage rgbImage = compositeImage.createMaskedImage(decodeArray);

return rgbImage;
} else {
// But if there is no soft mask, use the unaltered image.
return bi;
}
}