/*
 * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved.
 *
 * The contents of this file are subject to the CCM Public
 * License (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the
 * License at http://www.redhat.com/licenses/ccmpl.html.
 *
 * Software distributed under the License is distributed on an
 * "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express
 * or implied. See the License for the specific language
 * governing rights and limitations under the License.
 *
 */
package com.arsdigita.mimetypes.image;

import java.awt.Dimension;
import java.io.DataInputStream;
import java.io.IOException;

/**
 * Implements the {@link ImageSizer} interface for BMP images
 *
 * @author <a href="mailto:sfreidin@arsdigita.com">Stanislav Freidin</a>
 * @version $Id: //core-platform/dev/src/com/arsdigita/mimetypes/image/BMPImageSizer.java#5 $
 */
public class BMPImageSizer extends ImageSizer {

    public static final String versionId = "$Id: //core-platform/dev/src/com/arsdigita/mimetypes/image/BMPImageSizer.java#5 $ by $Author: dennis $, $DateTime: 2004/04/07 16:07:11 $";

    private static final byte BMP_MARKER_1 = 0x42;
    private static final byte BMP_MARKER_2 = 0x4d;
    private static final int HEADER_SIZE = 54;

    protected BMPImageSizer() { super(); }

    /**
     * Read the input stream, determine the size of the image,
     * and return it.
     * WARNING ! Only works for BMP files whose width and height are
     * less than 32767 pixels.
     *
     * @param in The InputStream to read
     * @return The size of the image, or null on failure
     */
    public Dimension computeSize(DataInputStream in) throws IOException {
        byte[] data = new byte[HEADER_SIZE];

        if(in.read(data) < HEADER_SIZE) {
            return null;
        }

        if(BMP_MARKER_1 == data[0] && BMP_MARKER_2 == data[1]) {
            // We have to manually mask out bits since Java has no unsigned primitive
            short width = ImageSizer.toShort(data[19], data[18]);
            short height = ImageSizer.toShort(data[23], data[22]);
            return new Dimension(width, height);
        } else {
            return null;
        }

    }
}
