use of com.tom_roush.harmony.javax.imageio.stream.ImageInputStream in project PdfBox-Android by TomRoush.
the class SampledImageReader method getStencilImage.
/**
* Returns an ARGB image filled with the given paint and using the given image as a mask.
* @param paint the paint to fill the visible portions of the image with
* @return a masked image filled with the given paint
* @throws IOException if the image cannot be read
* @throws IllegalStateException if the image is not a stencil.
*/
public static Bitmap getStencilImage(PDImage pdImage, Paint paint) throws IOException {
int width = pdImage.getWidth();
int height = pdImage.getHeight();
// compose to ARGB
Bitmap masked = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas g = new Canvas(masked);
// draw the mask
// g.drawImage(mask, 0, 0, null);
// fill with paint using src-in
// g.setComposite(AlphaComposite.SrcIn);
g.drawRect(0, 0, width, height, paint);
// set the alpha
// avoid getting a Bitmap for the mask to lessen memory footprint.
// Such masks are always bpc=1 and have no colorspace, but have a decode.
// (see 8.9.6.2 Stencil Masking)
ImageInputStream iis = null;
try {
iis = new MemoryCacheImageInputStream(pdImage.createInputStream());
final float[] decode = getDecodeArray(pdImage);
int value = decode[0] < decode[1] ? 1 : 0;
int rowLen = width / 8;
if (width % 8 > 0) {
rowLen++;
}
byte[] buff = new byte[rowLen];
for (int y = 0; y < height; y++) {
int x = 0;
int readLen = iis.read(buff);
for (int r = 0; r < rowLen && r < readLen; r++) {
int byteValue = buff[r];
int mask = 128;
int shift = 7;
for (int i = 0; i < 8; i++) {
int bit = (byteValue & mask) >> shift;
mask >>= 1;
--shift;
if (bit == value) {
masked.setPixel(x, y, Color.TRANSPARENT);
}
x++;
if (x == width) {
break;
}
}
}
if (readLen != rowLen) {
Log.w("PdfBox-Android", "premature EOF, image will be incomplete");
break;
}
}
} finally {
if (iis != null) {
iis.close();
}
}
return masked;
}
Aggregations