public void writeImage(BufferedImage img, TranscoderOutput output)
throws TranscoderException {
OutputStream ostream = output.getOutputStream();
if (ostream == null) {
throw new TranscoderException(
Messages.formatMessage("tiff.badoutput", null));
}
TIFFEncodeParam params = new TIFFEncodeParam();
float PixSzMM = userAgent.getPixelUnitToMillimeter();
// num Pixs in 100 Meters
int numPix = (int)(((1000*100)/PixSzMM)+0.5);
int denom = 100*100; // Centimeters per 100 Meters;
long [] rational = {numPix, denom};
TIFFField [] fields = {
new TIFFField(TIFFImageDecoder.TIFF_RESOLUTION_UNIT,
TIFFField.TIFF_SHORT, 1,
new char [] { (char)3 }),
new TIFFField(TIFFImageDecoder.TIFF_X_RESOLUTION,
TIFFField.TIFF_RATIONAL, 1,
new long [][] { rational }),
new TIFFField(TIFFImageDecoder.TIFF_Y_RESOLUTION,
TIFFField.TIFF_RATIONAL, 1,
new long [][] { rational })
};
params.setExtraFields(fields);
//
// This is a trick so that viewers which do not support the alpha
// channel will see a white background (and not a black one).
//
boolean forceTransparentWhite = false;
if (hints.containsKey(KEY_FORCE_TRANSPARENT_WHITE)) {
forceTransparentWhite =
((Boolean)hints.get
(KEY_FORCE_TRANSPARENT_WHITE)).booleanValue();
}
int w = img.getWidth();
int h = img.getHeight();
SinglePixelPackedSampleModel sppsm;
sppsm = (SinglePixelPackedSampleModel)img.getSampleModel();
if (forceTransparentWhite) {
//
// This is a trick so that viewers which do not support
// the alpha channel will see a white background (and not
// a black one).
//
DataBufferInt biDB=(DataBufferInt)img.getRaster().getDataBuffer();
int scanStride = sppsm.getScanlineStride();
int dbOffset = biDB.getOffset();
int pixels[] = biDB.getBankData()[0];
int p = dbOffset;
int adjust = scanStride - w;
int a=0, r=0, g=0, b=0, pel=0;
for(int i=0; i<h; i++){
for(int j=0; j<w; j++){
pel = pixels[p];
a = (pel >> 24) & 0xff;
r = (pel >> 16) & 0xff;
g = (pel >> 8 ) & 0xff;
b = pel & 0xff;
r = (255*(255 -a) + a*r)/255;
g = (255*(255 -a) + a*g)/255;
b = (255*(255 -a) + a*b)/255;
pixels[p++] =
(a<<24 & 0xff000000) |
(r<<16 & 0xff0000) |
(g<<8 & 0xff00) |
(b & 0xff);
}
p += adjust;
}
}
try {
TIFFImageEncoder tiffEncoder =
new TIFFImageEncoder(ostream, params);
int bands = sppsm.getNumBands();
int [] off = new int[bands];
for (int i=0; i<bands; i++)
off[i] = i;
SampleModel sm = new PixelInterleavedSampleModel
(DataBuffer.TYPE_BYTE, w, h, bands, w*bands, off);
RenderedImage rimg = new FormatRed(GraphicsUtil.wrap(img), sm);
tiffEncoder.encode(rimg);
} catch (IOException ex) {
throw new TranscoderException(ex);
}
}