package org.apache.xmlgraphics.image.loader.impl;
import java.io.IOException;
import java.nio.ByteOrder;
import javax.imageio.stream.ImageInputStream;
import javax.xml.transform.Source;
import org.apache.xmlgraphics.image.loader.ImageContext;
import org.apache.xmlgraphics.image.loader.ImageException;
import org.apache.xmlgraphics.image.loader.ImageInfo;
import org.apache.xmlgraphics.image.loader.ImageSize;
import org.apache.xmlgraphics.image.loader.util.ImageUtil;
import org.apache.xmlgraphics.util.UnitConv;
public class PreloaderBMP extends AbstractImagePreloader {
protected static final int BMP_SIG_LENGTH = 2;
private static final int WIDTH_OFFSET = 18;
public ImageInfo preloadImage(String uri, Source src, ImageContext context)
throws IOException, ImageException {
if (!ImageUtil.hasImageInputStream(src)) {
return null;
}
ImageInputStream in = ImageUtil.needImageInputStream(src);
byte[] header = getHeader(in, BMP_SIG_LENGTH);
boolean supported = ((header[0] == (byte) 0x42)
&& (header[1] == (byte) 0x4d));
if (supported) {
ImageInfo info = new ImageInfo(uri, "image/bmp");
info.setSize(determineSize(in, context));
return info;
} else {
return null;
}
}
private ImageSize determineSize(ImageInputStream in, ImageContext context)
throws IOException, ImageException {
in.mark();
ByteOrder oldByteOrder = in.getByteOrder();
try {
ImageSize size = new ImageSize();
in.setByteOrder(ByteOrder.LITTLE_ENDIAN);
in.skipBytes(WIDTH_OFFSET);
int width = in.readInt();
int height = in.readInt();
size.setSizeInPixels(width, height);
in.skipBytes(12);
int xRes = in.readInt();
double xResDPI = UnitConv.in2mm(xRes / 1000d);
if (xResDPI == 0) {
xResDPI = context.getSourceResolution();
}
int yRes = in.readInt();
double yResDPI = UnitConv.in2mm(yRes / 1000d);
if (yResDPI == 0) {
yResDPI = context.getSourceResolution();
}
size.setResolution(xResDPI, yResDPI);
size.calcSizeFromPixels();
return size;
} finally {
in.setByteOrder(oldByteOrder);
in.reset();
}
}
}