001/*
002 * $RCSfile: WBMPImageReader.java,v $
003 *
004 * 
005 * Copyright (c) 2005 Sun Microsystems, Inc. All  Rights Reserved.
006 * 
007 * Redistribution and use in source and binary forms, with or without
008 * modification, are permitted provided that the following conditions
009 * are met: 
010 * 
011 * - Redistribution of source code must retain the above copyright 
012 *   notice, this  list of conditions and the following disclaimer.
013 * 
014 * - Redistribution in binary form must reproduce the above copyright
015 *   notice, this list of conditions and the following disclaimer in 
016 *   the documentation and/or other materials provided with the
017 *   distribution.
018 * 
019 * Neither the name of Sun Microsystems, Inc. or the names of 
020 * contributors may be used to endorse or promote products derived 
021 * from this software without specific prior written permission.
022 * 
023 * This software is provided "AS IS," without a warranty of any 
024 * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND 
025 * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, 
026 * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
027 * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL 
028 * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF 
029 * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
030 * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR 
031 * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
032 * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
033 * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
034 * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
035 * POSSIBILITY OF SUCH DAMAGES. 
036 * 
037 * You acknowledge that this software is not designed or intended for 
038 * use in the design, construction, operation or maintenance of any 
039 * nuclear facility. 
040 *
041 * $Revision: 1.2 $
042 * $Date: 2006/04/21 00:02:26 $
043 * $State: Exp $
044 */
045package com.github.jaiimageio.impl.plugins.wbmp;
046
047import java.awt.Rectangle;
048import java.awt.image.BufferedImage;
049import java.awt.image.DataBufferByte;
050import java.awt.image.MultiPixelPackedSampleModel;
051import java.awt.image.Raster;
052import java.awt.image.WritableRaster;
053
054import javax.imageio.IIOException;
055import javax.imageio.ImageReader;
056import javax.imageio.ImageReadParam;
057import javax.imageio.ImageTypeSpecifier;
058import javax.imageio.metadata.IIOMetadata;
059import javax.imageio.spi.ImageReaderSpi;
060import javax.imageio.stream.ImageInputStream;
061
062import java.io.*;
063import java.util.ArrayList;
064import java.util.Iterator;
065
066import com.github.jaiimageio.impl.common.ImageUtil;
067
068/** This class is the Java Image IO plugin reader for WBMP images.
069 *  It may subsample the image, clip the image,
070 *  and shift the decoded image origin if the proper decoding parameter
071 *  are set in the provided <code>WBMPImageReadParam</code>.
072 */
073public class WBMPImageReader extends ImageReader {
074    /** The input stream where reads from */
075    private ImageInputStream iis = null;
076
077    /** Indicates whether the header is read. */
078    private boolean gotHeader = false;
079
080    /** The stream position where the image data starts. */
081    private long imageDataOffset;
082
083    /** The original image width. */
084    private int width;
085
086    /** The original image height. */
087    private int height;
088
089    private int wbmpType;
090
091    private WBMPMetadata metadata;
092
093    /** Constructs <code>WBMPImageReader</code> from the provided
094     *  <code>ImageReaderSpi</code>.
095     */
096    public WBMPImageReader(ImageReaderSpi originator) {
097        super(originator);
098    }
099
100    /** Overrides the method defined in the superclass. */
101    public void setInput(Object input,
102                         boolean seekForwardOnly,
103                         boolean ignoreMetadata) {
104        super.setInput(input, seekForwardOnly, ignoreMetadata);
105        iis = (ImageInputStream) input; // Always works
106        gotHeader = false;
107    }
108
109    /** Overrides the method defined in the superclass. */
110    public int getNumImages(boolean allowSearch) throws IOException {
111        if (iis == null) {
112            throw new IllegalStateException(I18N.getString("GetNumImages0"));
113        }
114        if (seekForwardOnly && allowSearch) {
115            throw new IllegalStateException(I18N.getString("GetNumImages1"));
116        }
117        return 1;
118    }
119
120    public int getWidth(int imageIndex) throws IOException {
121        checkIndex(imageIndex);
122        readHeader();
123        return width;
124    }
125
126    public int getHeight(int imageIndex) throws IOException {
127        checkIndex(imageIndex);
128        readHeader();
129        return height;
130    }
131
132    public boolean isRandomAccessEasy(int imageIndex) throws IOException {
133        checkIndex(imageIndex);
134        return true;
135    }
136
137    private void checkIndex(int imageIndex) {
138        if (imageIndex != 0) {
139            throw new IndexOutOfBoundsException(I18N.getString("WBMPImageReader0"));
140        }
141    }
142
143    public void readHeader() throws IOException {
144        if (gotHeader) {
145            // Seek to where the image data starts, since that is where
146            // the stream pointer should be after header is read
147            iis.seek(imageDataOffset);
148            return;
149        }
150
151        if (iis == null) {
152            throw new IllegalStateException(I18N.getString("WBMPImageReader1"));
153        }
154
155        metadata = new WBMPMetadata();
156        wbmpType = iis.readByte();   // TypeField
157        byte fixHeaderField = iis.readByte();
158
159        // check for valid wbmp image
160        if (fixHeaderField != 0
161            || !isValidWbmpType(wbmpType)) {
162            throw new IIOException(I18N.getString("WBMPImageReader2"));
163        }
164
165        metadata.wbmpType = wbmpType;
166
167        // Read image width
168        width = ImageUtil.readMultiByteInteger(iis);
169        metadata.width = width;
170
171        // Read image height
172        height = ImageUtil.readMultiByteInteger(iis);
173        metadata.height = height;
174
175        gotHeader = true;
176        // Store the stream position where the image data starts
177        imageDataOffset = iis.getStreamPosition();
178    }
179
180    public Iterator getImageTypes(int imageIndex)
181        throws IOException {
182        checkIndex(imageIndex);
183        readHeader();
184
185        BufferedImage bi =
186            new BufferedImage(1, 1, BufferedImage.TYPE_BYTE_BINARY);
187        ArrayList list = new ArrayList(1);
188        list.add(new ImageTypeSpecifier(bi));
189        return list.iterator();
190    }
191
192    public ImageReadParam getDefaultReadParam() {
193        return new ImageReadParam();
194    }
195
196    public IIOMetadata getImageMetadata(int imageIndex)
197        throws IOException {
198        checkIndex(imageIndex);
199        if (metadata == null) {
200            readHeader();
201        }
202        return metadata;
203    }
204
205    public IIOMetadata getStreamMetadata() throws IOException {
206        return null;
207    }
208
209    public BufferedImage read(int imageIndex, ImageReadParam param)
210        throws IOException {
211
212        if (iis == null) {
213            throw new IllegalStateException(I18N.getString("WBMPImageReader1"));
214        }
215
216        checkIndex(imageIndex);
217        clearAbortRequest();
218        processImageStarted(imageIndex);
219        if (param == null)
220            param = getDefaultReadParam();
221
222        //read header
223        readHeader();
224
225        Rectangle sourceRegion = new Rectangle(0, 0, 0, 0);
226        Rectangle destinationRegion = new Rectangle(0, 0, 0, 0);
227
228        computeRegions(param, this.width, this.height,
229                       param.getDestination(),
230                       sourceRegion,
231                       destinationRegion);
232
233        int scaleX = param.getSourceXSubsampling();
234        int scaleY = param.getSourceYSubsampling();
235        int xOffset = param.getSubsamplingXOffset();
236        int yOffset = param.getSubsamplingYOffset();
237
238        // If the destination is provided, then use it.  Otherwise, create new one
239        BufferedImage bi = param.getDestination();
240
241        if (bi == null)
242            bi = new BufferedImage(destinationRegion.x + destinationRegion.width,
243                              destinationRegion.y + destinationRegion.height,
244                              BufferedImage.TYPE_BYTE_BINARY);
245
246        boolean noTransform =
247            destinationRegion.equals(new Rectangle(0, 0, width, height)) &&
248            destinationRegion.equals(new Rectangle(0, 0, bi.getWidth(), bi.getHeight()));
249
250        // Get the image data.
251        WritableRaster tile = bi.getWritableTile(0, 0);
252
253        // Get the SampleModel.
254        MultiPixelPackedSampleModel sm =
255            (MultiPixelPackedSampleModel)bi.getSampleModel();
256
257        if (noTransform) {
258            if (abortRequested()) {
259                processReadAborted();
260                return bi;
261            }
262
263            // If noTransform is necessary, read the data.
264            iis.read(((DataBufferByte)tile.getDataBuffer()).getData(),
265                     0, height*sm.getScanlineStride());
266            processImageUpdate(bi,
267                               0, 0,
268                               width, height, 1, 1,
269                               new int[]{0});
270            processImageProgress(100.0F);
271        } else {
272            int len = (this.width + 7) / 8;
273            byte[] buf = new byte[len];
274            byte[] data = ((DataBufferByte)tile.getDataBuffer()).getData();
275            int lineStride = sm.getScanlineStride();
276            iis.skipBytes(len * sourceRegion.y);
277            int skipLength = len * (scaleY - 1);
278
279            // cache the values to avoid duplicated computation
280            int[] srcOff = new int[destinationRegion.width];
281            int[] destOff = new int[destinationRegion.width];
282            int[] srcPos = new int[destinationRegion.width];
283            int[] destPos = new int[destinationRegion.width];
284
285            for (int i = destinationRegion.x, x = sourceRegion.x, j = 0;
286                i < destinationRegion.x + destinationRegion.width;
287                    i++, j++, x += scaleX) {
288                srcPos[j] = x >> 3;
289                srcOff[j] = 7 - (x & 7);
290                destPos[j] = i >> 3;
291                destOff[j] = 7 - (i & 7);
292            }
293
294            for (int j = 0, y = sourceRegion.y,
295                k = destinationRegion.y * lineStride;
296                j < destinationRegion.height; j++, y+=scaleY) {
297
298                if (abortRequested())
299                    break;
300                iis.read(buf, 0, len);
301                for (int i = 0; i < destinationRegion.width; i++) {
302                    //get the bit and assign to the data buffer of the raster
303                    int v = (buf[srcPos[i]] >> srcOff[i]) & 1;
304                    data[k + destPos[i]] |= v << destOff[i];
305                }
306
307                k += lineStride;
308                iis.skipBytes(skipLength);
309                        processImageUpdate(bi,
310                                           0, j,
311                                           destinationRegion.width, 1, 1, 1,
312                                           new int[]{0});
313                        processImageProgress(100.0F*j/destinationRegion.height);
314            }
315        }
316
317        if (abortRequested())
318            processReadAborted();
319        else
320            processImageComplete();
321        return bi;
322    }
323
324    public boolean canReadRaster() {
325        return true;
326    }
327
328    public Raster readRaster(int imageIndex,
329                             ImageReadParam param) throws IOException {
330        BufferedImage bi = read(imageIndex, param);
331        return bi.getData();
332    }
333
334    public void reset() {
335        super.reset();
336        iis = null;
337        gotHeader = false;
338    }
339
340    /*
341     * This method verifies that given byte is valid wbmp type marker.
342     * At the moment only 0x0 marker is described by wbmp spec.
343     */
344    boolean isValidWbmpType(int type) {
345        return type == 0;
346    }
347}