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 PreloaderEMF extends AbstractImagePreloader {
protected static final int EMF_SIG_LENGTH = 88;
private static final int SIGNATURE_OFFSET = 40;
private static final int WIDTH_OFFSET = 32;
private static final int HEIGHT_OFFSET = 36;
private static final int HRES_PIXEL_OFFSET = 72;
private static final int VRES_PIXEL_OFFSET = 76;
private static final int HRES_MM_OFFSET = 80;
private static final int VRES_MM_OFFSET = 84;
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, EMF_SIG_LENGTH);
boolean supported
= ((header[SIGNATURE_OFFSET + 0] == (byte) 0x20)
&& (header[SIGNATURE_OFFSET + 1] == (byte) 0x45)
&& (header[SIGNATURE_OFFSET + 2] == (byte) 0x4D)
&& (header[SIGNATURE_OFFSET + 3] == (byte) 0x46));
if (supported) {
ImageInfo info = new ImageInfo(uri, "image/emf");
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 = (int)in.readUnsignedInt();
int height = (int)in.readUnsignedInt();
in.skipBytes(HRES_PIXEL_OFFSET - WIDTH_OFFSET - 8);
long hresPixel = in.readUnsignedInt();
long vresPixel = in.readUnsignedInt();
long hresMM = in.readUnsignedInt();
long vresMM = in.readUnsignedInt();
double resHorz = hresPixel / UnitConv.mm2in(hresMM);
double resVert = vresPixel / UnitConv.mm2in(vresMM);
size.setResolution(resHorz, resVert);
width = (int)Math.round(UnitConv.mm2mpt(width / 100f));
height = (int)Math.round(UnitConv.mm2mpt(height / 100f));
size.setSizeInMillipoints(width, height);
size.calcPixelsFromSize();
return size;
} finally {
in.setByteOrder(oldByteOrder);
in.reset();
}
}
}