KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > openlaszlo > iv > flash > api > image > JPEGBitmap


1 /*
2  * $Id: JPEGBitmap.java,v 1.5 2002/02/25 19:07:04 ptalbot Exp $
3  *
4  * ==========================================================================
5  *
6  * The JGenerator Software License, Version 1.0
7  *
8  * Copyright (c) 2000 Dmitry Skavish (skavish@usa.net). All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions are met:
12  *
13  * 1. Redistributions of source code must retain the above copyright
14  * notice, this list of conditions and the following disclaimer.
15  *
16  * 2. Redistributions in binary form must reproduce the above copyright
17  * notice, this list of conditions and the following disclaimer in
18  * the documentation and/or other materials provided with the
19  * distribution.
20  *
21  * 3. The end-user documentation included with the redistribution, if
22  * any, must include the following acknowlegement:
23  * "This product includes software developed by Dmitry Skavish
24  * (skavish@usa.net, http://www.flashgap.com/)."
25  * Alternately, this acknowlegement may appear in the software itself,
26  * if and wherever such third-party acknowlegements normally appear.
27  *
28  * 4. The name "The JGenerator" must not be used to endorse or promote
29  * products derived from this software without prior written permission.
30  * For written permission, please contact skavish@usa.net.
31  *
32  * 5. Products derived from this software may not be called "The JGenerator"
33  * nor may "The JGenerator" appear in their names without prior written
34  * permission of Dmitry Skavish.
35  *
36  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
37  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
38  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
39  * DISCLAIMED. IN NO EVENT SHALL DMITRY SKAVISH OR THE OTHER
40  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
41  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
42  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
43  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
44  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
45  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
46  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
47  * SUCH DAMAGE.
48  *
49  */

50
51 package org.openlaszlo.iv.flash.api.image;
52
53 import java.io.*;
54 import java.awt.color.ColorSpace JavaDoc;
55 import java.awt.image.ColorConvertOp JavaDoc;
56 import java.awt.image.BufferedImage JavaDoc;
57 import java.awt.image.Raster JavaDoc;
58 import java.awt.geom.*;
59 import org.openlaszlo.iv.flash.url.*;
60 import org.openlaszlo.iv.flash.util.*;
61 import org.openlaszlo.iv.flash.parser.*;
62 import org.openlaszlo.iv.flash.api.*;
63
64 import com.sun.image.codec.jpeg.*;
65
66 public class JPEGBitmap extends Bitmap {
67
68     private static final String JavaDoc jpegTablesName = "%JPEGTABLES$JPEGTABLES%";
69     private DataMarker data;
70     private FlashItem jpegTables;
71     private Rectangle2D bounds;
72     private JPEGInfo info;
73
74     /** true - ready to be generated, false - not ready, has to be converted */
75     private boolean readyToGen;
76
77     public JPEGBitmap() {}
78
79     public void setData( DataMarker data ) {
80         this.data = data;
81         this.bounds = null;
82         this.readyToGen = false;
83     }
84
85     public static Bitmap parse( Parser p ) {
86         JPEGBitmap o = new JPEGBitmap();
87         o.setID( p.getUWord() );
88         o.data = new DataMarker( p.getBuf(), p.getPos(), p.getTagEndPos() );
89         o.readyToGen = true;
90         o.tagCode = p.getTagCode();
91         if( o.tagCode == Tag.DEFINEBITS ) {
92             o.jpegTables = p.getDefFromLibrary(jpegTablesName);
93         }
94         return o;
95     }
96
97     public static void parseJPegTables( Parser p ) {
98         JPEGTables tables = new JPEGTables();
99         tables.setData( new DataMarker( p.getBuf(), p.getPos(), p.getTagEndPos() ) ); // 02/09/01 by sd
100
tables.setName( jpegTablesName );
101         p.addDefToLibrary( jpegTablesName, tables );
102     }
103
104     public int getSize() {
105         return data.buffer.length;
106     }
107
108     public Rectangle2D getBounds() {
109         if( bounds != null ) return bounds;
110         parseData();
111         return bounds;
112     }
113
114     public void collectDeps( DepsCollector dc ) {
115
116         /* LASZLO we never output JPEGTABLES tags
117         if( jpegTables != null ) {
118             dc.addDep(jpegTables);
119         }
120         */

121     }
122
123     public static JPEGBitmap newJPEGBitmap( String JavaDoc fileName )
124         throws IVException, IOException
125     {
126         return newJPEGBitmap( IVUrl.newUrl(fileName));
127     }
128
129     public static JPEGBitmap newJPEGBitmap( IVUrl url )
130         throws IVException, IOException
131     {
132         return newJPEGBitmap( Util.readUrl(url) );
133     }
134
135     public static JPEGBitmap newJPEGBitmap( FlashBuffer fob ) throws IVException {
136         JPEGBitmap bitmap = new JPEGBitmap();
137         bitmap.setTag( Tag.DEFINEBITSJPEG2 );
138         DataMarker data = new DataMarker(fob.getBuf(), 0, fob.getSize());
139         bitmap.setData(data);
140         //bitmap.parseData();
141
return bitmap;
142     }
143
144     private void parseData() {
145         info = JPEGHelper.getInfo(data.buffer, data.start, data.end);
146         bounds = GeomHelper.newRectangle(0,0,info.width,info.height);
147
148         // check if it's not progressive jpeg or gray
149
if( info.type == 0 && info.num_comps == 3 ) {
150             readyToGen = true;
151         } else {
152             readyToGen = false;
153         }
154     }
155
156     /**
157      * Reencode the image with specified quality
158      * <P>
159      * As a side effect this method converts from progressive jpeg
160      * (if any) to regular
161      *
162      * @param quality quality of new jpeg: 0..1, with 1 being highest quality
163      */

164     public void processImage( float quality ) {
165         try {
166             Log.logRB( Resource.REENCODINGJPEG, new Object JavaDoc[] {new Float JavaDoc(quality)} );
167             int size = data.end-data.start;
168             InputStream is = data.getInputStream();
169             JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder( is );
170             BufferedImage JavaDoc image = decoder.decodeAsBufferedImage();
171
172             info = JPEGHelper.getInfo(data.buffer, data.start, data.end);
173             // Need to color convert from greyscale to RGB
174
if (info.num_comps != 3) {
175                 ColorConvertOp JavaDoc op = new ColorConvertOp JavaDoc(image.getColorModel().getColorSpace(),
176                     ColorSpace.getInstance(ColorSpace.CS_LINEAR_RGB), null);
177                 image = op.filter(image, null);
178             }
179
180             bounds = GeomHelper.newRectangle(0,0,image.getWidth(),image.getHeight());
181
182             FlashBuffer fob = new FlashBuffer(size);
183             OutputStream os = fob.getOutputStream();
184
185             JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os);
186             JPEGEncodeParam params = encoder.getDefaultJPEGEncodeParam(image);
187             params.setQuality(quality,true);
188             encoder.encode(image,params);
189
190             data.buffer = fob.getBuf();
191             data.end = fob.getSize();
192             data.start = 0;
193             readyToGen = true;
194         } catch( IOException e ) {
195             Log.log( e );
196         }
197     }
198
199     /**
200      * Rescales this image with specified width, height and quality
201      *
202      * @param width new width
203      * @param height new height
204      * @param quality new quality
205      */

206     public void rescale( int width, int height, float quality ) {
207         try {
208             Log.logRB(Resource.RESCALINGJPEG,
209                 new Object JavaDoc[] {new Integer JavaDoc(width), new Integer JavaDoc(height), new Float JavaDoc(quality)});
210             int size = data.end-data.start;
211             InputStream is = data.getInputStream();
212             JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(is);
213             BufferedImage JavaDoc image = decoder.decodeAsBufferedImage();
214             image = (BufferedImage JavaDoc) image.getScaledInstance(width, height, java.awt.Image.SCALE_SMOOTH);
215
216             bounds = GeomHelper.newRectangle(0,0,image.getWidth(),image.getHeight());
217
218             FlashBuffer fob = new FlashBuffer(size);
219             OutputStream os = fob.getOutputStream();
220
221             JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os);
222             JPEGEncodeParam params = encoder.getDefaultJPEGEncodeParam(image);
223             params.setQuality(quality,true);
224             encoder.encode(image,params);
225
226             data.buffer = fob.getBuf();
227             data.end = fob.getSize();
228             data.start = 0;
229             readyToGen = true;
230         } catch( IOException e ) {
231             Log.log( e );
232         }
233     }
234
235 /* private GraphicsConfiguration gr_config = null;
236     private static GraphicsConfiguration getGraphicsConfiguration() {
237         if( gr_config == null ) {
238             GraphicsEnvironment gr_env = GraphicsEnvironment.getLocalGraphicsEnvironment();
239             GraphicsDevice gr_device = gr_env.getDefaultScreenDevice();
240             gr_config = gr_device.getDefaultConfiguration();
241         }
242         return gr_config;
243     }
244 */

245     public void write( FlashOutput fob ) {
246         if( !readyToGen ) {
247             processImage(.75f);
248         }
249         // LASZLO, turn DEFINEBITS into DEFINTEBITSJPEG2
250
if (tagCode == Tag.DEFINEBITS) {
251             JPEGTables tables = (JPEGTables) jpegTables;
252             fob.writeTag(Tag.DEFINEBITSJPEG2, 2 + data.length() + tables.getDataLength());
253             fob.writeDefID( this );
254             tables.writeData(fob);
255         } else {
256             fob.writeTag(tagCode, 2+data.length());
257             fob.writeDefID( this );
258         }
259         data.write(fob);
260     }
261
262     public void printContent( PrintStream out, String JavaDoc indent ) {
263         out.println( indent+"JPEGBitmap("+Tag.tagNames[tagCode]+"): id="+getID()+" size="+data.length()+" name='"+getName()+"'" );
264     }
265
266     protected FlashItem copyInto( FlashItem item, ScriptCopier copier ) {
267         super.copyInto( item, copier );
268         ((JPEGBitmap)item).data = (DataMarker) data.getCopy();
269         ((JPEGBitmap)item).jpegTables = jpegTables;
270         ((JPEGBitmap)item).bounds = (Rectangle2D) bounds.clone();
271         ((JPEGBitmap)item).readyToGen = readyToGen;
272         ((JPEGBitmap)item).info = info!=null?info.getCopy():null;
273         return item;
274     }
275
276     public FlashItem getCopy( ScriptCopier copier ) {
277         return copyInto( new JPEGBitmap(), copier );
278     }
279
280     public static class JPEGInfo {
281         public int type; // 0 - regular, 1 - progressive
282
public int width;
283         public int height;
284         public int num_comps;
285         public int precision;
286         public JPEGInfo getCopy() {
287             JPEGInfo info = new JPEGInfo();
288             info.type = type;
289             info.width = width;
290             info.height = height;
291             info.num_comps = num_comps;
292             info.precision = precision;
293             return info;
294         }
295     }
296
297     private static class JPEGTables extends FlashDef {
298         DataMarker data;
299         public JPEGTables() {}
300         public int getTag() { return Tag.JPEGTABLES; }
301         public void setData( DataMarker data ) { this.data = data; }
302         public void write( FlashOutput fob ) {
303             fob.writeTag(Tag.JPEGTABLES, data.length());
304             data.write(fob);
305         }
306
307         public void writeData( FlashOutput fob ) {
308             data.write(fob);
309         }
310         public int getDataLength( ) {
311             return data.length();
312         }
313     }
314
315 }
316
317
Popular Tags