jai-imageio-core-1.2/ 0000775 0001751 0001751 00000000000 11650556211 013467 5 ustar tille tille jai-imageio-core-1.2/LICENSE-codecLibJIIO.txt 0000664 0001751 0001751 00000034472 10203036165 017473 0 ustar tille tille Sun Microsystems, Inc. Binary Code License Agreement CODECLIB FOR JAI-IMAGE I/O READ THE TERMS OF THIS AGREEMENT AND ANY PROVIDED SUPPLEMENTAL LICENSE TERMS (COLLECTIVELY "AGREEMENT") CAREFULLY BEFORE OPENING THE SOFTWARE MEDIA PACKAGE. BY OPENING THE SOFTWARE MEDIA PACKAGE, YOU AGREE TO THE TERMS OF THIS AGREEMENT. IF YOU ARE ACCESSING THE SOFTWARE ELECTRONICALLY, INDICATE YOUR ACCEPTANCE OF THESE TERMS BY SELECTING THE "ACCEPT" BUTTON AT THE END OF THIS AGREEMENT. IF YOU DO NOT AGREE TO ALL THESE TERMS, PROMPTLY RETURN THE UNUSED SOFTWARE TO YOUR PLACE OF PURCHASE FOR A REFUND OR, IF THE SOFTWARE IS ACCESSED ELECTRONICALLY, SELECT THE "DECLINE" BUTTON AT THE END OF THIS AGREEMENT. 1. LICENSE TO USE. Sun grants you a non-exclusive and non-transferable license for the internal use only of the accompanying software and documentation and any error corrections provided by Sun (collectively "Software"), by the number of users and the class of computer hardware for which the corresponding fee has been paid. 2. RESTRICTIONS. Software is confidential and copyrighted. Title to Software and all associated intellectual property rights is retained by Sun and/or its licensors. Except as specifically authorized in any Supplemental License Terms, you may not make copies of Software, other than a single copy of Software for archival purposes. Unless enforcement is prohibited by applicable law, you may not modify, decompile, or reverse engineer Software. You acknowledge that Software is not designed, licensed or intended for use in the design, construction, operation or maintenance of any nuclear facility. Sun disclaims any express or implied warranty of fitness for such uses. No right, title or interest in or to any trademark, service mark, logo or trade name of Sun or its licensors is granted under this Agreement. 3. LIMITED WARRANTY. Sun warrants to you that for a period of ninety (90) days from the date of purchase, as evidenced by a copy of the receipt, the media on which Software is furnished (if any) will be free of defects in materials and workmanship under normal use. Except for the foregoing, Software is provided "AS IS". Your exclusive remedy and Sun's entire liability under this limited warranty will be at Sun's option to replace Software media or refund the fee paid for Software. 4. DISCLAIMER OF WARRANTY. UNLESS SPECIFIED IN THIS AGREEMENT, ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT ARE DISCLAIMED, EXCEPT TO THE EXTENT THAT THESE DISCLAIMERS ARE HELD TO BE LEGALLY INVALID. 5. LIMITATION OF LIABILITY. TO THE EXTENT NOT PROHIBITED BY LAW, IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR SPECIAL, INDIRECT, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF OR RELATED TO THE USE OF OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. In no event will Sun's liability to you, whether in contract, tort (including negligence), or otherwise, exceed the amount paid by you for Software under this Agreement. The foregoing limitations will apply even if the above stated warranty fails of its essential purpose. 6. Termination. This Agreement is effective until terminated. You may terminate this Agreement at any time by destroying all copies of Software. This Agreement will terminate immediately without notice from Sun if you fail to comply with any provision of this Agreement. Upon Termination, you must destroy all copies of Software. 7. Export Regulations. All Software and technical data delivered under this Agreement are subject to US export control laws and may be subject to export or import regulations in other countries. You agree to comply strictly with all such laws and regulations and acknowledge that you have the responsibility to obtain such licenses to export, re-export, or import as may be required after delivery to you. 8. U.S. Government Restricted Rights. If Software is being acquired by or on behalf of the U.S. Government or by a U.S. Government prime contractor or subcontractor (at any tier), then the Government's rights in Software and accompanying documentation will be only as set forth in this Agreement; this is in accordance with 48 CFR 227.7201 through 227.7202-4 (for Department of Defense (DOD) acquisitions) and with 48 CFR 2.101 and 12.212 (for non-DOD acquisitions). 9. Governing Law. Any action related to this Agreement will be governed by California law and controlling U.S. federal law. No choice of law rules of any jurisdiction will apply. 10. Severability. If any provision of this Agreement is held to be unenforceable, this Agreement will remain in effect with the provision omitted, unless omission would frustrate the intent of the parties, in which case this Agreement will immediately terminate. 11. Integration. This Agreement is the entire agreement between you and Sun relating to its subject matter. It supersedes all prior or contemporaneous oral or written communications, proposals, representations and warranties and prevails over any conflicting or additional terms of any quote, order, acknowledgment, or other communication between the parties relating to its subject matter during the term of this Agreement. No modification of this Agreement will be binding, unless in writing and signed by an authorized representative of each party. Supplemental provisions for CODECLIB for JAI-IMAGE I/O 1. COPYRIGHT NOTICE AND ACKNOWLEDGMENT. COPYRIGHT 2002 SUN MICROSYSTEM, INC. ALL RIGHTS RESERVED. The following copyrights apply to specific Software provided under his license. JPEG2000 IMPLEMENTATION IN C This Software is based on the JPEG2000 CODEC Software, licensed under the IMAGE POWER JPEG-2000 PUBLIC LICENSE, Copyright (c) 1999-2000, Image Power, Inc. and the University of British Columbia, Canada; Copyright (c) 2001-2002 Michael David Adams. All rights reserved. JPEG2000 IMPLEMENTATION IN JAVA Copyright (c) 1999/2000 JJ2000 Partners. This software module was originally developed by Raphaël Grosbois and Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research Centre France S.A) in the course of development of the JPEG2000 standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This software module is an implementation of a part of the JPEG 2000 Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio Systems AB and Canon Research Centre France S.A (collectively JJ2000 Partners) agree not to assert against ISO/IEC and users of the JPEG 2000 Standard (Users) any of their rights under the copyright, not including other intellectual property rights, for this software module with respect to the usage by ISO/IEC and Users of this software module or modifications thereof for use in hardware or software products claiming conformance to the JPEG 2000 Standard. Those intending to use this software module in hardware or software products are advised that their use may infringe existing patents. The original developers of this software module, JJ2000 Partners and ISO/IEC assume no liability for use of this software module or modifications thereof. No license or right to this software module is granted for non JPEG 2000 Standard conforming products. JJ2000 Partners have full right to use this software module for his/her own purpose, assign or donate this software module to any third party and to inhibit third parties from using this software module for non JPEG 2000 Standard conforming products. This copyright notice must be included in all copies or derivative works of this software module. 2. LICENSE TO USE. Permission is hereby granted, free of charge, to any person (the "User") obtaining a copy of this JCODECLIB FOR JAI-IMAGE I/O Software, the Java Advanced Imaging and the JAI Image I/O Open Source Project, and associated documentation ("Software"), to deal in the Software without restriction, including without limitation the right to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software (in source and binary forms), and to permit persons to whom the Software is furnished to do so, provided further that the License Conditions below are met and that the Software is bundled with the implementation of the Java Advanced Imaging and the JAI Image I/O Open Source Project. A. Redistribution of source code must retain the above copyright notices, and this list of conditions, and the following Warranty Disclaimer and Limitation of Liability. B. Redistribution in binary form must reproduce the above copyright notices, and this list of conditions, and the following Warranty Disclaimer and Limitation of Liability in the documentation and/or other materials provided with the distribution. C. Neither the name of Sun Microsystems, Inc., Image Power, Inc. nor any other contributor (including, but not limited to, the University of British Columbia and Michael David Adams) may be used to endorse or promote products derived from this software without specific prior written permission. D. User agrees that it shall not commence any action against Sun Microsystems, Inc., Image Power, Inc., the University of British Columbia, Michael David Adams, or any other contributors (collectively "Licensors") for infringement of any intellectual property rights ("IPR") held by the User in respect of any technology that User owns or has a right to license or sublicense and which is an element required in order to claim compliance with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). "IPR" means all intellectual property rights worldwide arising under statutory or common law, and whether or not perfected, including, without limitation, all (i) patents and patent applications owned or licensable by User; (ii) rights associated with works of authorship including copyrights, copyright applications, copyright registrations, mask work rights, mask work applications, mask work registrations; (iii) rights relating to the protection of trade secrets and confidential information; (iv) any right analogous to those set forth in subsections (i), (ii), or (iii) and any other proprietary rights relating to intangible property (other than trademark, trade dress, or service mark rights); and (v) divisions, continuations, renewals, reissues and extensions of the foregoing (as and to the extent applicable) now existing, hereafter filed, issued or acquired. E. If User commences an infringement action against any Licensor(s) then such Licensor(s) shall have the right to terminate User's license and all sublicenses that have been granted hereunder by User to other parties. F. This software is for use only in hardware or software products that are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1). No license or right to this Software is granted for products that do not comply with ISO/IEC 15444-1. The JPEG-2000 Part 1 standard can be purchased from the ISO. 3. DISCLAIMER OF WARRANTY. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. NO USE OF THE JPEG2000 CODEC SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS DISCLAIMER. THE JPEG2000 CODEC SOFTWARE IS PROVIDED BY THE LICENSORS AND CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES THAT THE JPEG2000 CODEC SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE, IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING. THOSE INTENDING TO USE THE JPEG2000 CODEC SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JPEG2000 CODEC SOFTWARE IS WITH THE USER. SHOULD ANY PART OF THE JPEG2000 CODEC SOFTWARE PROVE DEFECTIVE IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, SUN MICROSYSTEMS, INC., THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING, REPAIR OR CORRECTION. 4. LIMITATION OF LIABILITY. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE INITIAL DEVELOPER, SUN MICROSYSTEMS, INC., THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE JPEG2000 CODEC SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY OF SUCH DAMAGES. THE JPEG2000 CODEC SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE JPEG2000 CODEC SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH RISK ACTIVITIES"). LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. USER WILL NOT KNOWINGLY USE, DISTRIBUTE OR RESELL THE JPEG2000 CODEC SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE NOTICE SPECIFIED IN THIS SECTION.UNLESS SPECIFIED IN THIS AGREEMENT, ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT ARE DISCLAIMED, EXCEPT TO THE EXTENT THAT THESE DISCLAIMERS ARE HELD TO BE LEGALLY INVALID. For inquiries please contact: Sun Microsystems, Inc. 4150 Network Circle, Santa Clara, CA 95054 (Form ID#011801) jai-imageio-core-1.2/build.properties 0000664 0001751 0001751 00000002537 10515267532 016717 0 ustar tille tille # # Base version and milestone. # String versions are as x.y[.z], file versions as x_y[_z]. # Specification milestones are edr, ..., mr. # Implementation milestones are alpha, ..., fcs # version_buildnum=04 version_betastr=alpha version_base=1.2 version_base_file=1_2 jai-imageio-core-1.2/src/ 0000775 0001751 0001751 00000000000 11650556176 014270 5 ustar tille tille jai-imageio-core-1.2/src/share/ 0000775 0001751 0001751 00000000000 11650556204 015362 5 ustar tille tille jai-imageio-core-1.2/src/share/services/ 0000775 0001751 0001751 00000000000 11650556177 017216 5 ustar tille tille jai-imageio-core-1.2/src/share/services/javax.imageio.spi.ImageInputStreamSpi 0000664 0001751 0001751 00000003736 10203036165 026336 0 ustar tille tille # # $RCSfile: javax.imageio.spi.ImageInputStreamSpi,v $ # # # Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # - Redistribution of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # - Redistribution in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # # Neither the name of Sun Microsystems, Inc. or the names of # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # This software is provided "AS IS," without a warranty of any # kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND # WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY # EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL # NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF # USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS # DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR # ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, # CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND # REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR # INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE # POSSIBILITY OF SUCH DAMAGES. # # You acknowledge that this software is not designed or intended for # use in the design, construction, operation or maintenance of any # nuclear facility. # # $Revision: 1.1 $ # $Date: 2005-02-11 05:02:44 $ # $State: Exp $ # # --- JAI-Image I/O ImageInputStream plug-ins --- # com.sun.media.imageioimpl.stream.ChannelImageInputStreamSpi jai-imageio-core-1.2/src/share/services/javax.media.jai.OperationRegistrySpi 0000664 0001751 0001751 00000003717 10203036165 026225 0 ustar tille tille # # $RCSfile: javax.media.jai.OperationRegistrySpi,v $ # # # Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # - Redistribution of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # - Redistribution in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # # Neither the name of Sun Microsystems, Inc. or the names of # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # This software is provided "AS IS," without a warranty of any # kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND # WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY # EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL # NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF # USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS # DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR # ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, # CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND # REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR # INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE # POSSIBILITY OF SUCH DAMAGES. # # You acknowledge that this software is not designed or intended for # use in the design, construction, operation or maintenance of any # nuclear facility. # # $Revision: 1.1 $ # $Date: 2005-02-11 05:02:44 $ # $State: Exp $ # # --- JAI-Image I/O operations registration --- # com.sun.media.jai.imageioimpl.ImageReadWriteSpi jai-imageio-core-1.2/src/share/services/javax.imageio.spi.ImageWriterSpi 0000664 0001751 0001751 00000005040 10667373164 025346 0 ustar tille tille # # $RCSfile: javax.imageio.spi.ImageWriterSpi,v $ # # # Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # - Redistribution of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # - Redistribution in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # # Neither the name of Sun Microsystems, Inc. or the names of # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # This software is provided "AS IS," without a warranty of any # kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND # WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY # EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL # NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF # USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS # DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR # ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, # CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND # REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR # INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE # POSSIBILITY OF SUCH DAMAGES. # # You acknowledge that this software is not designed or intended for # use in the design, construction, operation or maintenance of any # nuclear facility. # # $Revision: 1.2 $ # $Date: 2007-09-05 00:21:08 $ # $State: Exp $ # # --- JAI-Image I/O ImageWriter plug-ins --- # com.sun.media.imageioimpl.plugins.jpeg.CLibJPEGImageWriterSpi com.sun.media.imageioimpl.plugins.png.CLibPNGImageWriterSpi com.sun.media.imageioimpl.plugins.jpeg2000.J2KImageWriterSpi com.sun.media.imageioimpl.plugins.jpeg2000.J2KImageWriterCodecLibSpi com.sun.media.imageioimpl.plugins.wbmp.WBMPImageWriterSpi com.sun.media.imageioimpl.plugins.bmp.BMPImageWriterSpi com.sun.media.imageioimpl.plugins.gif.GIFImageWriterSpi com.sun.media.imageioimpl.plugins.pcx.PCXImageWriterSpi com.sun.media.imageioimpl.plugins.pnm.PNMImageWriterSpi com.sun.media.imageioimpl.plugins.raw.RawImageWriterSpi com.sun.media.imageioimpl.plugins.tiff.TIFFImageWriterSpi jai-imageio-core-1.2/src/share/services/javax.imageio.spi.ImageOutputStreamSpi 0000664 0001751 0001751 00000003733 10203036165 026534 0 ustar tille tille # # $RCSfile: javax.imageio.spi.ImageOutputStreamSpi,v $ # # # Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # - Redistribution of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # - Redistribution in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # # Neither the name of Sun Microsystems, Inc. or the names of # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # This software is provided "AS IS," without a warranty of any # kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND # WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY # EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL # NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF # USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS # DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR # ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, # CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND # REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR # INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE # POSSIBILITY OF SUCH DAMAGES. # # You acknowledge that this software is not designed or intended for # use in the design, construction, operation or maintenance of any # nuclear facility. # # $Revision: 1.1 $ # $Date: 2005-02-11 05:02:44 $ # $State: Exp $ # # --- JAI-Image I/O ImageReader plug-ins --- # com.sun.media.imageioimpl.stream.ChannelImageOutputStreamSpi jai-imageio-core-1.2/src/share/services/javax.imageio.spi.ImageReaderSpi 0000664 0001751 0001751 00000004750 10667373164 025303 0 ustar tille tille # # $RCSfile: javax.imageio.spi.ImageReaderSpi,v $ # # # Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # - Redistribution of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # - Redistribution in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # # Neither the name of Sun Microsystems, Inc. or the names of # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # This software is provided "AS IS," without a warranty of any # kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND # WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY # EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL # NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF # USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS # DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR # ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, # CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND # REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR # INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE # POSSIBILITY OF SUCH DAMAGES. # # You acknowledge that this software is not designed or intended for # use in the design, construction, operation or maintenance of any # nuclear facility. # # $Revision: 1.2 $ # $Date: 2007-09-05 00:21:08 $ # $State: Exp $ # # --- JAI-Image I/O ImageReader plug-ins --- # com.sun.media.imageioimpl.plugins.jpeg.CLibJPEGImageReaderSpi com.sun.media.imageioimpl.plugins.png.CLibPNGImageReaderSpi com.sun.media.imageioimpl.plugins.jpeg2000.J2KImageReaderSpi com.sun.media.imageioimpl.plugins.jpeg2000.J2KImageReaderCodecLibSpi com.sun.media.imageioimpl.plugins.wbmp.WBMPImageReaderSpi com.sun.media.imageioimpl.plugins.bmp.BMPImageReaderSpi com.sun.media.imageioimpl.plugins.pcx.PCXImageReaderSpi com.sun.media.imageioimpl.plugins.pnm.PNMImageReaderSpi com.sun.media.imageioimpl.plugins.raw.RawImageReaderSpi com.sun.media.imageioimpl.plugins.tiff.TIFFImageReaderSpi jai-imageio-core-1.2/src/share/classes/ 0000775 0001751 0001751 00000000000 11650556205 017020 5 ustar tille tille jai-imageio-core-1.2/src/share/classes/overview.html 0000664 0001751 0001751 00000107711 10667373231 021566 0 ustar tille tille
JavaTM Advanced Imaging Image I/O Tools provides JAI read and write operations which use the Java Image I/O Framework, image input and output streams which use the New I/O APIs, and image reader and writer plug-ins.java.nio
I/O APIs,
for use with the "raw" format image reader plug-in, and for reading
discontiguous image data are provided in the package
{@link com.sun.media.imageio.stream}.
true
if and only
if the image data are uncompressed. Capabilities not listed may be assumed to
revert to the respective defaults for reading and writing.
Capability | BMP | GIF | JPEG | JPEG 2000 | PCX | PNG | PNM | Raw | TIFF | WBMP |
---|---|---|---|---|---|---|---|---|---|---|
{@link javax.imageio.ImageReader#canReadRaster()} | T | X | F | T | F | F | T | T | F | T |
{@link javax.imageio.ImageReader#isRandomAccessEasy(int)} | U | X | F | F | F | F | T | T | U | T |
{@link javax.imageio.ImageReader#readerSupportsThumbnails()} | F | F | T | F | F | F | F | F | F | F |
{@link javax.imageio.ImageWriteParam#canWriteCompressed()} | T | T | T | T | F | T | F | F | T | F |
{@link javax.imageio.ImageWriteParam#canWriteProgressive()} | F | T | F | T | F | T | F | F | F | F |
{@link javax.imageio.ImageWriteParam#canWriteTiles()} | F | F | F | T | F | F | F | T | T | F |
{@link javax.imageio.ImageWriter#canInsertEmpty(int)} | F | F | F | F | F | F | F | F | T | F |
{@link javax.imageio.ImageWriter#canInsertImage(int)} | F | F | F | F | F | F | F | F | T | F |
{@link javax.imageio.ImageWriter#canReplacePixels(int)} | F | F | F | F | F | F | F | F | T | F |
{@link javax.imageio.ImageWriter#canWriteRasters()} | T | F | F | T | F | F | T | T | F | T |
{@link javax.imageio.ImageWriter#canWriteEmpty()} | F | F | F | F | F | F | F | F | T | F |
{@link javax.imageio.ImageWriter#canWriteSequence()} | F | T | F | F | F | F | F | F | T | F |
Stream Metadata | F | T | F | F | F | F | F | F | T | F |
Standard Image Metadata | T | T | T (reader only) | T | F | T | T | F | T | T (reader only) |
Native Image Metadata | T | T | T (reader only) | T | F | T | T | F | T | T (reader only) |
ImageReader
and ImageWriter
plug-ins are provided
for the Bitmap (BMP) format. A summary of the attributes of these plug-ins is
given in the following table with more details in the description of the
package {@link com.sun.media.imageio.plugins.bmp}.
Attribute | Value |
---|---|
Format Name | bmp |
MIME Type | image/bmp |
Suffix | bmp |
Native Image Metadata | com_sun_media_imageio_plugins_bmp_image_1.0 |
{@link javax.imageio.ImageWriteParam} | {@link com.sun.media.imageio.plugins.bmp.BMPImageWriteParam} |
References | No formal, well-defined specification exists but the BMP - Windows Bitmap Format FAQ Entry contains useful information |
ImageWriter
plug-in is provided for the Graphics Interchange
Format (GIF). Animated GIF images may be created using the standard sequence
writing methods defined in {@link javax.imageio.ImageWriter}. By default the
writer creates version "89a" images.
The writer supports setting output stream metadata from
metadata supplied to the writer in either the native GIF stream metadata format
javax_imageio_gif_stream_1.0
or the standard metadata format
javax_imageio_1.0
, and setting output image metadata from metadata
supplied to the writer in either the native GIF image metadata format
javax_imageio_gif_image_1.0
or the standard metadata format
javax_imageio_1.0
. The mapping of standard metadata format to
the GIF native stream and image metadata formats is given in the tables
below.
A global color table is written to the output stream if one of the following conditions obtains:
A local color table is written to the output stream only if image metadata containing a LocalColorTable element are supplied to the writer, or no image metadata are supplied to the writer and the local color table which would be generated from the image itself is not equal to the global color table.
A Graphic Control Extension block is written to the output stream only if image metadata containing a GraphicControlExtension element are supplied to the writer, or no image metadata are supplied and the local color table generated from the image requires a transparent index. Application, Plain Text, and Comment Extension blocks are written only if they are supplied to the writer via image metadata.
Standard Metadata Component | GIF Native Stream Metadata Component |
---|---|
/Chroma/Palette/PaletteEntry@index | /GlobalColorTable/ColorTableEntry@index |
/Chroma/Palette/PaletteEntry@red | /GlobalColorTable/ColorTableEntry@red |
/Chroma/Palette/PaletteEntry@green | /GlobalColorTable/ColorTableEntry@green |
/Chroma/Palette/PaletteEntry@blue | /GlobalColorTable/ColorTableEntry@blue |
/Chroma/BackgroundIndex@value | /GlobalColorTable@backgroundColorIndex |
/Data/BitsPerSample@value | /LogicalScreenDescriptor@colorResolution |
/Dimension/PixelAspectRatio@value | /LogicalScreenDescriptor@pixelAspectRatio |
/Dimension/HorizontalScreenSize@value | /LogicalScreenDescriptor@logicalScreenWidth |
/Dimension/VerticalScreenSize@value | /LogicalScreenDescriptor@logicalScreenHeight |
/Document/FormatVersion@value | /Version@value |
Standard Metadata Component | GIF Native Image Metadata Component |
---|---|
/Chroma/Palette/PaletteEntry@index | /LocalColorTable/ColorTableEntry@index |
/Chroma/Palette/PaletteEntry@red | /LocalColorTable/ColorTableEntry@red |
/Chroma/Palette/PaletteEntry@green | /LocalColorTable/ColorTableEntry@green |
/Chroma/Palette/PaletteEntry@blue | /LocalColorTable/ColorTableEntry@blue |
/Compression/NumProgressiveScans@value | /ImageDescriptor@interlaceFlag |
/Dimension/HorizontalPixelOffset@value | /ImageDescriptor@imageLeftPosition |
/Dimension/VerticalPixelOffset@value | /ImageDescriptor@imageTopPosition |
/Text/TextEntry@value | /CommentExtensions/CommentExtension@value |
/Transparency/TransparentIndex@value | /GraphicControlExtension@transparentColorIndex (/GraphicControlExtension@transparentColorFlag is also set to "TRUE") |
Attribute | Value |
---|---|
Format Name | gif |
MIME Type | image/gif |
Suffix | gif |
{@link javax.imageio.ImageWriteParam} | ImageWriteParam subclass |
References | GIF 87a Specification (W3C page) |
Attribute | Value |
---|---|
Compression Types | "LZW" |
Compression Modes | ImageWriteParam.MODE_DEFAULT ,
ImageWriteParam.MODE_EXPLICIT |
Progressive Modes | ImageWriteParam.MODE_COPY_FROM_METADATA (use metadata
setting if provided, otherwise interlaced),
ImageWriteParam.MODE_DEFAULT (interlaced),
ImageWriteParam.MODE_DISABLED (not interlaced)
( MODE_COPY_FROM_METADATA is initial setting)
|
ImageReader
and ImageWriter
plug-ins are provided
for the JPEG image format. These plug-ins are accelerated using native code.
If security permission settings disallow loading native code, or if the
system property "com.sun.media.imageio.disableCodecLib" is set to "true"
at the time of plug-in registration the service provider will deregister
itself and the plug-ins will not be available.
In addition to providing better performance through native acceleration for conventional (lossy) JPEG (baseline sequential DCT, 8-bit sample precision), these plug-ins also support the following additional JPEG coding processes from ISO-10918-1/ITU-T.81:
compressionType
set to "JPEG")compressionType
set to "JPEG-LOSSLESS")compressionType
set to "JPEG-LS")All subsampling and sub-banding is performed in memory, however, so if either is required, use of the core JPEG plug-in might be preferable. This plug-in performs best when the data are pixel interleaved with pixel stride equal to the number of samples per pixel and color component order G (grayscale), GA (grayscale with alpha), RGB (red-green-blue), BGR (blue-green-red), RGBA (red-green-blue with alpha), or CMYK (cyan-magenta-yellow-black) as appropriate for the color space. Other layouts will cause data to be reformatted in memory.
If the JPEG reader detects an ICC profile in an APP2 marker segment it
will use it to define the raw {@link javax.imageio.ImageTypeSpecifier}.
If the inferred color space not based on the ICC profile is compatible
with the ICC profile-based color space, then a second
ImageTypeSpecifier
derived from this inferred color
space will be included in the {@link java.util.Iterator} returned by
{@link javax.imageio.ImageReader#getImageTypes}. If the iterator contains
more than one type, the first one will be based on the ICC profile and the
second on the inferred color space.
The JPEG reader supports TIFF native image metadata as an extra metadata
format. If the JPEG stream contains an EXIF APP1 marker segment, the primary
IFD contained therein will be available from the metadata tree extracted
using the TIFF extra metadata format name. The IIOMetadata
object returned by the JPEG reader may also be used in a call to
{@link com.sun.media.imageio.plugins.tiff.TIFFDirectory#createFromMetadata
TIFFDirectory.createFromMetadata()} to create a TIFFDirectory
instance from which TIFFField
s may be easily extracted.
The JPEG reader supports thumbnails. These may be derived from JFIF APP0, JFXX APP0, or EXIF APP1 marker segments. Although APP0 marker segments are not allowed by the EXIF specification, there nevertheless exist EXIF images which contain them. If there is more than one thumbnail present, the JFIF thumbnail will be retrieved first, followed by any JFXX thumbnail(s), followed by any EXIF thumbnail. The source of each respective thumbnail may be determined by consulting the native image metadata.
The baseline DCT JPEG writer encodes images with from 1 to 4 bands. If
the image is 4-banded with a ColorSpace
of type
{@link java.awt.color.ColorSpace#TYPE_CMYK ColorSpace.TYPE_CMYK}, an Adobe
APP14 marker with transform parameter value 0 will be written and the image
components will not be subsampled.
Attribute | Value |
---|---|
Format Names | jpeg, jpg, jpeg-lossless (ISO 10918-1 lossless), jpeg-ls (ISO 14495-1 lossless), jfif |
MIME Type | image/jpeg |
Suffixes | jpeg, jpg, jls (ISO 14495-1 lossless), jfif |
Native Image Metadata | javax_imageio_jpeg_1.0 |
Extra Image Metadata | com_sun_media_imageio_plugins_tiff_image_1.0 |
{@link javax.imageio.ImageWriteParam} | ImageWriteParam subclass |
References | JPEG Home Page |
Attribute | Value |
---|---|
Compression Types | "JPEG" (conventional, lossy JPEG), "JPEG-LOSSLESS" (ISO-10918-1 lossless), "JPEG-LS" (ISO-14495-1 lossless) |
Compression Modes | ImageWriteParam.MODE_DEFAULT (lossy),
ImageWriteParam.MODE_EXPLICIT |
{@link javax.imageio.ImageWriteParam#isCompressionLossless()} | true if and only if compressionType is
not "JPEG" |
ImageReader
and
ImageWriter
plug-ins are provided for the JPEG 2000 image format.
A summary of the attributes of these plug-ins is given in the table below
with more details in the description of the package
{@link com.sun.media.imageio.plugins.jpeg2000}.
If security permission settings disallow loading native code, or if the
system property "com.sun.media.imageio.disableCodecLib" is set to "true"
at the time of plug-in registration the native service providers will
deregister themselves and the native plug-ins will not be available. If both
the native and JavaTM plug-ins are registered, the native plug-ins
will have higher precedence in the IIORegistry
.
Attribute | Value |
---|---|
Format Names | jpeg2000, jpeg 2000 |
MIME Type | image/jp2, image/jpeg2000 |
Suffix | jp2 |
Native Image Metadata | com_sun_media_imageio_plugins_jpeg2000_image_1.0 |
{@link javax.imageio.ImageReadParam} | {@link com.sun.media.imageio.plugins.jpeg2000.J2KImageReadParam} |
{@link javax.imageio.ImageWriteParam} | {@link com.sun.media.imageio.plugins.jpeg2000.J2KImageWriteParam} |
References | JPEG 2000 Links |
ImageReader
and ImageWriter
plug-ins are provided
for the PCX image format. A summary of the attributes of these plug-ins is
given in the following table.
Attribute | Value |
---|---|
Format Name | pcx |
MIME Types | image/pcx, image/x-pcx, image/x-windows-pcx, image/x-pc-paintbrush |
Suffixes | pcx |
References |
PCX Summary from the Encyclopedia of Graphics File Formats |
ImageReader
and ImageWriter
plug-ins are provided
for the Portable Network Graphics (PNG) image format. These plug-ins are
accelerated using native code.
If security permission settings disallow loading native code, or if the
system property "com.sun.media.imageio.disableCodecLib" is set to "true"
at the time of plug-in registration the service provider will deregister
itself and the plug-ins will not be available.
In addition to providing better performance through native acceleration, these plug-ins also provide the ability to set the compression level and encoder strategy. All subsampling and sub-banding is performed in memory, however, so if either of these is required, use of the core PNG plug-in might be preferable. This plug-in performs best when the data are either packed bilevel (1 sample per pixel, 1 bit per sample) or pixel interleaved with pixel stride equal to the number of samples per pixel and color component order G (grayscale), GA (grayscale with alpha), RGB (red-green-blue), or RGBA (red-green-blue with alpha) as appropriate for the color space. Other layouts will cause data to be reformatted in memory. Currently only bit depths of 1, 8, and 16 are supported.
If the PNG reader detects an ICC profile in an iCCP chunk it
will use it to define the raw {@link javax.imageio.ImageTypeSpecifier}.
If the inferred color space not based on the ICC profile field is compatible
with the ICC profile-based color space, then a second
ImageTypeSpecifier
derived from this inferred color
space will be included in the {@link java.util.Iterator} returned by
{@link javax.imageio.ImageReader#getImageTypes}. If the iterator contains
more than one type, the first one will be based on the ICC profile and the
second on the inferred color space.
The PNG writer will write an iCCP chunk to the output if one is in the
native image metadata object provided to the writer, or if the
ColorSpace
of the ColorModel
of the destination
ImageTypeSpecifier
is based on an ICC profile which is not one
of the standard ColorSpace
s corresponding to the
ColorSpace.cs_*
constants. The destination type is set via
{@link javax.imageio.ImageWriteParam#setDestinationType(ImageTypeSpecifier)
ImageWriteParam.setDestinationType()} and defaults to the
ImageTypeSpecifier
of the image being written.
Attribute | Value |
---|---|
Format Name | png |
MIME Type | image/png |
Suffix | png |
Native Image Metadata | javax_imageio_png_1.0 |
{@link javax.imageio.ImageWriteParam} | ImageWriteParam subclass |
References | W3C PNG Page |
Attribute | Value |
---|---|
Compression Types | "DEFAULT", "FILTERED", "HUFFMAN_ONLY" |
Compression Modes | ImageWriteParam.MODE_DEFAULT ,
ImageWriteParam.MODE_EXPLICIT ,
ImageWriteParam.MODE_COPY_FROM_METADATA (initial setting).
|
Compression Quality | Sets compression level as
compressionLevel = (int)(9*(1.0F - compressionQuality))
|
Progressive Modes | ImageWriteParam.MODE_DEFAULT ("Adam7" interlacing),
ImageWriteParam.MODE_DISABLED (no interlacing),
ImageWriteParam.MODE_COPY_FROM_METADATA (initial setting).
|
Standard Metadata Component | PNG Native Image Metadata Component |
---|---|
/Chroma/ColorSpaceType@name | /IHDR@colorType |
/Chroma/NumChannels@value | /IHDR@colorType, /tRNS |
/Chroma/Gamma@value | /gAMA@gamma |
/Chroma/BlackIsZero@value | Always "TRUE" |
/Chroma/Palette | /PLTE |
/Chroma/Palette/PaletteEntry@red | /PLTE/PLTEEntry@red |
/Chroma/Palette/PaletteEntry@green | /PLTE/PLTEEntry@green |
/Chroma/Palette/PaletteEntry@blue | /PLTE/PLTEEntry@blue |
/Chroma/Palette/PaletteEntry@alpha | /PLTE/PLTEEntry@alpha |
/Chroma/BackgroundIndex@value | /bKGD/bKGD_Palette@index |
/Chroma/BackgroundColor@red | /bKGD/bKGD_RGB@red or /bKGD/bKGD_Grayscale@gray |
/Chroma/BackgroundColor@green | /bKGD/bKGD_RGB@green or /bKGD/bKGD_Grayscale@gray |
/Chroma/BackgroundColor@blue | /bKGD/bKGD_RGB@blue or /bKGD/bKGD_Grayscale@gray |
/Compression/CompressionTypeName@value | Always "deflate" |
/Compression/Lossless@value | Always "TRUE" |
/Compression/NumProgressiveScans@value | /IHDR/interlaceMethod@value |
/Data/PlanarConfiguration@value | Always "PixelInterleaved" |
/Data/SampleFormat@value | /IHDR@colorType |
/Data/BitsPerSample@value | /IHDR@bitDepth, /IHDR@colorType, /tRNS |
/Data/SignificantBitsPerSample@value | /sBIT |
/Dimension/PixelAspectRatio@value | /pHYs@pixelsPerUnitYAxis//pHYs@pixelsPerUnitXAxis or 1.0 |
/Dimension/ImageOrientation@value | Always "Normal" |
/Dimension/HorizontalPixelSize@value | /pHYs@pixelsPerUnitXAxis, /pHYS@unitSpecifier |
/Dimension/VerticalPixelSize@value | /pHYs@pixelsPerUnitYAxis, /pHYS@unitSpecifier |
/Document/ImageModificationTime@value | /tIME |
/Text/TextEntry | /tEXt, /iTXt, /zTXt |
/Transparency/Alpha@value | /IHDR@colorType, /tRNS@alpha |
/Transparency/TransparentColor@value | /tRNS |
ImageReader
and ImageWriter
plug-ins are provided
for the "portable anymap" (PNM) image format which refers collectively to the
formats PBM (portable bitmap), PGM (portable graymap), and PPM (portable
pixmap). A summary of the attributes of these plug-ins is given in the
following table with more details in the description of the package
{@link com.sun.media.imageio.plugins.pnm}.
Attribute | Value |
---|---|
Format Name | pnm |
MIME Types | image/x-portable-anymap, image/x-portable-bitmap image/x-portable-graymap,image/x-portable-pixmap |
Suffixes | pbm, pgm, ppm |
Native Image Metadata | com_sun_media_imageio_plugins_pnm_image_1.0 |
{@link javax.imageio.ImageWriteParam} | {@link com.sun.media.imageio.plugins.pnm.PNMImageWriteParam} |
References |
The Netpbm Formats, Manpage of pbm, Manpage of pgm, Manpage of ppm |
ImageReader
and ImageWriter
plug-ins are provided
for the "raw" image format. The ImageReader
plug-in for the
"raw" format requires an input which is a
{@link com.sun.media.imageio.stream.RawImageInputStream}.
The reader plug-in reads any uncompressed data defined by
ComponentSampleModel
,
SinglePixelPackedSampleModel
or
MultiPixelPackedSampleModel
as viewed via the
ImageInputStream
. For example, if extra data are prepended or
appended to image lines,
{@link com.sun.media.imageio.stream.SegmentedImageInputStream} may be used
to define the location of the image data for each line. Thus, if the
data viewed from RawImageInputStream
are defined by the
SampleModel
s above
after RawImageInputStream
is chained with
SegmentedImageInputStream
, the reader plug-in can decode these
data correctly.
The writer plug-in writes the data to the stream exactly as defined by
the SampleModel
. If the SampleModel
has a
scanline stride associated with it, this will be used to determine the length
of each line written. If only the actual image data and not any prefix or
suffix data on the line are to be written and the scanline stride is greater
than the SampleModel
width multiplied by the number of bands,
the image should first be reformatted to remove the extra data. If JAI
is available the "Format" operation may be used for reformatting the data.
Attribute | Value |
---|---|
Format Name | raw |
MIME Type | none |
Suffix | none |
{@link javax.imageio.ImageWriteParam} | ImageWriteParam subclass |
References | XML {@link org.xml.sax.InputSource} defined at {@link com.sun.media.imageio.stream.RawImageInputStream#RawImageInputStream(javax.imageio.stream.ImageInputStream,org.xml.sax.InputSource)} |
Attribute | Value |
---|---|
Tiling Modes | ImageWriteParam.MODE_DEFAULT |
ImageReader
and ImageWriter
plug-ins are provided
for the Tag(ged) Image File Format (TIFF). A summary of the attributes of these
plug-ins is given in the table below with more details in the description
of the package {@link com.sun.media.imageio.plugins.tiff}. Native code
is used to accelerate bilevel encodings. If security permission settings
disallow loading native code, or if the system property
"com.sun.media.imageio.disableCodecLib" is set to "true" at the time of
(de)compression, native acceleration will not be used.
Attribute | Value |
---|---|
Format Names | tif, tiff |
MIME Type | image/tiff |
Suffixes | tif, tiff |
Native Stream Metadata | com_sun_media_imageio_plugins_tiff_stream_1.0 |
Native Image Metadata | com_sun_media_imageio_plugins_tiff_image_1.0 |
{@link javax.imageio.ImageReadParam} | {@link com.sun.media.imageio.plugins.tiff.TIFFImageReadParam} |
{@link javax.imageio.ImageWriteParam} | {@link com.sun.media.imageio.plugins.tiff.TIFFImageWriteParam} |
References |
TIFF 6.0 Specification (PDF), TIFF Specification Supplement 1 (PDF), TIFF Specification Supplement 2 (PDF) (covers ZLIB and JPEG compression in TIFF), The Unofficial TIFF Home Page, TIFF Software (libtiff), TIFF-F Revised Specification, JPEG-in-TIFF compression, DEFLATE specification (Zip-in-TIFF), ZLIB specification (Zip-in-TIFF), ICC Specification (PDF): section B.4: Embedding ICC profiles in TIFF files, EXIF and related resources |
ImageReader
and ImageWriter
plug-ins are provided
for the Wireless Bitmap (WBMP) image format. A summary of the attributes of
these plug-ins is given in the following table.
Attribute | Value |
---|---|
Format Name | wbmp |
MIME Type | image/vnd.wap.wbmp |
Suffix | wbmp |
Native Image Metadata | com_sun_media_imageio_plugins_wbmp_image_1.0 |
References | WAP Media Types Specification (PDF) available from WAP Forum Specifications and Open Mobile Alliance |
<?xml version="1.0" encoding="UTF-8"?> <!-- Schema for WBMP native image metadata format. --> <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://com.sun.media.imageio.plugins" targetNamespace="http://com.sun.media.imageio.plugins"> <!-- WBMP Schema 1.0 root element. --> <xsd:element name="com_sun_media_imageio_plugins_wbmp_image_1.0"> <xsd:complexType> <xsd:sequence> <!-- WBMP type --> <xsd:element name="WBMPType" type="xsd:unsignedInt"/> <!-- Bitmap width --> <xsd:element name="Width" type="xsd:unsignedInt"/> <!-- Bitmap height --> <xsd:element name="Height" type="xsd:unsignedInt"/> </xsd:sequence> </xsd:complexType> </xsd:element> <!-- wbmp_image_1.0 --> </xsd:schema>@since 1.0 jai-imageio-core-1.2/src/share/classes/com/ 0000775 0001751 0001751 00000000000 11650556205 017576 5 ustar tille tille jai-imageio-core-1.2/src/share/classes/com/sun/ 0000775 0001751 0001751 00000000000 11650556205 020403 5 ustar tille tille jai-imageio-core-1.2/src/share/classes/com/sun/media/ 0000775 0001751 0001751 00000000000 11650556206 021463 5 ustar tille tille jai-imageio-core-1.2/src/share/classes/com/sun/media/jai/ 0000775 0001751 0001751 00000000000 11650556205 022225 5 ustar tille tille jai-imageio-core-1.2/src/share/classes/com/sun/media/jai/imageioimpl/ 0000775 0001751 0001751 00000000000 11650556205 024521 5 ustar tille tille jai-imageio-core-1.2/src/share/classes/com/sun/media/jai/imageioimpl/ImageReadCRIF.java 0000664 0001751 0001751 00000042433 10343443200 027640 0 ustar tille tille /* * $RCSfile: ImageReadCRIF.java,v $ * * * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistribution of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * This software is provided "AS IS," without a warranty of any * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for * use in the design, construction, operation or maintenance of any * nuclear facility. * * $Revision: 1.2 $ * $Date: 2005-12-01 00:39:04 $ * $State: Exp $ */ package com.sun.media.jai.imageioimpl; import java.awt.Dimension; import java.awt.RenderingHints; import java.awt.geom.Rectangle2D; import java.awt.image.RenderedImage; import java.awt.image.renderable.ParameterBlock; import java.awt.image.renderable.RenderableImage; import java.awt.image.renderable.RenderContext; import java.io.FileInputStream; import java.io.InputStream; import java.io.IOException; import java.io.RandomAccessFile; import java.net.Socket; import java.net.URL; import java.nio.channels.Channel; import java.nio.channels.Channels; import java.util.Collection; import java.util.Comparator; import java.util.EventListener; import java.util.Iterator; import java.util.Locale; import java.util.TreeMap; import java.util.Vector; import javax.imageio.ImageIO; import javax.imageio.ImageReader; import javax.imageio.ImageReadParam; import javax.imageio.event.IIOReadProgressListener; import javax.imageio.event.IIOReadUpdateListener; import javax.imageio.event.IIOReadWarningListener; import javax.imageio.spi.ImageReaderSpi; import javax.imageio.stream.ImageInputStream; import javax.media.jai.CRIFImpl; import javax.media.jai.ImageLayout; import javax.media.jai.JAI; import javax.media.jai.MultiResolutionRenderableImage; import javax.media.jai.PropertySource; import javax.media.jai.WritablePropertySource; import com.sun.media.jai.operator.ImageReadDescriptor; public final class ImageReadCRIF extends CRIFImpl { public ImageReadCRIF() { super(); // Pass up the name? } /** * Attempt to create an {@link ImageInputStream} for the supplied * input. The following sequence is effected: *
input
is an ImageInputStream
it
* is cast and returned.input
is a String
it is converted
* to a read-only RandomAccessFile
.RandomAccessFile
fails, the
* String
input
is converted to an
* InputStream
by accessing it as a resource bundled
* in a JAR file.input
is a URL
it is converted
* to an InputStream
.input
is a Socket
it is converted
* to an InputStream
.ImageIO.createImageInputStream()
is invoked
* with parameter set to the (possibly converted) input and the
* value it returns (which could be null
) is returned
* to the caller.Object
to be used as the source,
* such as a String
, URL
, File
,
* readable RandomAccessFile
, InputStream
,
* readable Socket
, or readable Channel
.
*
* @return An ImageInputStream
or null
.
*/
private static ImageInputStream getImageInputStream(Object input) {
// The value to be returned.
ImageInputStream stream = null;
// If already an ImageInputStream cast and return.
if(input instanceof ImageInputStream) {
stream = (ImageInputStream)input;
} else {
// If the input is a String replace it with a RandomAccessFile.
if(input instanceof String) {
try {
// 'input' is conditionally checked for readability
// in the OperationDescriptor.
input = new RandomAccessFile((String)input, "r");
} catch(Exception e) {
// Try to get the file as an InputStream resource. This
// would happen when the application and image file are
// packaged in a JAR file
input = ImageReadCRIF.class.getClassLoader().getResourceAsStream((String)input);
if (input == null)
throw new RuntimeException
(I18N.getString("ImageReadCRIF0")+" "+input);
}
} else if(input instanceof URL) {
// If the input is a URL replace it with an InputStream.
try {
input = ((URL)input).openStream();
} catch(Exception e) {
throw new RuntimeException
(I18N.getString("ImageReadCRIF1")+" "+input);
}
} else if(input instanceof Socket) {
// If output is a Socket replace it with an InputStream.
try {
Socket socket = (Socket)input;
// XXX check binding, connection, closed, shutdown
// as these could have changed.
input = socket.getInputStream();
} catch(Exception e) {
throw new RuntimeException
(I18N.getString("ImageReadCRIF2")+" "+input);
}
}
}
// Create the ImageInputStream.
try {
stream = ImageIO.createImageInputStream(input);
} catch(Exception e) {
throw new RuntimeException(e);
}
return stream;
}
/**
* Get the ImageReader
and set its input and metadata flag.
* The input set on the reader might not be the same object as the input
* passed in if the latter was replaced by getImageInputStream().
*/
static ImageReader getImageReader(ParameterBlock pb) {
// Get the input.
Object input = pb.getObjectParameter(0);
// Get the reader parameter.
ImageReader reader = (ImageReader)pb.getObjectParameter(8);
// Attempt to create an ImageInputStream from the input.
ImageInputStream stream = getImageInputStream(input);
// If no reader passed in, try to find one.
if(reader == null) {
// Get all compatible readers.
Iterator readers = ImageIO.getImageReaders(stream != null ?
stream : input);
// If any readers, take the first one whose originating
// service provider indicates that it can decode the input.
if(readers != null && readers.hasNext()) {
do {
ImageReader tmpReader = (ImageReader)readers.next();
ImageReaderSpi readerSpi =
tmpReader.getOriginatingProvider();
try {
if(readerSpi.canDecodeInput(stream != null ?
stream : input)) {
reader = tmpReader;
}
} catch(IOException ioe) {
// XXX Ignore it?
}
} while(reader == null && readers.hasNext());
}
}
// If reader found, set its input and metadata flag.
if(reader != null) {
// Get the locale parameter and set on the reader.
Locale locale = (Locale)pb.getObjectParameter(6);
if(locale != null) {
reader.setLocale(locale);
}
// Get the listeners parameter and set on the reader.
EventListener[] listeners =
(EventListener[])pb.getObjectParameter(5);
if(listeners != null) {
for(int i = 0; i < listeners.length; i++) {
EventListener listener = listeners[i];
if(listener instanceof IIOReadProgressListener) {
reader.addIIOReadProgressListener(
(IIOReadProgressListener)listener);
}
if(listener instanceof IIOReadUpdateListener) {
reader.addIIOReadUpdateListener(
(IIOReadUpdateListener)listener);
}
if(listener instanceof IIOReadWarningListener) {
reader.addIIOReadWarningListener(
(IIOReadWarningListener)listener);
}
}
}
// Get the metadata reading flag.
boolean readMetadata =
((Boolean)pb.getObjectParameter(2)).booleanValue();
// Set the input and indicate metadata reading state.
reader.setInput(stream != null ? stream : input,
false, // seekForwardOnly
!readMetadata); // ignoreMetadata
}
return reader;
}
static void copyProperty(PropertySource ps,
WritablePropertySource wps,
String propertyName) {
Object propertyValue = ps.getProperty(propertyName);
if(propertyValue != null &&
!propertyValue.equals(java.awt.Image.UndefinedProperty)) {
wps.setProperty(propertyName, propertyValue);
}
}
public RenderedImage create(ParameterBlock pb,
RenderingHints rh) {
// Value to be returned.
RenderedImage image = null;
// Get the reader.
ImageReader reader = getImageReader(pb);
// Proceed if a compatible reader was found.
if(reader != null) {
// Get the remaining parameters required.
int imageIndex = pb.getIntParameter(1);
ImageReadParam param =
(ImageReadParam)pb.getObjectParameter(7);
boolean readThumbnails =
((Boolean)pb.getObjectParameter(3)).booleanValue();
// Initialize the layout.
ImageLayout layout =
(rh != null && rh.containsKey(JAI.KEY_IMAGE_LAYOUT)) ?
(ImageLayout)rh.get(JAI.KEY_IMAGE_LAYOUT) :
new ImageLayout();
try {
// Get the parameter input.
Object paramInput = pb.getObjectParameter(0);
// Get the reader input.
Object readerInput = reader.getInput();
// Set the stream to close when the OpImage is disposed.
ImageInputStream streamToClose = null;
if(readerInput != paramInput &&
readerInput instanceof ImageInputStream) {
streamToClose = (ImageInputStream)readerInput;
}
// Create the rendering.
image = new ImageReadOpImage(layout,
rh,
param,
reader,
imageIndex,
readThumbnails,
streamToClose);
} catch(Exception e) {
throw new RuntimeException(e);
}
}
return image;
}
// XXX This implementation of renderable mode is incredibly lame
// but the architecture and implementation allow for nothing else.
// It would be better if the CRIFs had some kind of state that
// could be associated with them. As it standards getBounds2D()
// will create a new MultiResolutionRenderableImage and so will
// the second create() below. Actually what is needed is a
// RenderableImageFactory definition.
// XXX There is also a problem with multiple invocations of the
// rendered mode case. Without saving and seeking back to the
// same offset it appears to have problems. Should ImageReadOpImage
// save the initial position and always seek back to it?
public RenderableImage createRenderable(ParameterBlock pb,
RenderingHints rh) {
// Read the collection.
Collection sequence = ImageReadCIF.createStatic(pb, rh);
// Create a SortedMap which sorts on the basis of inverse area.
// The keys will be Dimensions and the objects RenderedImages.
TreeMap sourceMap = new TreeMap(new Comparator() {
public int compare(Object o1, Object o2) {
Dimension d1 = (Dimension)o1;
Dimension d2 = (Dimension)o2;
int area1 = d1.width*d1.height;
int area2 = d2.width*d2.height;
double inverse1 = area1 == 0 ?
Double.MAX_VALUE : 1.0/area1;
double inverse2 = area2 == 0 ?
Double.MAX_VALUE : 1.0/area2;
if(inverse1 < inverse2) {
return -1;
} else if(inverse1 > inverse2) {
return 1;
} else {
return 0;
}
}
public boolean equals(Object o1, Object o2) {
return o1.equals(o2);
}
});
Iterator images = sequence.iterator();
while(images.hasNext()) {
RenderedImage image = (RenderedImage)images.next();
sourceMap.put(new Dimension(image.getWidth(), image.getHeight()),
image);
}
// Create the rendered source list sorted by inverse area.
Vector renderedSources = new Vector(sourceMap.size());
Iterator keys = sourceMap.keySet().iterator();
while(keys.hasNext()) {
renderedSources.add(sourceMap.get(keys.next()));
}
// Create the RenderableImage from the sorted RenderedImages.
MultiResolutionRenderableImage renderableImage =
new MultiResolutionRenderableImage(renderedSources,
0.0F, 0.0F, 1.0F);
// Set properties from those of the first rendered source.
PropertySource firstSource = (PropertySource)renderedSources.get(0);
copyProperty(firstSource,
renderableImage,
ImageReadDescriptor.PROPERTY_NAME_IMAGE_READ_PARAM);
copyProperty(firstSource,
renderableImage,
ImageReadDescriptor.PROPERTY_NAME_IMAGE_READER);
copyProperty(firstSource,
renderableImage,
ImageReadDescriptor.PROPERTY_NAME_METADATA_STREAM);
copyProperty(firstSource,
renderableImage,
ImageReadDescriptor.PROPERTY_NAME_METADATA_IMAGE);
// Return the RenderableImage.
return renderableImage;
}
public RenderedImage create(RenderContext rc,
ParameterBlock pb) {
RenderableImage renderableImage =
createRenderable(pb, rc.getRenderingHints());
RenderedImage renderedImage = renderableImage.createRendering(rc);
((WritablePropertySource)renderedImage).setProperty(
ImageReadDescriptor.PROPERTY_NAME_RENDERABLE_INPUT,
(PropertySource)renderableImage);
return renderedImage;
}
public Rectangle2D getBounds2D(ParameterBlock pb) {
// XXX Should just get the aspect ratio of the first image and use it.
// Otherwise this will be very inefficient.
RenderableImage renderable = createRenderable(pb, null);
return new Rectangle2D.Float(renderable.getMinX(),
renderable.getMinY(),
renderable.getWidth(),
renderable.getHeight());
}
}
jai-imageio-core-1.2/src/share/classes/com/sun/media/jai/imageioimpl/ImageWriteCIF.java 0000664 0001751 0001751 00000025564 10203036165 027746 0 ustar tille tille /*
* $RCSfile: ImageWriteCIF.java,v $
*
*
* Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistribution of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any
* kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
* WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
* EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
* NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
* USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
* ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
* CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
* REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
* INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for
* use in the design, construction, operation or maintenance of any
* nuclear facility.
*
* $Revision: 1.1 $
* $Date: 2005-02-11 05:01:55 $
* $State: Exp $
*/
package com.sun.media.jai.imageioimpl;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.awt.image.renderable.ParameterBlock;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.stream.ImageOutputStream;
import javax.media.jai.CollectionImage;
import javax.media.jai.CollectionImageFactory;
import javax.media.jai.CollectionOp;
import javax.media.jai.PropertySource;
import com.sun.media.jai.operator.ImageWriteDescriptor;
public final class ImageWriteCIF implements CollectionImageFactory {
/** Constructor. */
public ImageWriteCIF() {}
public CollectionImage create(ParameterBlock args,
RenderingHints hints) {
// Get the writer.
ImageWriter writer = (ImageWriter)args.getObjectParameter(13);
// Find a writer if null.
if(writer == null) {
// Get the format. Should be non-null from OperationDescriptor.
String format = (String)args.getObjectParameter(1);
// Find a writer.
Iterator writers = ImageIO.getImageWritersByFormatName(format);
// Get the writer.
if(writers != null) {
writer = (ImageWriter)writers.next();
} else {
throw new RuntimeException
(I18N.getString("ImageWriteCIF0")+" "+format);
}
}
// Get the source Collection.
Collection collection = (Collection)args.getSource(0);
// Determine the number of RenderedImages in the Collection.
int numRenderedImages = 0;
Iterator iter = collection.iterator();
while(iter.hasNext()) {
if(iter.next() instanceof RenderedImage) {
numRenderedImages++;
}
}
// Set the sequence flag.
boolean writeToSequence = writer.canWriteSequence();
// Check that the writer can write sequences.
if(numRenderedImages > 1 && !writeToSequence) {
throw new RuntimeException
(I18N.getString("ImageWriteCIF1"));
}
// Get the stream metadata.
IIOMetadata streamMetadata =
(IIOMetadata)args.getObjectParameter(7);
// Get the property use flag.
boolean useProperties =
((Boolean)args.getObjectParameter(2)).booleanValue();
// If null, get stream metadata from source properties if allowed.
if(streamMetadata == null &&
useProperties &&
collection instanceof PropertySource) {
Object streamMetadataProperty =
((PropertySource)collection).getProperty(
ImageWriteDescriptor.PROPERTY_NAME_METADATA_STREAM);
if(streamMetadataProperty instanceof IIOMetadata) {
streamMetadata = (IIOMetadata)streamMetadataProperty;
}
}
// Get the writer parameters.
ImageWriteParam param = (ImageWriteParam)args.getObjectParameter(12);
// Transcode the stream metadata if requested.
if(streamMetadata != null) {
// Get the transcoding flag.
boolean transcode =
((Boolean)args.getObjectParameter(3)).booleanValue();
if(transcode) {
// Overwrite the stream metadata with transcoded metadata.
streamMetadata =
writer.convertStreamMetadata(streamMetadata,
param);
}
}
if(writeToSequence) {
// Write the stream metadata to the sequence.
try {
// Get the output.
Object output = args.getObjectParameter(0);
// Try to get an ImageOutputStream.
ImageOutputStream stream =
ImageWriteCRIF.getImageOutputStream(output);
// Set the writer's output.
writer.setOutput(stream != null ? stream : output);
// Prepare the sequence.
writer.prepareWriteSequence(streamMetadata);
} catch(IOException e) {
throw new RuntimeException(e);
}
}
// Clone the ParameterBlock as the writer, image metadata, and
// thumbnail parameters will be replaced.
ParameterBlock imagePB = (ParameterBlock)args.clone();
// Clear the stream metadata.
imagePB.set(null, 7);
// Set the ImageWriter.
imagePB.set(writer, 13);
// Get the image metadata array.
IIOMetadata[] imageMetadata =
(IIOMetadata[])args.getObjectParameter(8);
// Get the thumbnail array.
BufferedImage[] thumbnails =
(BufferedImage[])args.getObjectParameter(9);
// Create a new Iterator.
iter = collection.iterator();
// Create an ImageIOCollectionImage to contain the result:
ImageIOCollectionImage imageList =
new ImageIOCollectionImage(collection.size());
// Iterate over the collection.
int imageIndex = 0;
while(iter.hasNext()) {
// Get the next element.
Object nextElement = iter.next();
// Process if a RenderedImage.
if(nextElement instanceof RenderedImage) {
// Replace source with current RenderedImage.
imagePB.setSource((RenderedImage)nextElement, 0);
// Replace image metadata.
if(imageMetadata != null) {
imagePB.set(imageMetadata[imageIndex], 8);
}
// Replace thumbnail array.
if(thumbnails != null) {
imagePB.set(thumbnails[imageIndex], 9);
}
// Write the image to the sequence
RenderedImage nextImage =
ImageWriteCRIF.create(imageIndex,
writeToSequence,
imagePB, hints);
// If the ImageWriteParam passed in was null, replace it
// with the first non-null ImageWriteParam property value
// and set the value in the local ParameterBlock.
if(param == null) {
Object paramPropertyValue =
nextImage.getProperty(
ImageWriteDescriptor.PROPERTY_NAME_IMAGE_WRITE_PARAM);
if(paramPropertyValue instanceof ImageWriteParam) {
param = (ImageWriteParam)paramPropertyValue;
// Replace the ImageWriteParam so the CRIF doesn't
// have to re-do the tile size initialization.
imagePB.set(param, 12);
}
}
// Add the image to the collection to be returned.
imageList.add(nextImage);
// Increment the index.
imageIndex++;
}
}
// Get the pixel replacement parameter.
boolean allowPixelReplacement =
((Boolean)args.getObjectParameter(5)).booleanValue();
if(writeToSequence && !allowPixelReplacement) {
// Complete writing the sequence.
try {
// XXX What about pixel replacement? If this is invoked here
// it will not be possible. How can this be invoked such that
// pixel replacement can occur but the user is not obliged to
// call this method manually?
// Answer: document that the user must obtain the writer from
// the collection-level ImageWriter property and invoke
// endWriteSequence() on it.
writer.endWriteSequence();
} catch(IOException e) {
throw new RuntimeException(e);
}
}
// Set collection-level properties.
if(param != null) {
imageList.setProperty(
ImageWriteDescriptor.PROPERTY_NAME_IMAGE_WRITE_PARAM,
param);
}
imageList.setProperty(
ImageWriteDescriptor.PROPERTY_NAME_IMAGE_WRITER,
writer);
if(streamMetadata != null) {
imageList.setProperty(
ImageWriteDescriptor.PROPERTY_NAME_METADATA_STREAM,
streamMetadata);
}
// Return CollectionImage.
return imageList;
}
// Forget it.
public CollectionImage update(ParameterBlock oldParamBlock,
RenderingHints oldHints,
ParameterBlock newParamBlock,
RenderingHints newHints,
CollectionImage oldRendering,
CollectionOp op) {
return null;
}
}
jai-imageio-core-1.2/src/share/classes/com/sun/media/jai/imageioimpl/ImageReadOpImage.java 0000664 0001751 0001751 00000106756 10456010035 030450 0 ustar tille tille /*
* $RCSfile: ImageReadOpImage.java,v $
*
*
* Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistribution of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any
* kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
* WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
* EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
* NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
* USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
* ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
* CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
* REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
* INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for
* use in the design, construction, operation or maintenance of any
* nuclear facility.
*
* $Revision: 1.2 $
* $Date: 2006-07-14 21:43:57 $
* $State: Exp $
*/
package com.sun.media.jai.imageioimpl;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.Raster;
import java.awt.image.SampleModel;
import java.awt.image.WritableRaster;
import java.io.InputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import javax.imageio.ImageReader;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageTypeSpecifier;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.spi.ImageReaderSpi;
import javax.imageio.stream.ImageInputStream;
import javax.media.jai.ImageLayout;
import javax.media.jai.OpImage;
import com.sun.media.jai.operator.ImageReadDescriptor;
/**
* Implementation of the OpImage
of the "ImageRead" operation.
*/
final class ImageReadOpImage extends OpImage {
/**
* XXX For testing only.
*/
/* XXX
public static void main(String[] args) throws Throwable {
java.io.File file = new java.io.File(args[0]);
int imageIndex = args.length > 1 ?
Integer.valueOf(args[1]).intValue() : 0;
int tileSize = args.length > 2 ?
Integer.valueOf(args[2]).intValue() : 128;
javax.imageio.stream.ImageInputStream stream =
new javax.imageio.stream.FileImageInputStream(file);
Iterator iter = javax.imageio.ImageIO.getImageReaders(stream);
ImageReader imageReader = (ImageReader)iter.next();
imageReader.setInput(stream,
true, // seekForwardOnly
false); // ignoreMetadata
ImageLayout layout = new ImageLayout();
layout.setTileWidth(tileSize).setTileHeight(tileSize);
//layout.setTileGridXOffset(42).setTileGridYOffset(7);
ImageReadParam param = imageReader.getDefaultReadParam();
param.setSourceSubsampling(2, 2, 0, 0);
param.setSourceRegion(new Rectangle(128, 0, 256, 256));
param.setSourceBands(new int[] {2, 1, 0});
param.setDestinationBands(new int[] {0, 1, 2});
OpImage image = new ImageReadOpImage(layout, // ImageLayout
null, // Map
param, // ImageReadParam
imageReader,
imageIndex,
true,
null); // streamToClose
System.out.println(new ImageLayout(image));
System.out.println("\nImage Properties:");
String[] propNames = image.getPropertyNames();
if(propNames != null) {
for(int i = 0; i < propNames.length; i++) {
System.out.println(i+" "+propNames[i]+" = "+
image.getProperty(propNames[i]));
}
}
System.out.println("");
BufferedImage[] thumbnails = null;
Object thumbnailProp =
image.getProperty(ImageReadDescriptor.PROPERTY_NAME_THUMBNAILS);
if(thumbnailProp != java.awt.Image.UndefinedProperty) {
thumbnails = (BufferedImage[])thumbnailProp;
}
java.awt.Frame frame =
new java.awt.Frame("ImageReadOpImage Test: "+file);
if(thumbnails != null) {
frame.setLayout(new java.awt.GridLayout(1, thumbnails.length+1));
}
frame.add(new javax.media.jai.widget.ScrollingImagePanel(image,
image.getWidth(),
image.getHeight()));
if(thumbnails != null) {
for(int i= 0; i < thumbnails.length; i++) {
frame.add(new javax.media.jai.widget.ScrollingImagePanel(thumbnails[i],
thumbnails[i].getWidth(),
thumbnails[i].getHeight()));
}
}
frame.pack();
frame.show();
}
*/
/**
* The ImageReadParam
used in reading the image.
*/
private ImageReadParam param;
/**
* The ImageReader
used to read the image.
*/
private ImageReader reader;
/**
* The index of the image to be read.
*/
private int imageIndex;
/**
* Whether thumbnails are to be read.
*/
private boolean readThumbnails;
/**
* Whether stream metadata have been be read.
*/
private boolean streamMetadataRead = false;
/**
* Whether image metadata have been be read.
*/
private boolean imageMetadataRead = false;
/**
* A stream to be closed when the instance is disposed; may be null.
*/
private ImageInputStream streamToClose;
/**
* Destination to source X scale factor.
*/
private int scaleX;
/**
* Destination to source Y scale factor.
*/
private int scaleY;
/**
* Destination to source X translation factor.
*/
private int transX;
/**
* Destination to source Y translation factor.
*/
private int transY;
/**
* Derive the image layout based on the user-supplied layout,
* reading parameters, and image index.
*/
private static ImageLayout layoutHelper(ImageLayout il,
ImageReadParam param,
ImageReader reader,
int imageIndex)
throws IOException {
ImageLayout layout = (il == null) ?
new ImageLayout() : (ImageLayout)il.clone();
// --- Determine the image type. ---
// If not provided in the original layout, set the SampleModel
// and ColorModel from the ImageReadParam, if supplied.
if(!layout.isValid(ImageLayout.SAMPLE_MODEL_MASK) &&
!layout.isValid(ImageLayout.COLOR_MODEL_MASK)) {
// If an ImageReadParam has been supplied and has its
// destinationType set then use it. Otherwise default to
// the raw image type.
ImageTypeSpecifier imageType =
(param != null && param.getDestinationType() != null) ?
param.getDestinationType() :
reader.getRawImageType(imageIndex);
// XXX The following block of code should not be necessary
// but for J2SE 1.4.0 FCS ImageReader.getRawImageType(0)
// returns null for earth.jpg, Bas-noir.jpg, etc.
if(imageType == null) {
Iterator imageTypes = reader.getImageTypes(imageIndex);
while(imageType == null && imageTypes.hasNext()) {
imageType = (ImageTypeSpecifier)imageTypes.next();
}
}
// XXX Should an exception be thrown if imageType is null?
if(imageType != null) {
// Set the SampleModel and ColorModel.
layout.setSampleModel(imageType.getSampleModel());
layout.setColorModel(imageType.getColorModel());
}
}
// --- Set up the destination bounds. ---
// Calculate the computable destination bounds.
Dimension sourceSize = getSourceSize(param, reader, imageIndex);
Rectangle srcRegion = new Rectangle();
Rectangle destRegion = new Rectangle();
computeRegions(param,
sourceSize.width,
sourceSize.height,
layout.getMinX(null), // valid value or 0
layout.getMinY(null), // valid value or 0
false,
srcRegion,
destRegion);
if(!destRegion.isEmpty()) {
// Backup layout image bounds with computable bounds.
if(!layout.isValid(ImageLayout.WIDTH_MASK)) {
layout.setWidth(destRegion.width);
}
if(!layout.isValid(ImageLayout.HEIGHT_MASK)) {
layout.setHeight(destRegion.height);
}
if(!layout.isValid(ImageLayout.MIN_X_MASK)) {
layout.setMinX(destRegion.x);
}
if(!layout.isValid(ImageLayout.MIN_Y_MASK)) {
layout.setMinY(destRegion.y);
}
// Ensure the layout bounds intersect computable bounds.
Rectangle destBounds = new Rectangle(layout.getMinX(null),
layout.getMinY(null),
layout.getWidth(null),
layout.getHeight(null));
if(destRegion.intersection(destBounds).isEmpty()) {
throw new IllegalArgumentException
(I18N.getString("ImageReadOpImage0"));
}
}
// --- Set up the tile grid. ---
if(!layout.isValid(ImageLayout.TILE_GRID_X_OFFSET_MASK)) {
layout.setTileGridXOffset(reader.getTileGridXOffset(imageIndex));
}
if(!layout.isValid(ImageLayout.TILE_GRID_Y_OFFSET_MASK)) {
layout.setTileGridYOffset(reader.getTileGridYOffset(imageIndex));
}
if(!layout.isValid(ImageLayout.TILE_WIDTH_MASK)) {
layout.setTileWidth(reader.getTileWidth(imageIndex));
}
if(!layout.isValid(ImageLayout.TILE_HEIGHT_MASK)) {
layout.setTileHeight(reader.getTileHeight(imageIndex));
}
return layout;
}
/**
* Returns whether an ImageTypeSpecifier
may be used
* to read in the image at a specified index.
*
* XXX
*/
private static boolean isCompatibleType(ImageTypeSpecifier imageType,
ImageReader reader,
int imageIndex)
throws IOException {
Iterator imageTypes = reader.getImageTypes(imageIndex);
boolean foundIt = false;
while (imageTypes.hasNext()) {
ImageTypeSpecifier type =
(ImageTypeSpecifier)imageTypes.next();
if (type.equals(imageType)) {
foundIt = true;
break;
}
}
return foundIt;
}
/**
* Returns the source region to be read. If the sourceRenderSize
* is being used it is returned; otherwise the raw source dimensions
* are returned.
*
* XXX
*/
private static Dimension getSourceSize(ImageReadParam param,
ImageReader reader,
int imageIndex)
throws IOException {
Dimension sourceSize = null;
if(param != null && param.canSetSourceRenderSize()) {
sourceSize = param.getSourceRenderSize();
}
if(sourceSize == null) {
sourceSize = new Dimension(reader.getWidth(imageIndex),
reader.getHeight(imageIndex));
}
return sourceSize;
}
/**
* XXX
*/
// Code copied from ImageReader.java
private static Rectangle getSourceRegion(ImageReadParam param,
int srcWidth,
int srcHeight) {
Rectangle sourceRegion = new Rectangle(0, 0, srcWidth, srcHeight);
if (param != null) {
Rectangle region = param.getSourceRegion();
if (region != null) {
sourceRegion = sourceRegion.intersection(region);
}
int subsampleXOffset = param.getSubsamplingXOffset();
int subsampleYOffset = param.getSubsamplingYOffset();
sourceRegion.x += subsampleXOffset;
sourceRegion.y += subsampleYOffset;
sourceRegion.width -= subsampleXOffset;
sourceRegion.height -= subsampleYOffset;
}
return sourceRegion;
}
/**
* XXX
*/
// clipDestRegion: whether to clip destRegion to positive coordinates.
// Code based on method of same name in ImageReader.java
private static void computeRegions(ImageReadParam param,
int srcWidth,
int srcHeight,
int destMinX,
int destMinY,
boolean clipDestRegion,
Rectangle srcRegion,
Rectangle destRegion) {
if (srcRegion == null) {
throw new IllegalArgumentException("srcRegion == null");
}
if (destRegion == null) {
throw new IllegalArgumentException("destRegion == null");
}
// Start with the entire source image
srcRegion.setBounds(0, 0, srcWidth, srcHeight);
// Destination also starts with source image, as that is the
// maximum extent if there is no subsampling
destRegion.setBounds(destMinX, destMinY, srcWidth, srcHeight);
// Clip that to the param region, if there is one
int periodX = 1;
int periodY = 1;
int gridX = 0;
int gridY = 0;
if (param != null) {
Rectangle paramSrcRegion = param.getSourceRegion();
if (paramSrcRegion != null) {
srcRegion.setBounds(srcRegion.intersection(paramSrcRegion));
}
periodX = param.getSourceXSubsampling();
periodY = param.getSourceYSubsampling();
gridX = param.getSubsamplingXOffset();
gridY = param.getSubsamplingYOffset();
srcRegion.translate(gridX, gridY);
srcRegion.width -= gridX;
srcRegion.height -= gridY;
Point destinationOffset = param.getDestinationOffset();
destRegion.translate(destinationOffset.x, destinationOffset.y);
}
if(clipDestRegion) {
// Now clip any negative destination offsets, i.e. clip
// to the top and left of the destination image
if (destRegion.x < 0) {
int delta = -destRegion.x*periodX;
srcRegion.x += delta;
srcRegion.width -= delta;
destRegion.x = 0;
}
if (destRegion.y < 0) {
int delta = -destRegion.y*periodY;
srcRegion.y += delta;
srcRegion.height -= delta;
destRegion.y = 0;
}
}
// Now clip the destination Region to the subsampled width and height
int subsampledWidth = (srcRegion.width + periodX - 1)/periodX;
int subsampledHeight = (srcRegion.height + periodY - 1)/periodY;
destRegion.width = subsampledWidth;
destRegion.height = subsampledHeight;
if (srcRegion.isEmpty() || destRegion.isEmpty()) {
throw new IllegalArgumentException
(I18N.getString("ImageReadOpImage1"));
}
}
/**
* XXX
* NB: This class may reset the following fields of the ImageReadParam
* destinationOffset
* destinationType
* sourceRegion
*/
ImageReadOpImage(ImageLayout layout,
Map configuration,
ImageReadParam param,
ImageReader reader,
int imageIndex,
boolean readThumbnails,
ImageInputStream streamToClose) throws IOException {
super(null,
layoutHelper(layout, param, reader, imageIndex),
configuration,
false);
// Revise parameter 'param' as needed.
if(param == null) {
// Get the ImageReadParam from the ImageReader.
param = reader.getDefaultReadParam();
} else if(param instanceof Cloneable) {
this.param = param;
} else if(param.getClass().getName().equals(
"javax.imageio.ImageReadParam")) {
// The ImageReadParam passed in is non-null. As the
// ImageReadParam class is not Cloneable, if the param
// class is simply ImageReadParam, then create a new
// ImageReadParam instance and set all its fields
// which were set in param. This will eliminate problems
// with concurrent modification of param for the cases
// in which there is not a special ImageReadparam used.
// Create a new ImageReadParam instance.
ImageReadParam newParam = new ImageReadParam();
// Set all fields which need to be set.
// IIOParamController field.
if(param.hasController()) {
newParam.setController(param.getController());
}
// Destination fields.
newParam.setDestination(param.getDestination());
if(param.getDestinationType() != null) {
// Set the destination type only if non-null as the
// setDestinationType() clears the destination field.
newParam.setDestinationType(param.getDestinationType());
}
newParam.setDestinationBands(param.getDestinationBands());
newParam.setDestinationOffset(param.getDestinationOffset());
// Source fields.
newParam.setSourceBands(param.getSourceBands());
newParam.setSourceRegion(param.getSourceRegion());
if(param.getSourceMaxProgressivePass() != Integer.MAX_VALUE) {
newParam.setSourceProgressivePasses(
param.getSourceMinProgressivePass(),
param.getSourceNumProgressivePasses());
}
if(param.canSetSourceRenderSize()) {
newParam.setSourceRenderSize(param.getSourceRenderSize());
}
newParam.setSourceSubsampling(param.getSourceXSubsampling(),
param.getSourceYSubsampling(),
param.getSubsamplingXOffset(),
param.getSubsamplingYOffset());
// Replace the local variable with the new ImageReadParam.
param = newParam;
}
// Revise parameter 'readThumbnails' as needed.
if(readThumbnails && !reader.hasThumbnails(imageIndex)) {
// Unset thumbnail flag if not supported by ImageReader.
readThumbnails = false;
}
// Set instance variables from (possibly revised) parameters.
this.param = param;
this.reader = reader;
this.imageIndex = imageIndex;
this.readThumbnails = readThumbnails;
this.streamToClose = streamToClose;
// If an ImageTypeSpecifier is specified in the ImageReadParam
// but it is incompatible with the ImageReader, then attempt to
// replace it with a compatible one derived from this image.
if(param.getDestinationType() != null &&
!isCompatibleType(param.getDestinationType(), reader, imageIndex) &&
sampleModel != null && colorModel != null) {
ImageTypeSpecifier newImageType =
new ImageTypeSpecifier(colorModel, sampleModel);
if(isCompatibleType(newImageType, reader, imageIndex)) {
param.setDestinationType(newImageType);
}
}
// --- Compute the destination to source mapping coefficients. ---
Dimension sourceSize = getSourceSize(param, reader, imageIndex);
Rectangle srcRegion = getSourceRegion(param,
sourceSize.width,
sourceSize.height);
Point destinationOffset = this.param.getDestinationOffset();
this.scaleX = this.param.getSourceXSubsampling();
this.scaleY = this.param.getSourceYSubsampling();
this.transX =
srcRegion.x + this.param.getSubsamplingXOffset() -
this.param.getSourceXSubsampling()*(minX + destinationOffset.x);
this.transY =
srcRegion.y + this.param.getSubsamplingYOffset() -
this.param.getSourceYSubsampling()*(minY + destinationOffset.y);
// Replace the original destination offset with (0,0) as the
// destination-to-source mapping assimilates this value.
this.param.setDestinationOffset(new Point());
// XXX Need to unset other ImageReadParam settings either here
// or in computeTile(). Examine this issue taking into account
// synchronization.
// Set the ImageReadParam property.
setProperty(ImageReadDescriptor.PROPERTY_NAME_IMAGE_READ_PARAM, param);
// Set the ImageReader property.
setProperty(ImageReadDescriptor.PROPERTY_NAME_IMAGE_READER, reader);
// If metadata are being read, set the value of the metadata
// properties to UndefinedProperty so that the property
// names will appear in the array of property names. The actual
// values will be retrieved when getProperty() is invoked.
if(!reader.isIgnoringMetadata()) {
// Get the service provider interface, if any.
ImageReaderSpi provider = reader.getOriginatingProvider();
// Stream metadata.
if(provider == null ||
provider.isStandardStreamMetadataFormatSupported() ||
provider.getNativeStreamMetadataFormatName() != null) {
// Assume an ImageReader with a null provider supports
// stream metadata.
setProperty(ImageReadDescriptor.PROPERTY_NAME_METADATA_STREAM,
java.awt.Image.UndefinedProperty);
} else {
// Provider supports neither standard nor native stream
// metadata so set flag to suppress later reading attempt.
streamMetadataRead = true;
}
// Image metadata.
if(provider == null ||
provider.isStandardImageMetadataFormatSupported() ||
provider.getNativeImageMetadataFormatName() != null) {
// Assume an ImageReader with a null provider supports
// image metadata.
setProperty(ImageReadDescriptor.PROPERTY_NAME_METADATA_IMAGE,
java.awt.Image.UndefinedProperty);
} else {
// Provider supports neither standard nor native image
// metadata so set flag to suppress later reading attempt.
imageMetadataRead = true;
}
}
// If thumbnail read flag is set, set the value of the thumbnail
// property to UndefinedProperty so that the thumbnail property
// name will appear in the array of property names. The actual
// value will be retrieved when getProperty() is invoked.
if(readThumbnails && reader.readerSupportsThumbnails()) {
setProperty(ImageReadDescriptor.PROPERTY_NAME_THUMBNAILS,
java.awt.Image.UndefinedProperty);
}
}
/**
* Returns false as ImageReaders might return Rasters
* via computeTile() tile that are internally cached.
*/
public boolean computesUniqueTiles() {
return false;
}
/**
* XXX
*/
private Rectangle computeSourceRect(Rectangle destRect) {
Rectangle sourceRect = new Rectangle();
sourceRect.x = scaleX*destRect.x + transX;
sourceRect.y = scaleY*destRect.y + transY;
sourceRect.width =
scaleX*(destRect.x + destRect.width) + transX - sourceRect.x;
sourceRect.height =
scaleY*(destRect.y + destRect.height) + transY - sourceRect.y;
return sourceRect;
}
/**
* Computes a tile.
*
* @param tileX The X index of the tile.
* @param tileY The Y index of the tile.
*/
public Raster computeTile(int tileX, int tileY) {
//XXX System.out.println("Tile ("+tileX+","+tileY+")");
// Create a new WritableRaster to represent this tile.
Point org = new Point(tileXToX(tileX), tileYToY(tileY));
//WritableRaster dest = Raster.createWritableRaster(sampleModel, org);
Rectangle rect = new Rectangle(org.x, org.y, tileWidth, tileHeight);
// Clip output rectangle to image bounds.
// Not sure what will happen here with the bounds intersection.
Rectangle destRect = rect.intersection(getBounds());
// XXX Check for destRect.isEmpty()?
/* XXX delete
java.awt.geom.AffineTransform transform =
new java.awt.geom.AffineTransform(scaleX, 0, 0, scaleY,
transX, transY);
*/
Rectangle srcRect =
computeSourceRect(destRect);
/* XXX delete
transform.createTransformedShape(destRect).getBounds();
*/
WritableRaster readerTile = null;
try {
synchronized(reader) {
param.setSourceRegion(srcRect);
BufferedImage bi = reader.read(imageIndex, param);
WritableRaster ras = bi.getRaster();
readerTile = ras.createWritableChild(0, 0,
ras.getWidth(),
ras.getHeight(),
org.x, org.y,
null);
}
} catch(IOException e) {
throw new RuntimeException(e);
}
WritableRaster tile = null;
if(sampleModel == readerTile.getSampleModel()) {
tile = readerTile;
} else {
// XXX As this method is synchronized, could a single
// destination be supplied to the reader instead of
// creating a new one?
tile = Raster.createWritableRaster(sampleModel, org);
tile.setRect(readerTile);
}
return tile;
}
/**
* Throws an IllegalArgumentException since the image has no image
* sources.
*
* @param sourceRect ignored.
* @param sourceIndex ignored.
*
* @throws IllegalArgumentException since the image has no sources.
*/
public Rectangle mapSourceRect(Rectangle sourceRect,
int sourceIndex) {
throw new IllegalArgumentException
(I18N.getString("ImageReadOpImage2"));
}
/**
* Throws an IllegalArgumentException since the image has no image
* sources.
*
* @param destRect ignored.
* @param sourceIndex ignored.
*
* @throws IllegalArgumentException since the image has no sources.
*/
public Rectangle mapDestRect(Rectangle destRect,
int sourceIndex) {
throw new IllegalArgumentException
(I18N.getString("ImageReadOpImage2"));
}
/**
* Gets a property from the property set of this image. If the
* property name is not recognized,
* java.awt.Image.UndefinedProperty
will be returned.
*
* This implementation first attempts to retrieve the property * using the equivalent superclass method. If the returned value * is not a valid property value, the requested property name is * that of the image thumbnails property, the stream metadata * property, or the image metadata property, and there has been no * prior attempt to read the corresponding property value, then its * reads the value and set the property. This implementation therefore * defers reading of the image thumbnails, stream metadata, and image * metadata values until the correpsonding property is actually * requested.
* * @param name the name of the property to get, as aString
.
*
* @return A reference to the property Object
, or the value
* java.awt.Image.UndefinedProperty
.
*
* @exception IllegalArgumentException if propertyName
* is null
.
*/
public Object getProperty(String name) {
// Attempt to get property from superclass method.
Object property = super.getProperty(name);
// If thumbnail property name with undefined value and thumbnails
// are being read and an attempt to read them has not already been
// made, then read the thumbnails and set the property.
if((property == null ||
property == java.awt.Image.UndefinedProperty)) {
// Thumbnails
if(readThumbnails &&
name.equalsIgnoreCase(
ImageReadDescriptor.PROPERTY_NAME_THUMBNAILS)) {
// Lock the class to avoid a race condition here
// and with computeTile().
synchronized(reader) {
// First re-check the flag in case another thread
// got here first.
if(readThumbnails) {
try {
// Get number of thumbnails.
int numThumbnails =
reader.getNumThumbnails(imageIndex);
if(numThumbnails > 0) {
// Read all thumbnails.
BufferedImage[] thumbnails =
new BufferedImage[numThumbnails];
for(int i = 0; i < numThumbnails; i++) {
thumbnails[i] =
reader.readThumbnail(imageIndex, i);
}
// Set thumbnail property.
setProperty(
ImageReadDescriptor.PROPERTY_NAME_THUMBNAILS,
thumbnails);
// Update return value.
property = thumbnails;
}
} catch(IOException e) {
throw new RuntimeException(e);
} finally {
// If return value is somehow null set it
// to UndefinedProperty.
if(property == null) {
property = java.awt.Image.UndefinedProperty;
}
// Unset thumbnail flag to avert subsequent
// reading attempts in case this one failed.
readThumbnails = false;
}
}
}
} else if(!reader.isIgnoringMetadata() &&
((!streamMetadataRead &&
name.equalsIgnoreCase(
ImageReadDescriptor.PROPERTY_NAME_METADATA_STREAM)) ||
(!imageMetadataRead &&
name.equalsIgnoreCase(
ImageReadDescriptor.PROPERTY_NAME_METADATA_IMAGE)))) {
// Lock the class to avoid a race condition here
// and with computeTile().
synchronized(reader) {
// Set flag to indicate stream or image metadata.
boolean isStreamMetadata =
name.equalsIgnoreCase(
ImageReadDescriptor.PROPERTY_NAME_METADATA_STREAM);
// Recheck the appropriate flag.
if(!(isStreamMetadata ?
streamMetadataRead : imageMetadataRead)) {
// Set property name.
String propertyName = isStreamMetadata ?
ImageReadDescriptor.PROPERTY_NAME_METADATA_STREAM :
ImageReadDescriptor.PROPERTY_NAME_METADATA_IMAGE;
IIOMetadata metadata = null;
try {
// Read metadata.
metadata = isStreamMetadata ?
reader.getStreamMetadata() :
reader.getImageMetadata(imageIndex);
// Set metadata property.
if(metadata != null) {
setProperty(propertyName, metadata);
}
// Update return value.
property = metadata;
} catch(IOException e) {
throw new RuntimeException(e);
} finally {
// If return value is somehow null set it
// to UndefinedProperty.
if(property == null) {
property = java.awt.Image.UndefinedProperty;
}
// Set appropriate flag to avert subsequent
// reading attempts in case this one failed.
if(isStreamMetadata) {
streamMetadataRead = true;
} else {
imageMetadataRead = true;
}
}
}
}
}
}
return property;
}
/**
* Closes an ImageInputStream
passed in, if any.
*/
public void dispose() {
if(streamToClose != null) {
try {
streamToClose.close();
} catch(IOException e) {
// Ignore it.
}
}
super.dispose();
}
}
jai-imageio-core-1.2/src/share/classes/com/sun/media/jai/imageioimpl/ImageReadCIF.java 0000664 0001751 0001751 00000014771 10203036165 027525 0 ustar tille tille /*
* $RCSfile: ImageReadCIF.java,v $
*
*
* Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistribution of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any
* kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
* WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
* EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
* NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
* USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
* ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
* CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
* REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
* INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for
* use in the design, construction, operation or maintenance of any
* nuclear facility.
*
* $Revision: 1.1 $
* $Date: 2005-02-11 05:01:54 $
* $State: Exp $
*/
package com.sun.media.jai.imageioimpl;
import java.awt.Dimension;
import java.awt.RenderingHints;
import java.awt.image.renderable.ParameterBlock;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageReader;
import javax.media.jai.CollectionImage;
import javax.media.jai.CollectionImageFactory;
import javax.media.jai.CollectionOp;
import javax.media.jai.JAI;
import javax.media.jai.PlanarImage;
import com.sun.media.jai.operator.ImageReadDescriptor;
public class ImageReadCIF implements CollectionImageFactory {
static CollectionImage createStatic(ParameterBlock args,
RenderingHints hints) {
// Clone the ParameterBlock as the ImageChoice will be overwritten.
ParameterBlock renderedPB = (ParameterBlock)args.clone();
// Get the ImageChoice.
int[] imageIndices = (int[])args.getObjectParameter(1);
// Variables to be set in the subsequent "if" block.
// XXX Could probably collapse the if block into a single code seq.
int numSources;
ImageIOCollectionImage imageList = null;
if(imageIndices == null) {
// null-valued ImageChoice: load all images.
// Load the first image.
renderedPB.set(0, 1);
PlanarImage image = JAI.create("ImageRead", renderedPB, hints);
// Get the ImageReader property.
Object readerProperty =
image.getProperty(
ImageReadDescriptor.PROPERTY_NAME_IMAGE_READER);
// Try to read the number of images.
if(readerProperty instanceof ImageReader) {
try {
// XXX Really should not allow search here. If search
// is disallowed and -1 is returned from getNumImages(),
// then "ImageRead" should just be called until an
// IndexOutOfBoundsException is caught.
numSources =
((ImageReader)readerProperty).getNumImages(true);
} catch(Exception e) { // IOException
// Default to one source.
numSources = 1;
}
} else {
numSources = 1;
}
// Allocate and fill index array.
imageIndices = new int[numSources];
for(int i = 0; i < numSources; i++) {
imageIndices[i] = i;
}
// Allocate list and add first image.
imageList = new ImageIOCollectionImage(numSources);
imageList.add(image);
} else {
// Set the number of sources and create the list.
numSources = imageIndices.length;
imageList = new ImageIOCollectionImage(numSources);
// Load the first image requested.
renderedPB.set(imageIndices[0], 1);
PlanarImage image = JAI.create("ImageRead", renderedPB, hints);
// Add the first image to the list.
imageList.add(image);
}
// Read subsequent images and add to the list.
for(int idx = 1; idx < numSources; idx++) {
renderedPB.set(imageIndices[idx], 1);
PlanarImage image = JAI.create("ImageRead", renderedPB, hints);
imageList.add(image);
}
// Get the first image in the Collection.
PlanarImage firstImage = (PlanarImage)imageList.get(0);
// Transfer properties to the Collection.
ImageReadCRIF.copyProperty(firstImage,
imageList,
ImageReadDescriptor.PROPERTY_NAME_IMAGE_READ_PARAM);
ImageReadCRIF.copyProperty(firstImage,
imageList,
ImageReadDescriptor.PROPERTY_NAME_IMAGE_READER);
ImageReadCRIF.copyProperty(firstImage,
imageList,
ImageReadDescriptor.PROPERTY_NAME_METADATA_STREAM);
return imageList;
}
/** Constructor. */
public ImageReadCIF() {}
public CollectionImage create(ParameterBlock args,
RenderingHints hints) {
return createStatic(args, hints);
}
// Forget it.
public CollectionImage update(ParameterBlock oldParamBlock,
RenderingHints oldHints,
ParameterBlock newParamBlock,
RenderingHints newHints,
CollectionImage oldRendering,
CollectionOp op) {
return null;
}
}
jai-imageio-core-1.2/src/share/classes/com/sun/media/jai/imageioimpl/ImageWriteCRIF.java 0000664 0001751 0001751 00000065474 10203036165 030074 0 ustar tille tille /*
* $RCSfile: ImageWriteCRIF.java,v $
*
*
* Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistribution of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any
* kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
* WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
* EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
* NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
* USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
* ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
* CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
* REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
* INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for
* use in the design, construction, operation or maintenance of any
* nuclear facility.
*
* $Revision: 1.1 $
* $Date: 2005-02-11 05:01:55 $
* $State: Exp $
*/
package com.sun.media.jai.imageioimpl;
import java.awt.Dimension;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.awt.image.renderable.ParameterBlock;
import java.awt.image.renderable.RenderableImage;
import java.awt.image.renderable.RenderContext;
import java.io.IOException;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.net.Socket;
import java.util.Arrays;
import java.util.EventListener;
import java.util.Iterator;
import java.util.Locale;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageTypeSpecifier;
import javax.imageio.ImageWriter;
import javax.imageio.ImageWriteParam;
import javax.imageio.event.IIOWriteProgressListener;
import javax.imageio.event.IIOWriteWarningListener;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.stream.ImageOutputStream;
import javax.media.jai.CRIFImpl;
import javax.media.jai.PlanarImage;
import javax.media.jai.RenderedImageAdapter;
import javax.media.jai.WritablePropertySource;
import com.sun.media.jai.operator.ImageWriteDescriptor;
public final class ImageWriteCRIF extends CRIFImpl {
public static void main(String[] args) throws Throwable {
java.io.File inFile = new java.io.File(args[0]);
java.io.File outFile = new java.io.File(args[1]);
String format = args.length > 2 ? args[2] : "png";
String mode = args.length > 3 ? args[3] : "rendered";
int imageIndex = 0;
javax.imageio.stream.ImageInputStream inStream =
javax.imageio.ImageIO.createImageInputStream(inFile);
java.util.Iterator iter =
javax.imageio.ImageIO.getImageReaders(inStream);
javax.imageio.ImageReader reader =
(javax.imageio.ImageReader)iter.next();
reader.setInput(inStream);
RenderedImage image = reader.read(imageIndex);
javax.imageio.metadata.IIOMetadata streamMetadata =
reader.getStreamMetadata();
javax.imageio.metadata.IIOMetadata imageMetadata =
reader.getImageMetadata(imageIndex);
java.awt.image.BufferedImage[] thumbnails = null;
if(reader.hasThumbnails(imageIndex)) {
int numThumbnails = reader.getNumThumbnails(imageIndex);
thumbnails = new java.awt.image.BufferedImage[numThumbnails];
for(int i = 0; i < numThumbnails; i++) {
thumbnails[i] = reader.readThumbnail(imageIndex, i);
}
}
ImageWriteCRIF crif = new ImageWriteCRIF();
ParameterBlock pb = new ParameterBlock();
if(mode.equalsIgnoreCase("rendered")) {
pb.addSource(image);
} else if(mode.equalsIgnoreCase("renderable")) {
ParameterBlock renderablePB = new ParameterBlock();
renderablePB.addSource(image);
RenderableImage renderable =
javax.media.jai.JAI.createRenderable("renderable",
renderablePB);
pb.addSource(renderable);
}
pb.add(outFile); // Output
pb.add(format); // Format
pb.add(Boolean.TRUE); // UseProperties
pb.add(Boolean.TRUE); // Transcode
pb.add(Boolean.TRUE); // VerifyOutput
pb.add(Boolean.TRUE); // AllowPixelReplacement
pb.add(null); // TileSize
pb.add(streamMetadata);
pb.add(imageMetadata);
pb.add(thumbnails);
pb.add(null); // EventListener[]
pb.add(null); // Locale
pb.add(null); // ImageWriteParam
pb.add(null); // ImageWriter
if(mode.equalsIgnoreCase("rendered")) {
crif.create(pb, null);
} else if(mode.equalsIgnoreCase("renderable")) {
java.awt.geom.AffineTransform transform =
new java.awt.geom.AffineTransform(256, 0, 0, 512, 0, 0);
crif.create(new RenderContext(transform), pb);
}
}
public ImageWriteCRIF() {
super();
}
/**
* Attempt to create an {@link ImageOutputStream} for the supplied
* output. The following sequence is effected:
* output
is an ImageOutputStream
it
* is cast and returned.output
is a String
it is converted
* to a read-write RandomAccessFile
.output
is a Socket
it is converted
* to an OutputStream
.ImageIO.createImageOutputStream()
is invoked
* with parameter set to the (possibly converted) output and the
* value it returns (which could be null
) is returned
* to the caller.Object
to be used as the destination,
* such as a String
, File
, writable
* RandomAccessFile
, OutputStream
, writable
* Socket
, or writable Channel
.
*
* @return An ImageOutputStream
or null
.
*/
static ImageOutputStream getImageOutputStream(Object output) {
// The value to be returned.
ImageOutputStream stream = null;
// If already an ImageOutputStream just cast.
if(output instanceof ImageOutputStream) {
stream = (ImageOutputStream)output;
} else {
if(output instanceof String) {
// If output is a String replace it with a RandomAccessFile.
try {
// 'output' is conditionally checked for writability
// in the OperationDescriptor.
output = new RandomAccessFile((String)output, "rw");
} catch(Exception e) {
throw new RuntimeException
(I18N.getString("ImageWriteCRIF0")+" "+output);
}
} else if(output instanceof Socket) {
// If output is a Socket replace it with an OutputStream.
try {
// XXX check binding, connection, closed, shutdown
// as these could have changed.
output = ((Socket)output).getOutputStream();
} catch(Exception e) {
throw new RuntimeException
(I18N.getString("ImageWriteCRIF1")+" "+output);
}
}
// Create the ImageOutputStream.
try {
stream = ImageIO.createImageOutputStream(output);
} catch(IOException e) {
throw new RuntimeException(e);
}
}
return stream;
}
/**
* {@link RenderedImageFactory} implementation.
*/
public RenderedImage create(ParameterBlock pb,
RenderingHints rh) {
return create(0, false, pb, rh);
}
private static ImageWriteParam getWriteParam(ImageWriteParam param,
ImageWriter writer) {
// Set default to original ImageWriteParam.
ImageWriteParam newParam = param;
if(param == null) {
newParam = writer.getDefaultWriteParam();
} else if(param.getClass().getName().equals(
"javax.imageio.ImageWriteParam")) {
// The ImageWriteParam passed in is non-null. As the
// ImageWriteParam class is not Cloneable, if the param
// class is simply ImageWriteParam, then create a new
// ImageWriteParam instance and set all its fields
// which were set in param. This will eliminate problems
// with concurrent modification of param for the cases
// in which there is not a special ImageWriteParam used.
// Create a new ImageWriteParam instance.
newParam = writer.getDefaultWriteParam();
// Set all fields which need to be set.
// IIOParamController field.
if(param.hasController()) {
newParam.setController(param.getController());
}
// Destination fields.
newParam.setDestinationOffset(param.getDestinationOffset());
newParam.setDestinationType(param.getDestinationType());
// Source fields.
newParam.setSourceBands(param.getSourceBands());
newParam.setSourceRegion(param.getSourceRegion());
newParam.setSourceSubsampling(param.getSourceXSubsampling(),
param.getSourceYSubsampling(),
param.getSubsamplingXOffset(),
param.getSubsamplingYOffset());
// Compression.
if(param.canWriteCompressed()) {
int compressionMode = param.getCompressionMode();
newParam.setCompressionMode(compressionMode);
if(compressionMode == ImageWriteParam.MODE_EXPLICIT) {
newParam.setCompressionQuality(param.getCompressionQuality());
newParam.setCompressionType(param.getCompressionType());
}
}
// Progressive
if(param.canWriteProgressive()) {
newParam.setProgressiveMode(param.getProgressiveMode());
}
// Tiling
if(param.canWriteTiles()) {
int tilingMode = param.getTilingMode();
newParam.setTilingMode(tilingMode);
if(tilingMode == ImageWriteParam.MODE_EXPLICIT) {
newParam.setTiling(param.getTileWidth(),
param.getTileHeight(),
param.getTileGridXOffset(),
param.getTileGridYOffset());
}
}
}
return newParam;
}
/**
* If tiling is supported, determine the appropriate tile size and
* set it on the returned param if necessary. The returned param
* will either be a new ImageWriteParam or the one passed in with
* its tiling settings possibly modified.
*/
private static ImageWriteParam setTileSize(ImageWriteParam param,
ImageWriter writer,
Dimension tileSize,
RenderedImage source) {
ImageWriteParam returnParam = getWriteParam(param, writer);
// If tiling possible set tile size if needed.
if(returnParam.canWriteTiles()) {
if(tileSize != null) {
// Check tile size.
if(tileSize.width <= 0 || tileSize.height <= 0) {
throw new IllegalArgumentException
("tileSize.width <= 0 || tileSize.height <= 0");
}
// Use specified tile size.
returnParam.setTilingMode(ImageWriteParam.MODE_EXPLICIT);
returnParam.setTiling(tileSize.width,
tileSize.height,
0, 0); // XXX set tile offsets?
} else if(param == null) {
if(source.getNumXTiles() > 1 || source.getNumYTiles() > 1) {
// Null tile size and param args: use source tile size.
returnParam.setTilingMode(ImageWriteParam.MODE_EXPLICIT);
returnParam.setTiling(source.getTileWidth(),
source.getTileHeight(),
0, 0); // XXX set tile offsets?
}
} else if(returnParam.getTilingMode() ==
ImageWriteParam.MODE_EXPLICIT) {
// Param passed in has explicit mode set but the tile
// grid might not actually be set.
boolean setTileSize = false;
// Save reference to preferred tile size array.
Dimension[] preferredTileSizes =
returnParam.getPreferredTileSizes();
// Set the tile width.
int tileWidth = 0;
try {
// Try to get it from the param.
tileWidth = returnParam.getTileWidth();
} catch(IllegalStateException e) {
// Not set in the param.
setTileSize = true;
if(preferredTileSizes != null &&
preferredTileSizes.length >= 2 &&
preferredTileSizes[0].width > 0 &&
preferredTileSizes[1].width > 0) {
// Use average of first two preferred tile widths.
tileWidth = (preferredTileSizes[0].width +
preferredTileSizes[1].width) / 2;
} else {
// Use source image tile width.
tileWidth = source.getTileWidth();
}
}
// Set the tile height.
int tileHeight = 0;
try {
// Try to get it from the param.
tileHeight = returnParam.getTileHeight();
} catch(IllegalStateException e) {
// Not set in the param.
setTileSize = true;
if(preferredTileSizes != null &&
preferredTileSizes.length >= 2 &&
preferredTileSizes[0].height > 0 &&
preferredTileSizes[1].height > 0) {
// Use average of first two preferred tile heights.
tileHeight = (preferredTileSizes[0].height +
preferredTileSizes[1].height) / 2;
} else {
// Use source image tile height.
tileHeight = source.getTileHeight();
}
}
// Set the tile size if not previously set in the param.
if(setTileSize) {
returnParam.setTiling(tileWidth,
tileHeight,
0, 0); // XXX set tile offsets?
}
}
}
return returnParam;
}
static RenderedImage create(int imageIndex,
boolean writeToSequence,
ParameterBlock pb,
RenderingHints rh) {
// Value to be returned.
RenderedImage image = null;
// Get the source image.
RenderedImage source = pb.getRenderedSource(0);
// Get the writer parameters.
ImageWriteParam param = (ImageWriteParam)pb.getObjectParameter(12);
// Set the target image type.
ImageTypeSpecifier destinationType = null;
if(param != null) {
destinationType = param.getDestinationType();
}
if(destinationType == null) {
destinationType = new ImageTypeSpecifier(source);
}
// Get the writer.
ImageWriter writer = (ImageWriter)pb.getObjectParameter(13);
if(writer == null) {
// Get the format. Should be non-null from OperationDescriptor.
String format = (String)pb.getObjectParameter(1);
// Find a writer.
Iterator writers = ImageIO.getImageWriters(destinationType,
format);
// Get the writer.
if(writers != null && writers.hasNext()) {
writer = (ImageWriter)writers.next();
}
}
// XXX What if no writer? Exception?
if(writer != null) {
// XXX Replace ImageWriter parameter in ParameterBlock?
ImageOutputStream streamToClose = null;
// Set the output if not writing to a sequence (in which
// case the output should already be set.
if(!writeToSequence) {
// Get the output.
Object output = pb.getObjectParameter(0);
// Try to get an ImageOutputStream.
ImageOutputStream stream = getImageOutputStream(output);
// Set stream to close if not writing to a sequence.
streamToClose = stream != output ? stream : null;
// Set the writer's output.
writer.setOutput(stream != null ? stream : output);
}
// Get the property use flag.
boolean useProperties =
((Boolean)pb.getObjectParameter(2)).booleanValue();
// Get the transcoding flag.
boolean transcode =
((Boolean)pb.getObjectParameter(3)).booleanValue();
IIOMetadata streamMetadata = null;
if(!writeToSequence) {
// Get the stream metadata.
streamMetadata = (IIOMetadata)pb.getObjectParameter(7);
// If null, get stream metadata from source properties
// if allowed.
if(streamMetadata == null && useProperties) {
Object streamMetadataProperty =
source.getProperty(
ImageWriteDescriptor.PROPERTY_NAME_METADATA_STREAM);
if(streamMetadataProperty instanceof IIOMetadata) {
streamMetadata = (IIOMetadata)streamMetadataProperty;
}
}
// Transcode the stream metadata if requested.
if(streamMetadata != null && transcode) {
// Overwrite the stream metadata with transcoded metadata.
streamMetadata =
writer.convertStreamMetadata(streamMetadata,
param);
}
}
// Get the image metadata.
IIOMetadata imageMetadata =
(IIOMetadata)pb.getObjectParameter(8);
// If null, get image metadata from source properties if allowed.
if(imageMetadata == null && useProperties) {
Object imageMetadataProperty =
source.getProperty(
ImageWriteDescriptor.PROPERTY_NAME_METADATA_IMAGE);
if(imageMetadataProperty instanceof IIOMetadata) {
imageMetadata = (IIOMetadata)imageMetadataProperty;
}
}
// Transcode the image metadata if requested.
if(imageMetadata != null && transcode) {
// Overwrite the image metadata with transcoded metadata.
imageMetadata = writer.convertImageMetadata(imageMetadata,
destinationType,
param);
}
// Get the thumbnails if supported by the writer.
BufferedImage[] thumbnails = null;
if(writer.getNumThumbnailsSupported(destinationType,
param,
streamMetadata,
imageMetadata) > 0) {
thumbnails = (BufferedImage[])pb.getObjectParameter(9);
// If null, get thumbnails from source properties if allowed.
if(thumbnails == null && useProperties) {
Object thumbnailsProperty =
source.getProperty(
ImageWriteDescriptor.PROPERTY_NAME_METADATA_IMAGE);
if(thumbnailsProperty instanceof BufferedImage[]) {
thumbnails = (BufferedImage[])thumbnailsProperty;
}
}
}
// Get the locale parameter and set on the writer.
Locale locale = (Locale)pb.getObjectParameter(11);
if(locale != null) {
writer.setLocale(locale);
}
// Get the listeners parameter and set on the writer.
EventListener[] listeners =
(EventListener[])pb.getObjectParameter(10);
if(listeners != null) {
for(int i = 0; i < listeners.length; i++) {
EventListener listener = listeners[i];
if(listener instanceof IIOWriteProgressListener) {
writer.addIIOWriteProgressListener(
(IIOWriteProgressListener)listener);
}
if(listener instanceof IIOWriteWarningListener) {
writer.addIIOWriteWarningListener(
(IIOWriteWarningListener)listener);
}
}
}
// Set the tile size.
// XXX Replace ImageWriteParam parameter in ParameterBlock?
param = setTileSize(param, writer,
(Dimension)pb.getObjectParameter(6),
source);
// Create the IIOImage container.
IIOImage iioImage = new IIOImage(source,
thumbnails != null ?
Arrays.asList(thumbnails) : null,
imageMetadata);
try {
// Write the image.
if(writeToSequence) {
writer.writeToSequence(iioImage, param);
} else {
writer.write(streamMetadata, iioImage, param);
}
// Get the pixel replacement parameter.
boolean allowPixelReplacement =
((Boolean)pb.getObjectParameter(5)).booleanValue();
// Set the return value.
if(allowPixelReplacement &&
source instanceof PlanarImage &&
writer.canReplacePixels(imageIndex)) {
// Create an image which is a PropertyChangeListener of
// "invalidregion" events including RenderingChangeEvents.
image = new PixelReplacementImage(source,
rh,
param,
writer,
imageIndex,
streamToClose);
// Register the image as a sink of its source so that
// it automatically receives events.
((PlanarImage)source).addSink(image);
} else if(!writeToSequence) {
Object writerOutput = writer.getOutput();
if(writerOutput != pb.getObjectParameter(0) &&
writerOutput instanceof ImageOutputStream) {
// This block is executed if and only if pixel
// replacement is not occurring, a sequence is
// not being written, and an ImageOutputStream
// inaccessible to the application is set on the
// ImageWriter.
((ImageOutputStream)writerOutput).flush();
}
// Set the return value to the original image or
// a wrapped version thereof.
image = source instanceof WritablePropertySource ?
source : new RenderedImageAdapter(source);
}
// Set required properties.
WritablePropertySource wps = (WritablePropertySource)image;
// Set the ImageWriteParam property.
wps.setProperty(
ImageWriteDescriptor.PROPERTY_NAME_IMAGE_WRITE_PARAM,
param);
// Set the ImageWriter property.
wps.setProperty(
ImageWriteDescriptor.PROPERTY_NAME_IMAGE_WRITER,
writer);
// Set the stream metadata property.
if(streamMetadata != null) {
wps.setProperty(
ImageWriteDescriptor.PROPERTY_NAME_METADATA_STREAM,
streamMetadata);
}
// Set the image metadata property.
if(imageMetadata != null) {
wps.setProperty(
ImageWriteDescriptor.PROPERTY_NAME_METADATA_IMAGE,
imageMetadata);
}
// Set the thumbnail property.
if(thumbnails != null) {
wps.setProperty(
ImageWriteDescriptor.PROPERTY_NAME_THUMBNAILS,
thumbnails);
}
} catch(IOException e) {
throw new RuntimeException(e);
}
}
return image;
}
}
jai-imageio-core-1.2/src/share/classes/com/sun/media/jai/imageioimpl/ImageIOCollectionImage.java 0000664 0001751 0001751 00000005447 10203036165 031616 0 ustar tille tille /*
* $RCSfile: ImageIOCollectionImage.java,v $
*
*
* Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistribution of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any
* kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
* WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
* EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
* NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
* USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
* ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
* CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
* REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
* INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for
* use in the design, construction, operation or maintenance of any
* nuclear facility.
*
* $Revision: 1.1 $
* $Date: 2005-02-11 05:01:54 $
* $State: Exp $
*/
package com.sun.media.jai.imageioimpl;
import java.util.ArrayList;
import javax.media.jai.CollectionImage;
/**
* A CollectionImage
to be used as the return value from
* ImageReadCIF.create()
and ImageWriteCIF.create()
.
* The imageCollection
instance variable is a List
.
*/
class ImageIOCollectionImage extends CollectionImage {
/**
* Creates an ImageIOCollectionImage
with the specified
* capacity.
*
* @exception IllegalArgumentException if capacity
is
* not positive.
*/
ImageIOCollectionImage(int capacity) {
super();
if(capacity <= 0) {
// No message as this is not at the API level and it is
// the unique exception.
throw new IllegalArgumentException();
}
imageCollection = new ArrayList(capacity);
}
}
jai-imageio-core-1.2/src/share/classes/com/sun/media/jai/imageioimpl/PixelReplacementImage.java 0000664 0001751 0001751 00000025175 10203036165 031571 0 ustar tille tille /*
* $RCSfile: PixelReplacementImage.java,v $
*
*
* Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistribution of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any
* kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
* WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
* EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
* NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
* USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
* ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
* CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
* REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
* INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for
* use in the design, construction, operation or maintenance of any
* nuclear facility.
*
* $Revision: 1.1 $
* $Date: 2005-02-11 05:01:55 $
* $State: Exp $
*/
package com.sun.media.jai.imageioimpl;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.image.Raster;
import java.awt.image.RenderedImage;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;
import java.util.Vector;
import javax.media.jai.ImageLayout;
import javax.media.jai.OpImage;
import javax.media.jai.PlanarImage;
import javax.media.jai.RenderedOp;
import javax.media.jai.PropertyChangeEventJAI;
import javax.media.jai.RenderingChangeEvent;
import javax.imageio.ImageWriter;
import javax.imageio.ImageWriteParam;
import javax.imageio.stream.ImageOutputStream;
/**
* Implementation of PlanarImage
for the "ImageWrite" operation
* for the case of ImageWriter
s which can replace pixels. The
* sole purpose of this class is to respond to "invalidregion" events so
* as to update the written image.
*/
final class PixelReplacementImage extends PlanarImage
implements PropertyChangeListener {
/**
* The ImageWriteParam
used in writing the image.
*/
private ImageWriteParam param;
/**
* The ImageWriter
used to write the image.
*/
private ImageWriter writer;
/**
* The index of the image to be write.
*/
private int imageIndex;
/**
* A stream to be closed when the instance is disposed; may be null.
*/
private ImageOutputStream streamToClose;
/**
* Creates a Vector
containing a single element.
*/
private static Vector createVector(Object element) {
Vector v = new Vector(1);
v.add(element);
return v;
}
/**
* XXX
*/
PixelReplacementImage(RenderedImage source,
Map configuration,
ImageWriteParam param,
ImageWriter writer,
int imageIndex,
ImageOutputStream streamToClose) throws IOException {
super(new ImageLayout(source), // Layout same as source.
createVector(source),
configuration);
// Verify that the writer can replace pixels.
if(!writer.canReplacePixels(imageIndex)) {
throw new IllegalArgumentException
("!writer.canReplacePixels(imageIndex)");
}
// Set the instance variables from the parameters.
// XXX Should ImageWriteParam original settings be cached for
// testing later to see whether anything important has changed?
this.param = param;
this.writer = writer;
this.imageIndex = imageIndex;
this.streamToClose = streamToClose;
}
/**
* Close an ImageOutputStream
passed in.
*/
public void dispose() {
if(streamToClose != null) {
try {
streamToClose.close();
} catch(IOException e) {
// Ignore it.
}
}
super.dispose();
}
/**
* Gets a tile.
*
* @param tileX The X index of the tile.
* @param tileY The Y index of the tile.
*/
public Raster getTile(int tileX, int tileY) {
return getSourceImage(0).getTile(tileX, tileY);
}
// --- PropertyChangeListener implementation ---
// XXX Doc
public void propertyChange(PropertyChangeEvent evt) {
PlanarImage source = getSourceImage(0);
Object eventSource = evt.getSource();
//
// Process the event if the writer can replace pixels,
// the event source is the source of this OpImage,
// and the event name is "invalidregion".
//
if((evt instanceof PropertyChangeEventJAI &&
evt.getPropertyName().equalsIgnoreCase("invalidregion") &&
eventSource.equals(source)) ||
(evt instanceof RenderingChangeEvent &&
evt.getOldValue().equals(source) &&
eventSource instanceof RenderedOp &&
evt.getNewValue().equals(((RenderedOp)eventSource).getRendering()))) {
// Get the invalid region information.
Shape srcInvalidRegion = null;
if(evt instanceof RenderingChangeEvent) {
// RenderingChangeEvent presumably from a source RenderedOp.
RenderingChangeEvent rcEvent = (RenderingChangeEvent)evt;
// Get the invalidated region of the source.
srcInvalidRegion = rcEvent.getInvalidRegion();
// Reset this image's source.
source = (PlanarImage)evt.getNewValue();
setSource(source, 0);
// If entire source is invalid replace with source bounds.
if(srcInvalidRegion == null) {
srcInvalidRegion =
((PlanarImage)rcEvent.getOldValue()).getBounds();
}
} else {
// Get the invalidated region of the source.
Object evtNewValue = (Shape)evt.getNewValue();
// Continue if the value class is correct.
if(evtNewValue instanceof Shape) {
srcInvalidRegion = (Shape)evtNewValue;
// If entire source is invalid replace with source bounds.
if(srcInvalidRegion == null) {
srcInvalidRegion = source.getBounds();
}
}
}
// Return if the invalid portion could not be determined.
if(srcInvalidRegion == null) {
return;
}
// Return if the invalid region does not overlap the param region.
if(param != null) {
Rectangle sourceRegion = param.getSourceRegion();
if(sourceRegion != null &&
!srcInvalidRegion.intersects(sourceRegion)) {
return;
}
} else {
param = writer.getDefaultWriteParam();
}
// Get indices of all tiles overlapping the invalid region.
Point[] tileIndices =
source.getTileIndices(srcInvalidRegion.getBounds());
// Should not happen but return if tileIndices is null.
if(tileIndices == null) return;
// Get subsampling values.
int gridX = minX + param.getSubsamplingXOffset();
int gridY = minY + param.getSubsamplingYOffset();
int stepX = param.getSourceXSubsampling();
int stepY = param.getSourceYSubsampling();
boolean isSubsampling =
stepX != 1 || stepY != 1 || gridX != minX || gridY != minY;
// Loop over affected tiles.
int numTiles = tileIndices.length;
for(int i = 0; i < numTiles; i++) {
// Save the next tile index.
Point tileIndex = tileIndices[i];
// Compute tile bounds.
Rectangle tileRect =
source.getTileRect(tileIndex.x, tileIndex.y);
// Replace if bounds intersect invalid region.
if(srcInvalidRegion.intersects(tileRect)) {
// Get the source tile.
Raster raster = source.getTile(tileIndex.x, tileIndex.y);
Rectangle destRect;
if(isSubsampling) {
int destMinX =
(tileRect.x - gridX + stepX - 1)/stepX;
int destMinY =
(tileRect.y - gridY + stepY - 1)/stepY;
int destMaxX =
(tileRect.x + tileRect.width -
gridX + stepX - 1)/stepX;
int destMaxY =
(tileRect.y + tileRect.height -
gridY + stepY - 1)/stepY;
destRect = new Rectangle(destMinX, destMinY,
destMaxX - destMinX,
destMaxY - destMinY);
} else {
destRect = tileRect;
}
// Replace the pixels.
try {
synchronized(writer) {
writer.prepareReplacePixels(imageIndex, destRect);
param.setDestinationOffset(destRect.getLocation());
writer.replacePixels(raster, param);
writer.endReplacePixels();
}
} catch(IOException e) {
throw new RuntimeException(e);
}
}
}
}
}
}
jai-imageio-core-1.2/src/share/classes/com/sun/media/jai/imageioimpl/properties 0000664 0001751 0001751 00000001713 10203036165 026631 0 ustar tille tille #
# $RCSfile: properties,v $
#
# Copyright (c) 2005 Sun Microsystems, Inc. All rights reserved.
#
# Use is subject to license terms.
#
# $Revision: 1.1 $
# $Date: 2005-02-11 05:01:56 $
# $State: Exp $
#
# Internationalization file for com.sun.media.jai.imageioimpl
ImageReadCRIF0=Cannot create read-only RandomAccessFile for path
ImageReadCRIF1=Cannot create InputStream for URL
ImageReadCRIF2=Cannot create InputStream for Socket
ImageReadOpImage0=Destination bounds do not intersect available destination data region.
ImageReadOpImage1=Source or destination region is empty.
ImageReadOpImage2=Cannot perform rectangle mapping between source and destination because the image has no sources.
ImageWriteCIF0=Unable to find an ImageWriter for format
ImageWriteCIF1=Source Collection has more than one image and ImageWriter cannot write sequences.
ImageWriteCRIF0=Cannot create read-write RandomAccessFile for path
ImageWriteCRIF1=Cannot create OutputStream for Socket
jai-imageio-core-1.2/src/share/classes/com/sun/media/jai/imageioimpl/I18N.java 0000664 0001751 0001751 00000004165 10203036165 026040 0 ustar tille tille /*
* $RCSfile: I18N.java,v $
*
*
* Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistribution of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any
* kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
* WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
* EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
* NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
* USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
* ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
* CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
* REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
* INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for
* use in the design, construction, operation or maintenance of any
* nuclear facility.
*
* $Revision: 1.1 $
* $Date: 2005-02-11 05:01:54 $
* $State: Exp $
*/
package com.sun.media.jai.imageioimpl;
import com.sun.media.imageioimpl.common.I18NImpl;
final class I18N extends I18NImpl {
static String getString(String key) {
return getString("com.sun.media.jai.imageioimpl.I18N", key);
}
}
jai-imageio-core-1.2/src/share/classes/com/sun/media/jai/imageioimpl/ImageReadWriteSpi.java 0000664 0001751 0001751 00000013706 10203036165 030667 0 ustar tille tille /*
* $RCSfile: ImageReadWriteSpi.java,v $
*
*
* Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistribution of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any
* kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
* WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
* EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
* NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
* USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
* ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
* CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
* REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
* INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for
* use in the design, construction, operation or maintenance of any
* nuclear facility.
*
* $Revision: 1.1 $
* $Date: 2005-02-11 05:01:55 $
* $State: Exp $
*/
package com.sun.media.jai.imageioimpl;
import java.awt.image.renderable.ContextualRenderedImageFactory;
import javax.media.jai.CollectionImageFactory;
import javax.media.jai.OperationDescriptor;
import javax.media.jai.OperationRegistry;
import javax.media.jai.OperationRegistrySpi;
import com.sun.media.jai.operator.ImageReadDescriptor;
import com.sun.media.jai.operator.ImageWriteDescriptor;
import javax.media.jai.registry.CollectionRegistryMode;
import javax.media.jai.registry.RenderableRegistryMode;
import javax.media.jai.registry.RenderedRegistryMode;
/**
* {@link OperationRegistrySpi} implementation to register the "ImageRead"
* and "ImageWrite" operations and their associated image factories.
*/
public class ImageReadWriteSpi implements OperationRegistrySpi {
/** The name of the product to which these operations belong. */
private String productName = "com.sun.media.jai";
/** Default constructor. */
public ImageReadWriteSpi() {}
/**
* Registers the "ImageRead" and "ImageWrite" operations and their
* associated image factories across all supported operation modes.
* An {@link OperationDescriptor} is created for each operation and
* registered with the supplied {@link OperationRegistry}. An image
* factory is then created for each supported mode of each operation
* registered for that operation with the registry.
*
* @param registry The registry with which to register the operations
* and their factories.
*/
public void updateRegistry(OperationRegistry registry) {
// Create the "ImageRead" descriptor instance.
OperationDescriptor readDescriptor = new ImageReadDescriptor();
// Register the "ImageRead" descriptor.
registry.registerDescriptor(readDescriptor);
// Create the "ImageRead" CRIF.
ContextualRenderedImageFactory readCRIF = new ImageReadCRIF();
// Get the "ImageRead" operation name.
String imageReadName = readDescriptor.getName();
// Register the "ImageRead" factory for rendered mode.
registry.registerFactory(RenderedRegistryMode.MODE_NAME,
imageReadName,
productName,
readCRIF);
// Register the "ImageRead" factory for renderable mode.
registry.registerFactory(RenderableRegistryMode.MODE_NAME,
imageReadName,
productName,
readCRIF);
// Create and register the "ImageRead" factory for collection mode.
registry.registerFactory(CollectionRegistryMode.MODE_NAME,
imageReadName,
productName,
new ImageReadCIF());
// Create the "ImageWrite" descriptor instance.
OperationDescriptor writeDescriptor = new ImageWriteDescriptor();
// Register the "ImageWrite" descriptor.
registry.registerDescriptor(writeDescriptor);
// Create the "ImageWrite" CRIF.
ContextualRenderedImageFactory writeCRIF = new ImageWriteCRIF();
// Get the "ImageWrite" operation name.
String imageWriteName = writeDescriptor.getName();
// Register the "ImageWrite" factory for rendered mode.
registry.registerFactory(RenderedRegistryMode.MODE_NAME,
imageWriteName,
productName,
writeCRIF);
// Register the "ImageWrite" factory for renderable mode.
registry.registerFactory(RenderableRegistryMode.MODE_NAME,
imageWriteName,
productName,
writeCRIF);
// Create and register the "ImageWrite" factory for collection mode.
registry.registerFactory(CollectionRegistryMode.MODE_NAME,
imageWriteName,
productName,
new ImageWriteCIF());
}
}
jai-imageio-core-1.2/src/share/classes/com/sun/media/jai/operator/ 0000775 0001751 0001751 00000000000 11650556205 024060 5 ustar tille tille jai-imageio-core-1.2/src/share/classes/com/sun/media/jai/operator/package.html 0000664 0001751 0001751 00000004065 10203036165 026335 0 ustar tille tille
Provides JAI operations which read and write images using the Java Image
I/O Framework. These operations are plug-ins which are automatically loaded
using the javax.media.jai.OperationRegistrySpi
mechanism of JAI.
@since 1.0
jai-imageio-core-1.2/src/share/classes/com/sun/media/jai/operator/ImageReadDescriptor.java 0000664 0001751 0001751 00000143443 10343443200 030575 0 ustar tille tille /*
* $RCSfile: ImageReadDescriptor.java,v $
*
*
* Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistribution of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any
* kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
* WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
* EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
* NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
* USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
* ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
* CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
* REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
* INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for
* use in the design, construction, operation or maintenance of any
* nuclear facility.
*
* $Revision: 1.2 $
* $Date: 2005-12-01 00:40:32 $
* $State: Exp $
*/
package com.sun.media.jai.operator;
import java.awt.RenderingHints;
import java.awt.image.RenderedImage;
import java.awt.image.renderable.ContextualRenderedImageFactory;
import java.awt.image.renderable.ParameterBlock;
import java.awt.image.renderable.RenderableImage;
import java.io.File;
import java.io.InputStream;
import java.net.Socket;
import java.util.Collection;
import java.util.EventListener;
import java.util.Locale;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.media.jai.JAI;
import javax.media.jai.OperationDescriptorImpl;
import javax.media.jai.OperationRegistry;
import javax.media.jai.PropertyGenerator;
import javax.media.jai.RenderedOp;
import javax.media.jai.RenderableOp;
import javax.media.jai.registry.CollectionRegistryMode;
import javax.media.jai.registry.RenderableRegistryMode;
import javax.media.jai.registry.RenderedRegistryMode;
import com.sun.media.jai.util.PropertyGeneratorImpl;
/**
* An OperationDescriptor
describing the "ImageRead" operation.
*
* The "ImageRead" operation uses the * Java * Image I/O Framework to read images from an input source. Which formats * may be read depends on which {@link javax.imageio.ImageReader} plug-ins are * registered with the Image I/O Framework when the operation is invoked.
* *The input source will usually be an
* {@link javax.imageio.stream.ImageInputStream}, but may be a
* {@link java.io.File}, {@link java.io.RandomAccessFile},
* {@link java.io.InputStream}, {@link java.net.URL},
* {@link java.net.Socket}, {@link java.nio.channels.ReadableByteChannel},
* file path represented as a String
or some other type
* compatible with a reader plug-in. The
* {@link javax.imageio.ImageIO} class should be used to specify the location
* and enable the use of cache files via its setCacheDirectory()
* and setUseCache()
methods, respectively. Note that this cache
* pertains to image stream caching and is unrelated to the JAI
* TileCache
.
The "ImageRead" operation supports rendered,
* renderable, and
* collection modes and requires no source image.
* A {@link java.awt.RenderingHints} object may be supplied when the operation
* is created. In addition to the {@link java.awt.RenderingHints.Key} hints
* recognized by the eventual OpImage
constructor, an
* ImageLayout
hint may also be
* supplied. The settings of this ImageLayout
override any other
* possible derivation of its components. In particular, it is possible that
* the generated image(s) have a different tile layout than that present in
* the image read from the input source.
Image properties are used to make available metadata and other * information. Property provision is mode-specific.
* *Name | Value |
---|---|
GlobalName | ImageRead |
LocalName | ImageRead |
Vendor | com.sun.media.jai |
Description | Reads an image using the Java Image I/O Framework. |
DocURL | http://java.sun.com/products/java-media/jai/forDevelopers/jai-imageio-1_0-rc-docs/com/sun/media/jai/operator/ImageReadDescriptor.html |
Version | 1.0 |
arg0Desc | The input source. |
arg1Desc | The index or indices of the image(s) to read. |
arg2Desc | Whether metadata should be read if available. |
arg3Desc | Whether thumbnails should be read if available. |
arg4Desc | Whether to verify the validity of the input source. |
arg5Desc | EventListeners to be registered with the ImageReader. |
arg6Desc | The Locale for the ImageReader to use. |
arg7Desc | Java Image I/O read parameter instance. |
arg8Desc | Java Image I/O reader instance. |
Name | Class Type | *Default Value |
---|---|---|
* Input | java.lang.Object.class | *NO_PARAMETER_DEFAULT | *
* ImageChoice | java.lang.Integer | *0 | *
* ReadMetadata | java.lang.Boolean | *TRUE | *
* ReadThumbnails | java.lang.Boolean | *TRUE | *
* VerifyInput | java.lang.Boolean | *TRUE | *
* Listeners | java.util.EventListener[] | *null | *
* Locale | java.util.Locale | *null | *
* ReadParam | javax.imageio.ImageReadParam | *null | *
* Reader | javax.imageio.ImageReader | *null | *
The rendered mode parameters are handled as follows: * *
The foregoing policy regarding modification of any supplied ImageReadParam * or ImageReader is necessary as neither of these classes is cloneable. Given * that as a starting point there are in effect three possibilities: (A) do not * accept them as parameters, (B) accept them via alternate parameters which do * not pose these problems (for example an ImageReaderSpi and a long list of * settings represented by the ImageReadParam), or (C) accept them explicitly. * Option C has been deemed preferable despite the potential race condition * issues.
* *In the Sun Microsystems implementation of this operation these potential * conflicts have been mitigated to a certain extent: * *
Any fields of the supplied ImageLayout which are not set will be set to * default values as follows. The ImageLayout will be cloned before it is * modified.
* *Each value defaults to the corresponding value of the destination * which would be derived on the basis of the source image dimensions * and the settings of the ImageReadParam, i.e., source region, * subsampling offsets and factors, and destination offset.
* *It should be noted that unlike in the Java Image I/O API itself, * negative coordinates are permitted and the image origin is not * required to be at (0,0) as for BufferedImages. Therefore it is * possible that a given image be loaded using the same ImageReadParam * by an ImageReader and by the "ImageRead" operation with different * results. Possible differences would be that the portion of the * image with negative coordinates is not clipped as it would be with * direct Image I/O access, and no empty extent between (0,0) and the * start of the data will be present.
* *For example, if the ImageReadParam had sourceRegion [0,0,w,h], * destinationOffset [-w/2,-h/2], and no subsampling, then the Java * Image I/O API would compute the effective source and destination * regions to be [w/2,h/2,w/2,h/2] and [0,0,w/2,h/2], respectively. * The JAI ImageRead operation would compute the effective source and * destination regions to be [0,0,w,h] and [-w/2,-h/2,w,h], respectively. * The Image I/O result would therefore be equal to the bottom right * quadrant of the JAI result.
* tileGridXOffset = ImageReader.getTileGridXOffset(imageIndex); * tileGridYOffset = ImageReader.getTileGridYOffset(imageIndex); * tileWidth = ImageReader.getTileWidth(imageIndex); * tileHeight = ImageReader.getTileHeight(imageIndex); *
* ImageReader.getRawImageType(imageIndex).getColorModel(); *
* ImageReader.getRawImageType(imageIndex).getSampleModel().createCompatibleSampleModel(tileWidth, tileHeight); *
Property Name | *Type | *Comment | *
---|---|---|
JAI.ImageReadParam | *ImageReadParam | *Set to ImageReadParam actually used which may differ from the one passed in. | *
JAI.ImageReader | *ImageReader | *Set to ImageReader actually used. | *
JAI.ImageMetadata | *IIOMetadata | *Set if and only if ReadMetadata parameter is TRUE and image metadata are available. | *
JAI.StreamMetadata | *IIOMetadata | *Set if and only if ReadMetadata parameter is TRUE and stream metadata are available. | *
JAI.Thumbnails | *BufferedImage[] | *Set if and only if ReadThumbnails parameter is TRUE and thumbnails are available. | *
If a given property is not set, this implies of course that the names of * absent properties will not appear in the array returned by getPropertyNames() * and getProperty() invoked to obtain absent properties will return * java.awt.Image.UndefinedProperty as usual.
* *The ImageReader and ImageReadParam may be used for subsequent invocations * of the operation (for example to obtain different images in a multi-page file) * or for informational purposes. Care should be taken in using these property * values with respect to the synchronization issues previously discussed.
* *In all cases image metadata properties will be set when the node is rendered, * i.e., metadata reading is not subject to the same deferred execution as is * image data reading. The thumbnail property value will not be set however until * its value is actually requested.
* *It should be noted that although they are discussed in the context of * rendered mode, the parameter synchronization * policy and ImageLayout handling methodology * apply to renderable mode as well.
* *Name | Class Type | *Default Value |
---|---|---|
ImageChoice | int[] | *int[] {0,...,NumImages-1} | *
In the Sun Microsystems renderable mode implementation of the "ImageRead" * operation, when createRendering() is invoked on the RenderableImage created * by the operation, a MultiResolutionRenderableImage is constructed from a * Vector of RenderedImages consisting of the images at the specified indices. * These images will be sorted into order of decreasing resolution (as * determined by the product of width and height for each image) and inserted * in this order in the Vector of images used to construct the * MultiResolutionRenderableImage. Metadata will be set on the component * RenderedImages as usual for rendered mode. Finally the * createRendering() invocation will be forwarded to the underlying * MultiResolutionRenderableImage and the resulting RenderedImage returned.
* *Note that using this approach the entire MultiResolutionRenderableImage * must be regenerated for each invocation of createRendering(). If multiple * renderings are to be created from the RenderableImage without changing * the operation parameters, then a more efficient approach would be to use the * "JAI.RenderableInput" property to be described.
* *Property Name | *Type | *Comment | *
---|---|---|
JAI.RenderableInput | *RenderableImage | *A RenderableImage derived from the input source according to the supplied set of parameters. | *
The RenderableImage which is the value of the foregoing property may have * set on it any of the properties previously described for rendered mode * contingent on parameter settings and data availability. The image metadata * and thumbnail properties would be copied from the highest resolution image * among those specified by the ImageChoice parameter.
* *If multiple renderings are to be created from the RenderableImage * without changing the operation parameters, then an efficient alternative * approach to multiple invocations of createRendering() on the RenderableImage * is to obtain the RenderableImage value of the "JAI.RenderableInput" property * and invoke createRendering() on this value.
* *Collection
of RenderedImage
s from the specified
* input source. This could be used for example to load an animated GIF
* image or a multi-page TIFF image.
*
* It should be noted that although they are discussed in the context of * rendered mode, the parameter synchronization * policy and ImageLayout handling methodology * apply to collection mode as well.
* *ParameterBlock
* and invokes {@link JAI#create(String,ParameterBlock,RenderingHints)}.
*
* @param input The input source.
* @param imageChoice The index of the image to read.
* @param readMetadata Whether metadata should be read if available.
* @param readThumbnails Whether thumbnails should be read if available.
* @param verifyInput Whether to verify the validity of the input source.
* @param listeners EventListeners to be registered with the ImageReader.
* @param locale The Locale for the ImageReader to use.
* @param readParam Java Image I/O read parameter instance.
* @param reader Java Image I/O reader instance.
* @param hints Hints possibly including an ImageLayout
.
* @return an image derived from the input source.
*/
public static RenderedOp create(ImageInputStream input,
Integer imageChoice,
Boolean readMetadata,
Boolean readThumbnails,
Boolean verifyInput,
EventListener[] listeners,
Locale locale,
ImageReadParam readParam,
ImageReader reader,
RenderingHints hints) {
ParameterBlock args = new ParameterBlock();
args.add(input);
args.add(imageChoice);
args.add(readMetadata);
args.add(readThumbnails);
args.add(verifyInput);
args.add(listeners);
args.add(locale);
args.add(readParam);
args.add(reader);
return JAI.create(OPERATION_NAME, args, hints);
}
/**
* Type-safe convenience method for creating a {@link Collection}
* representing the "ImageRead" operation in collection mode. The
* method packs the parameters into a new ParameterBlock
* and invokes
* {@link JAI#createCollection(String,ParameterBlock, RenderingHints)}.
*
* @param input The input source.
* @param imageChoice The indices of the images to read.
* @param readMetadata Whether metadata should be read if available.
* @param readThumbnails Whether thumbnails should be read if available.
* @param verifyInput Whether to verify the validity of the input source.
* @param listeners EventListeners to be registered with the ImageReader.
* @param locale The Locale for the ImageReader to use.
* @param readParam Java Image I/O read parameter instance.
* @param reader Java Image I/O reader instance.
* @param hints Hints possibly including an ImageLayout
.
* @return a collection of images derived from the input source.
*/
public static Collection createCollection(ImageInputStream input,
int[] imageChoice,
Boolean readMetadata,
Boolean readThumbnails,
Boolean verifyInput,
EventListener[] listeners,
Locale locale,
ImageReadParam readParam,
ImageReader reader,
RenderingHints hints) {
ParameterBlock args = new ParameterBlock();
args.add(input);
args.add(imageChoice);
args.add(readMetadata);
args.add(readThumbnails);
args.add(verifyInput);
args.add(listeners);
args.add(locale);
args.add(readParam);
args.add(reader);
return JAI.createCollection(OPERATION_NAME, args, hints);
}
/**
* Type-safe convenience method for creating a {@link RenderableOp}
* representing the "ImageRead" operation in renderable mode. The
* method packs the parameters into a new ParameterBlock
* and invokes
* {@link JAI#createRenderable(String,ParameterBlock,RenderingHints)}.
*
* @param input The input source.
* @param imageChoice The indices of the images to read.
* @param readMetadata Whether metadata should be read if available.
* @param readThumbnails Whether thumbnails should be read if available.
* @param verifyInput Whether to verify the validity of the input source.
* @param listeners EventListeners to be registered with the ImageReader.
* @param locale The Locale for the ImageReader to use.
* @param readParam Java Image I/O read parameter instance.
* @param reader Java Image I/O reader instance.
* @param hints Hints possibly including an ImageLayout
.
* @return an image capable of rendering an image from those in the
* input source.
*/
public static RenderableOp createRenderable(ImageInputStream input,
int[] imageChoice,
Boolean readMetadata,
Boolean readThumbnails,
Boolean verifyInput,
EventListener[] listeners,
Locale locale,
ImageReadParam readParam,
ImageReader reader,
RenderingHints hints) {
ParameterBlock args = new ParameterBlock();
args.add(input);
args.add(imageChoice);
args.add(readMetadata);
args.add(readThumbnails);
args.add(verifyInput);
args.add(listeners);
args.add(locale);
args.add(readParam);
args.add(reader);
return JAI.createRenderable(OPERATION_NAME, args, hints);
}
/**
* Returns the array of {@link PropertyGenerator}s for the specified
* mode of this operation.
*
* For renderable mode returns an array containing a single
* PropertyGenerator
which defines a
* {@link RenderableImage}-valued property named "JAI.RenderableInput".
* For all other modes null
is returned.
PropertyGenerator
* if modeName
is "renderable" (case-insensitive) or
* null
otherwise.
*/
public PropertyGenerator[] getPropertyGenerators(String modeName) {
return modeName.equalsIgnoreCase(RenderableRegistryMode.MODE_NAME) ?
new PropertyGenerator[] { new ImageReadPropertyGenerator() } :
null;
}
/**
* Validates the parameters in the supplied ParameterBlock
.
*
* In addition to the standard validation performed by the * corresponding superclass method, this method verifies the following: *
TRUE
and Input
* is a File
or String
, whether the
* corresponding physical file exists and is readable; andTRUE
and Input
* is a String
, converting which to a
* corresponding physical file failed, whether it can be converted
* to an InputStream accessed as a resource from a JAR file; andTRUE
and Input
* is a Socket
, whether it is bound, connected, open,
* and the read-half is not shut down.msg
and
* false
will be returned; otherwise true
will
* be returned.
*
* The file existence and readability verification may be suppressed
* by setting the VerifyInput parameter to FALSE
.
* This might be desirable for example if the operation is being
* created for remote rendering and Input is a file which is at
* a location visible on the remote peer but not on the host on which
* the operation is created.
OperationDescriptor
describing the "ImageWrite" operation.
*
* The "ImageWrite" operation uses the * Java * Image I/O Framework to write images to an output destination. Which * formats may be written depends on which {@link javax.imageio.ImageWriter} * plug-ins are registered with the Image I/O Framework when the operation is * invoked.
* *The output destination will usually be an
* {@link javax.imageio.stream.ImageOutputStream}, but may be a
* {@link java.io.File}, {@link java.io.RandomAccessFile},
* {@link java.io.OutputStream}, {@link java.net.Socket},
* {@link java.nio.channels.WritableByteChannel}, file path represented as a
* String
or some other type compatible with a writer plug-in. The
* {@link javax.imageio.ImageIO} class should be used to specify the location
* and enable the use of cache files via its setCacheDirectory()
* and setUseCache()
methods, respectively. Note that this cache
* pertains to image stream caching and is unrelated to the JAI
* TileCache
. If an {@link javax.imageio.stream.ImageOutputStream}
* is created internally by the operation, for example from a
* {@link java.io.File}-valued Output parameter,
* then it will be flushed automatically if and only if the operation is not
* in collection mode and pixel replacement is
* not occurring.
The "ImageWrite" operation supports rendered,
* renderable, and
* collection modes and requires a single
* source. The operation is "immediate" for all modes as specified by
* OperationDescriptor.isImmediate()
so that
* {@link #isImmediate()} returns true
. The operation will
* therefore be rendered when created via either JAI.create[NS]()
* or JAI.createCollection[NS]()
.
* A {@link java.awt.RenderingHints} object supplied when the
* operation is created will have no effect except with respect to the
* mapping of JAI.KEY_INTERPOLATION
and then only in renderable
* mode.
Image properties are used to pass metadata and other information to the * writer plug-in and to make available metadata as actually written to the * output destination. Property handling is mode-specific.
* *Name | Value |
---|---|
GlobalName | ImageWrite |
LocalName | ImageWrite |
Vendor | com.sun.media.jai |
Description | Writes an image using the Java Image I/O Framework. |
DocURL | http://java.sun.com/products/java-media/jai/forDevelopers/jai-imageio-1_0-rc-docs/com/sun/media/jai/operator/ImageWriteDescriptor.html |
Version | 1.0 |
arg0Desc | The output destination. |
arg1Desc | The format name of the output. |
arg2Desc | Whether to use image metadata properties as fallbacks. |
arg3Desc | Whether to transcode metadata before writing. |
arg4Desc | Whether to verify the validity of the output destination. |
arg5Desc | Whether to allow pixel replacement in the output image. |
arg6Desc | The tile size of the output image. |
arg7Desc | Stream metadata to write to the output. |
arg8Desc | Image metadata to write to the output. |
arg9Desc | Thumbnails to write to the output. |
arg10Desc | EventListeners to be registered with the ImageWriter. |
arg11Desc | The Locale for the ImageWriter to use. |
arg12Desc | Java Image I/O write parameter instance. |
arg13Desc | Java Image I/O writer instance. |
Name | Class Type | *Default Value |
---|---|---|
* Output | java.lang.Object.class | *NO_PARAMETER_DEFAULT | *
* Format | java.lang.String | *null | *
* UseProperties | java.lang.Boolean | *TRUE | *
* Transcode | java.lang.Boolean | *TRUE | *
* VerifyOutput | java.lang.Boolean | *TRUE | *
* AllowPixelReplacement | java.lang.Boolean | *FALSE | *
* TileSize | java.awt.Dimension | *null | *
* StreamMetadata | javax.imageio.metadata.IIOMetadata | *null | *
* ImageMetadata | javax.imageio.metadata.IIOMetadata | *null | *
* Thumbnails | java.awt.BufferedImage[] | *null | *
* Listeners | java.util.EventListener[] | *null | *
* Locale | java.util.Locale | *null | *
* WriteParam | javax.imageio.ImageWriteParam | *null | *
* Writer | javax.imageio.ImageWriter | *null | *
The rendered mode parameters are handled as follows: * *
In the Sun Microsystems implementation of this operation these potential * conflicts have been mitigated to a certain extent: * *
* if ImageWriter cannot write tiles * output is untiled * else * if TileSize parameter is non-null * set tile size to TileSize * else * if WriteParam is null * set tile size to source tile size * else * if tilingMode is ImageWriteParam.MODE_EXPLICIT * if tile dimension is set in WriteParam * set tile size to tile dimension from WriteParam * else * if preferred tile dimension is set in WriteParam * set tile size to average of first two preferred dimensions * else * set tile size to source tile size * else // tilingMode is not ImageWriteParam.MODE_EXPLICIT * the plug-in decides the tile size ** * There is no mechanism to set the tile grid offsets of the output. * *
Note that this behavior differs from what would happen if the RenderedOp * created by the operation received a RenderingChangeEvent: in this case a * new rendering of the node would be created using the ParameterBlock and * RenderingHints currently in effect. This would cause the entire image to be * rewritten at the current position of the output. This will also happen * when AllowPixelReplacement is FALSE. In effect in both of these cases the * behavior in response to a RenderingChangeEvent is unspecified and the result * will likely be unexpected.
* *To avoid any inadvertent overwriting of the destination as a result of * events received by the RenderedOp, the following usage is recommended when * the objective is automatic pixel replacement: * *
* // Sources, parameters, and hints. * ParameterBlock args; * RenderingHints hints; * * // Create the OperationNode. * RenderedOp imageWriteNode = JAI.create("ImageWrite", args, hints); * * // Get the rendering which already exists due to "immediate" status. * RenderedImage imageWriteRendering = imageWriteNode.getRendering(); * * // Unhook the OperationNode as a sink of its source OperationNode. * imageWriteNode.getSourceImage(0).removeSink(imageWriteNode); * * // Add the rendering as a sink of the source OperationNode. * imageWriteNode.getSourceImage(0).addSink(imageWriteRendering); * * // Free the OperationNode for garbage collection. * imageWriteNode = null; ** * At this point a reference to imageWriteRendering must be held as long as the * data of the source of the operation may change. Then provided the events are * correctly propagated to imageWriteRendering, the data in the output file * will be automatically updated to match the source data. * *
If pixel replacement is not the objective and inadvertent overwriting is * to be avoided then the safest approach would be the following: * *
* // Create the OperationNode. * RenderedOp imageWriteNode = JAI.create("ImageWrite", args, hints); * * // Unhook the OperationNode as a sink of its source * imageWriteNode.getSourceImage(0).removeSink(imageWriteNode); ** * The image is written by the first statement and no reference to the * rendering need be retained as before. * *
Property Name | *Type | *Comment | *
---|---|---|
JAI.ImageWriteParam | *ImageWriteParam | *Set to ImageWriteParam actually used which may differ from the one passed in. | *
JAI.ImageWriter | *ImageWriter | *Set to ImageWriter actually used. | *
JAI.ImageMetadata | *IIOMetadata | *Set if and only if image metadata are available; may be transcoded. | *
JAI.StreamMetadata | *IIOMetadata | *Set if and only if stream metadata are available; may be transcoded. | *
JAI.Thumbnails | *BufferedImage[] | *Set if and only thumbnails are provided and the writer supportes writing them. | *
If a given property is not set, this implies of course that the names of * absent properties will not appear in the array returned by getPropertyNames() * and getProperty() invoked to obtain absent properties will return * java.awt.Image.UndefinedProperty as usual.
* *The ImageWriter and ImageWriteParam may be used for subsequent invocations * of the operation or for informational purposes. Care should be taken in using * these property values with respect to the synchronization issues previously * discussed.
* *Metadata properties will be set to those actually written to the output. They * may be derived either from input parameters or source properties depending on * the values of the StreamMetadata, ImageMetadata, and UseProperties parameters. * They will be transcoded data if Transcode is TRUE and the ImageWriter supports * transcoding.
* *All properties will be set when the node is rendered.
* *JAI.KEY_INTERPOLATION
is supplied via a
* RenderingHints
passed to the operation, then the interpolation
* type it specifies will be used to create the rendering if interpolation is
* required.
*
* The Collection is treated as a sequence of images which will be * extracted from the Collection in the order returned by a new Iterator. * Elements in the Collection which are not RenderedImages will be ignored. * The derived sequence of images will then be written to the output.
* *If there is only one RenderedImage in the source Collection, this image * will be written as done in rendered mode operation. If there is more than * one RenderedImage, the sequence of RenderedImages will be written as an * image sequence. In the latter case the ImageWriter must be able to write * sequences.
* *Name | Class Type | *Default Value |
---|---|---|
ImageMetadata | javax.imageio.metadataIIOMetadata[] | *null | *
Thumbnails | java.awt.image.BufferedImage[][] | *null | *
* The change to the ImageMetadata and Thumbnails parameters is that there can * now be a distinct image metadata object and thumbnail array for each image * in the Collection. The components of these respective arrays will be indexed * using the sequence of RenderedImages extracted from the source Collection by * the Iterator. It is the responsibility of the caller to ensure that this * sequencing is correct. In this context it is advisable to use a source * Collection which maintains the order of its elements such as a List. *
* ** To ensure proper termination of the image sequence and avoid any inadvertent * overwriting of the destination as a result of events received by the * CollectionOp, the following usage is recommended when the objective is * automatic pixel replacement: * *
* // Sources, parameters, and hints. * ParameterBlock args; * RenderingHints hints; * * // Create the Collection. * CollectionImage imageWriteCollection = * (CollectionImage)JAI.createCollection("ImageWrite", args, hints); * * // Unhook the Collection node from the source to avoid * // re-renderings caused by CollectionChangeEvents. * if(args.getSource(0) instanceof CollectionImage) { * CollectionImage sourceCollection = * (CollectionImage)args.getSource(0); * sourceCollection.removeSink(imageWriteCollection); * } * * // !!! Pixel replacement activity happens here ... !!! * * // Get the ImageWriter. * ImageWriter writer = * (ImageWriter)imageWriteCollection.getProperty("JAI.ImageWriter"); * * // End the sequence if necessary. * if(writer.canWriteSequence()) { * writer.endWriteSequence(); * } ** * *
* Using the foregoing construct, all pixels in all images written to the output * sequence will remain current with the in-memory data of their respective * source provided all events are propagated as expected. Note that it is not * necessary to end the sequence manually if pixel replacement is not allowed or * is not supported. Also the sequence must be manually ended if and only if the * writer is capable of writing sequences. This permits pixel replacement to * work in the case where the source collection contains only a single image * and the writer supports pixel replacement but cannot write sequences. *
* ** If pixel replacement is not the objective, i.e., AllowPixelReplacement is * FALSE, and inadvertent overwriting is to be avoided then the safest approach * would be the following: * *
* // Create the Collection. * Collection imageWriteCollection = * JAI.create("ImageWrite", args, hints); * * // Unhook the Collection node from the source to avoid * // re-renderings caused by CollectionChangeEvents. * if(args.getSource(0) instanceof CollectionImage) { * CollectionImage sourceCollection = * (CollectionImage)args.getSource(0); * sourceCollection.removeSink(imageWriteCollection); * } ** * The image is written by the first statement and no reference to the * rendering need be retained. * *
ParameterBlock
and invokes
* {@link JAI#create(String,ParameterBlock,RenderingHints)}.
*
* @param source The image to be written.
* @param output The output destination.
* @param format The format name of the output.
* @param useProperties Whether to use image metadata properties as
* fallbacks.
* @param transcode Whether to transcode metadata before writing.
* @param verifyOutput Whether to verify the validity of the output
* destination.
* @param allowPixelReplacement Whether to allow pixel replacement
* in the output image.
* @param tileSize The tile size of the output image.
* @param streamMetadata Stream metadata to write to the output.
* @param imageMetadata Image metadata to write to the output.
* @param thumbnails Thumbnails to write to the output.
* @param listeners EventListeners to be registered with the ImageWriter.
* @param locale The Locale for the ImageWriter to use.
* @param writeParam Java Image I/O write parameter instance.
* @param writer Java Image I/O writer instance.
* @param hints Operation hints.
* @return a reference to the operation source.
*/
public static RenderedOp create(RenderedImage source,
ImageOutputStream output,
String format,
Boolean useProperties,
Boolean transcode,
Boolean verifyOutput,
Boolean allowPixelReplacement,
Dimension tileSize,
IIOMetadata streamMetadata,
IIOMetadata imageMetadata,
BufferedImage[] thumbnails,
EventListener[] listeners,
Locale locale,
ImageWriteParam writeParam,
ImageWriter writer,
RenderingHints hints) {
ParameterBlock args = new ParameterBlock();
args.addSource(source);
args.add(output);
args.add(format);
args.add(useProperties);
args.add(transcode);
args.add(verifyOutput);
args.add(allowPixelReplacement);
args.add(tileSize);
args.add(streamMetadata);
args.add(imageMetadata);
args.add(thumbnails);
args.add(listeners);
args.add(locale);
args.add(writeParam);
args.add(writer);
return JAI.create(OPERATION_NAME, args, hints);
}
/**
* Type-safe convenience method for creating a {@link Collection}
* representing the "ImageWrite" operation in collection mode. The
* method packs the source and parameters into a new
* ParameterBlock
and invokes
* {@link JAI#createCollection(String,ParameterBlock,RenderingHints)}.
*
* @param source The collection to be written.
* @param output The output destination.
* @param format The format name of the output.
* @param useProperties Whether to use image metadata properties as
* fallbacks.
* @param transcode Whether to transcode metadata before writing.
* @param verifyOutput Whether to verify the validity of the output
* destination.
* @param allowPixelReplacement Whether to allow pixel replacement
* in the output image.
* @param tileSize The tile size of the output image.
* @param streamMetadata Stream metadata to write to the output.
* @param imageMetadata Image metadata to write to the output.
* @param thumbnails Thumbnails to write to the output.
* @param listeners EventListeners to be registered with the ImageWriter.
* @param locale The Locale for the ImageWriter to use.
* @param writeParam Java Image I/O write parameter instance.
* @param writer Java Image I/O writer instance.
* @param hints Operation hints.
* @return a reference to the operation source.
*/
public static Collection createCollection(Collection source,
ImageOutputStream output,
String format,
Boolean useProperties,
Boolean transcode,
Boolean verifyOutput,
Boolean allowPixelReplacement,
Dimension tileSize,
IIOMetadata streamMetadata,
IIOMetadata[] imageMetadata,
BufferedImage[][] thumbnails,
EventListener[] listeners,
Locale locale,
ImageWriteParam writeParam,
ImageWriter writer,
RenderingHints hints) {
ParameterBlock args = new ParameterBlock();
args.addSource(source);
args.add(output);
args.add(format);
args.add(useProperties);
args.add(transcode);
args.add(verifyOutput);
args.add(allowPixelReplacement);
args.add(tileSize);
args.add(streamMetadata);
args.add(imageMetadata);
args.add(thumbnails);
args.add(listeners);
args.add(locale);
args.add(writeParam);
args.add(writer);
return JAI.createCollection(OPERATION_NAME, args, hints);
}
/**
* Type-safe convenience method for creating a {@link RenderableOp}
* representing the "ImageWrite" operation in renderable mode. The
* method packs the source and parameters into a new
* ParameterBlock
and invokes
* {@link JAI#createRenderable(String,ParameterBlock,RenderingHints)}.
*
* @param source The renderable source to be written.
* @param output The output destination.
* @param format The format name of the output.
* @param useProperties Whether to use image metadata properties as
* fallbacks.
* @param transcode Whether to transcode metadata before writing.
* @param verifyOutput Whether to verify the validity of the output
* destination.
* @param allowPixelReplacement Whether to allow pixel replacement
* in the output image.
* @param tileSize The tile size of the output image.
* @param streamMetadata Stream metadata to write to the output.
* @param imageMetadata Image metadata to write to the output.
* @param thumbnails Thumbnails to write to the output.
* @param listeners EventListeners to be registered with the ImageWriter.
* @param locale The Locale for the ImageWriter to use.
* @param writeParam Java Image I/O write parameter instance.
* @param writer Java Image I/O writer instance.
* @param hints Operation hints.
* @return a reference to the operation source.
*/
public static RenderableOp createRenderable(RenderableImage source,
ImageOutputStream output,
String format,
Boolean useProperties,
Boolean transcode,
Boolean verifyOutput,
Boolean allowPixelReplacement,
Dimension tileSize,
IIOMetadata streamMetadata,
IIOMetadata imageMetadata,
BufferedImage[] thumbnails,
EventListener[] listeners,
Locale locale,
ImageWriteParam writeParam,
ImageWriter writer,
RenderingHints hints) {
ParameterBlock args = new ParameterBlock();
args.addSource(source);
args.add(output);
args.add(format);
args.add(useProperties);
args.add(transcode);
args.add(verifyOutput);
args.add(allowPixelReplacement);
args.add(tileSize);
args.add(streamMetadata);
args.add(imageMetadata);
args.add(thumbnails);
args.add(listeners);
args.add(locale);
args.add(writeParam);
args.add(writer);
return JAI.createRenderable(OPERATION_NAME, args, hints);
}
/**
* Returns true indicating that the operation should be rendered
* immediately during a call to JAI.create[]()
or
* JAI.createCollection[NS]()
.
*
* @see javax.media.jai.OperationDescriptor
*/
public boolean isImmediate() {
return true;
}
/**
* Validates the parameters in the supplied ParameterBlock
.
*
* In addition to the standard validation performed by the * corresponding superclass method, this method verifies the following: *
TRUE
and Output
* is a File
or String
, whether the
* corresponding physical file is writable, i.e., exists and may
* be overwritten or does not exist and may be created; andTRUE
and Output
* is a Socket
, whether it is bound, connected, open,
* and the write-half is not shut down; andmodeName
equals
* {@link CollectionRegistryMode#MODE_NAME}), the source is not a
* {@link CollectionOp}, and the size of the source
* {@link Collection} is greater than unity, whether the
* {@link ImageWriter} cannot write sequences.msg
and
* false
will be returned; otherwise true
will
* be returned.
*
* @param modeName The operation mode.
* @param args The source and parameters of the operation.
* @param msg A container for any error messages.
*
* @return Whether the supplied parameters are valid.
*/
protected boolean validateParameters(String modeName,
ParameterBlock args,
StringBuffer msg) {
if (!super.validateParameters(modeName, args, msg)) {
return false;
}
// Get the Output parameter.
Object output = args.getObjectParameter(0);
// Check the output if so requested by "VerifyOutput".
Boolean verifyOutput = (Boolean)args.getObjectParameter(4);
if (verifyOutput.booleanValue()){
if(output instanceof File || output instanceof String) {
// Set file and path variables.
File file = null;
String path = null;
if(output instanceof File) {
file = (File)output;
path = file.getPath();
} else if(output instanceof String) {
path = (String)output;
file = new File(path);
}
// Perform non-destructive test that the file
// may be created and written.
try {
if (file.exists()) {
if (!file.canWrite()) {
// Cannot write to existing file.
msg.append(file.getPath() + " " +
I18N.getString("ImageWriteDescriptor15"));
return false;
}
} else {
if (!file.createNewFile()) {
// Cannot create file.
msg.append(file.getPath() + " " +
I18N.getString("ImageWriteDescriptor16"));
return false;
}
file.delete();
}
} catch (IOException ioe) {
// I/O exception during createNewFile().
msg.append(file.getPath() + " " +
I18N.getString("ImageWriteDescriptor17") + " " +
ioe.getMessage());
return false;
} catch (SecurityException se) {
// Security exception during exists(), canWrite(),
// createNewFile(), or delete().
msg.append(file.getPath() + " " +
I18N.getString("ImageWriteDescriptor18") + " " +
se.getMessage());
return false;
}
} else if(output instanceof Socket) {
Socket socket = (Socket)output;
if(socket.isOutputShutdown()) {
msg.append("\"" + socket + "\": " +
I18N.getString("ImageWriteDescriptor19"));
return false;
} else if(socket.isClosed()) {
msg.append("\"" + socket + "\": " +
I18N.getString("ImageWriteDescriptor20"));
return false;
} else if(!socket.isBound()) {
msg.append("\"" + socket + "\": " +
I18N.getString("ImageWriteDescriptor21"));
return false;
} else if(!socket.isConnected()) {
msg.append("\"" + socket + "\": " +
I18N.getString("ImageWriteDescriptor22"));
return false;
}
}
}
// Get the Format parameter.
String format = (String)args.getObjectParameter(1);
// Get the ImageWriter parameter.
ImageWriter writer = (ImageWriter)args.getObjectParameter(13);
if(format == null) {
// Attempt to get the format from the ImageWriter provider.
if(writer != null) {
// Get the SPI.
ImageWriterSpi spi = writer.getOriginatingProvider();
// Set from the SPI.
if(spi != null) {
format = spi.getFormatNames()[0];
}
}
// Attempt to deduce the format from the file suffix.
if(format == null &&
(output instanceof File || output instanceof String)) {
// Set the file name string.
String name = output instanceof File ?
((File)output).getName() : (String)output;
// Extract the suffix.
String suffix = name.substring(name.lastIndexOf(".") + 1);
// Get the writers of that suffix.
Iterator writers = ImageIO.getImageWritersBySuffix(suffix);
if(writers != null) {
// Get the first writer.
writer = (ImageWriter)writers.next();
if(writer != null) {
// Get the SPI.
ImageWriterSpi spi = writer.getOriginatingProvider();
// Set from the SPI.
if(spi != null) {
format = spi.getFormatNames()[0];
}
}
}
}
// Default to the most versatile core Java Image I/O writer.
if(format == null) {
format = "PNG";
}
// Replace the format setting.
if(format != null) {
args.set(format, 1);
}
}
// Check the tile size parameter if present.
Dimension tileSize = (Dimension)args.getObjectParameter(6);
if(tileSize != null && (tileSize.width <= 0 || tileSize.height <= 0)) {
msg.append(I18N.getString("ImageWriteDescriptor23"));
return false;
}
// For collection mode, verify that the source collection contains
// at least one RenderedImage and that the writer can handle sequences
// if there is more than one RenderedImage in the source collection.
if(modeName.equalsIgnoreCase(CollectionRegistryMode.MODE_NAME)) {
// Get the source collection.
Collection source = (Collection)args.getSource(0);
// If the source collection is a CollectionOp do not perform this
// check as invoking source.size() will render the node.
if(!(source instanceof CollectionOp)) {
// Determine the number of RenderedImages in the Collection.
int numRenderedImages = 0;
Iterator iter = source.iterator();
while(iter.hasNext()) {
if(iter.next() instanceof RenderedImage) {
numRenderedImages++;
}
}
if(numRenderedImages == 0) {
msg.append(I18N.getString("ImageWriteDescriptor24"));
return false;
} else if(numRenderedImages > 1) {
// Get the writer parameter.
writer = (ImageWriter)args.getObjectParameter(13);
// If the parameter writer is null, get one based on the
// format.
if(writer == null && format != null) {
// Get the writers of that format.
Iterator writers =
ImageIO.getImageWritersByFormatName(format);
if(writers != null) {
// Get the first writer.
writer = (ImageWriter)writers.next();
}
}
if(writer != null) {
// Check that the writer can write sequences.
if(!writer.canWriteSequence()) {
msg.append(I18N.getString("ImageWriteDescriptor25"));
return false;
}
}
}
}
}
return true;
}
}
jai-imageio-core-1.2/src/share/classes/com/sun/media/jai/operator/properties 0000664 0001751 0001751 00000005523 10203036165 026173 0 ustar tille tille #
# $RCSfile: properties,v $
#
# Copyright (c) 2005 Sun Microsystems, Inc. All rights reserved.
#
# Use is subject to license terms.
#
# $Revision: 1.1 $
# $Date: 2005-02-11 05:01:57 $
# $State: Exp $
#
# Internationalization file for com.sun.media.jai.operator
DescriptorVersion=1.0
ImageReadDescriptor0=Reads an image using the Java Image I/O Framework.
ImageReadDescriptor1=The input source.
ImageReadDescriptor2=The index or indices of the image(s) to read.
ImageReadDescriptor3=Whether metadata should be read if available.
ImageReadDescriptor4=Whether thumbnails should be read if available.
ImageReadDescriptor5=Whether to verify the validity of the input source.
ImageReadDescriptor6=EventListeners to be registered with the ImageReader.
ImageReadDescriptor7=The Locale for the ImageReader to use.
ImageReadDescriptor8=Java Image I/O read parameter instance.
ImageReadDescriptor9=Java Image I/O reader instance.
ImageReadDescriptor10=Image index parameter must be non-negative.
ImageReadDescriptor11=does not exist.
ImageReadDescriptor12=is not readable.
ImageReadDescriptor13=has its read-half shut down.
ImageReadDescriptor14=is closed.
ImageReadDescriptor15=is not bound to an address.
ImageReadDescriptor16=is not connected.
ImageWriteDescriptor0=Writes an image using the Java Image I/O Framework.
ImageWriteDescriptor1=The output destination.
ImageWriteDescriptor2=The format name of the output.
ImageWriteDescriptor3=Whether to use image metadata properties as fallbacks.
ImageWriteDescriptor4=Whether to transcode metadata before writing.
ImageWriteDescriptor5=Whether to verify the validity of the output destination.
ImageWriteDescriptor6=Whether to allow pixel replacement in the output image.
ImageWriteDescriptor7=The tile size of the output image.
ImageWriteDescriptor8=Stream metadata to write to the output.
ImageWriteDescriptor9=Image metadata to write to the output.
ImageWriteDescriptor10=Thumbnails to write to the output.
ImageWriteDescriptor11=EventListeners to be registered with the ImageWriter.
ImageWriteDescriptor12=The Locale for the ImageWriter to use.
ImageWriteDescriptor13=Java Image I/O write parameter instance.
ImageWriteDescriptor14=Java Image I/O writer instance.
ImageWriteDescriptor15=exists but is not writable.
ImageWriteDescriptor16=does not exist and cannot be created.
ImageWriteDescriptor17=encountered IOException during createNewFile:
ImageWriteDescriptor18=access denied by security manager:
ImageWriteDescriptor19=has its write-half shut down.
ImageWriteDescriptor20=is closed.
ImageWriteDescriptor21=is not bound to an address.
ImageWriteDescriptor22=is not connected.
ImageWriteDescriptor23=Non-positive tile dimension specified.
ImageWriteDescriptor24=No RenderedImages in the source Collection.
ImageWriteDescriptor25=There is more than one RenderedImage in the source \
Collection and the supplied ImageWriter cannot write sequences.
jai-imageio-core-1.2/src/share/classes/com/sun/media/jai/operator/PrintProps.java 0000664 0001751 0001751 00000006615 10203036165 027042 0 ustar tille tille /*
* $RCSfile: PrintProps.java,v $
*
*
* Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistribution of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any
* kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
* WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
* EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
* NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
* USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
* ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
* CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
* REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
* INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for
* use in the design, construction, operation or maintenance of any
* nuclear facility.
*
* $Revision: 1.1 $
* $Date: 2005-02-11 05:01:57 $
* $State: Exp $
*/
package com.sun.media.jai.operator;
import java.util.Collection;
import java.util.Iterator;
import javax.media.jai.PropertySource;
final class PrintProps {
static final void print(PropertySource ps) {
String[] propNames = ps.getPropertyNames();
if(propNames != null) {
System.out.println("\nPROPERTIES OF "+
ps.getClass().getName()+"@"+
ps.hashCode()+":\n");
for(int j = 0; j < propNames.length; j++) {
Object propVal = ps.getProperty(propNames[j]);
if(propVal == null) {
System.out.println(propNames[j]+" is NULL.");
} else if(propVal == java.awt.Image.UndefinedProperty) {
System.out.println(propNames[j]+" is UNDEFINED.");
} else {
System.out.println(propNames[j]+" = "+
propVal.getClass().getName()+"@"+
propVal.hashCode());
}
}
} else {
System.out.println("\n"+ps+" has no properties.");
}
System.out.println("\n");
if(ps instanceof Collection) {
Iterator iter = ((Collection)ps).iterator();
while(iter.hasNext()) {
Object nextElement = iter.next();
if(nextElement instanceof PropertySource) {
print((PropertySource)nextElement);
}
}
}
}
}
jai-imageio-core-1.2/src/share/classes/com/sun/media/jai/operator/I18N.java 0000664 0001751 0001751 00000004160 10203036165 025372 0 ustar tille tille /*
* $RCSfile: I18N.java,v $
*
*
* Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistribution of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any
* kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
* WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
* EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
* NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
* USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
* ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
* CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
* REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
* INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for
* use in the design, construction, operation or maintenance of any
* nuclear facility.
*
* $Revision: 1.1 $
* $Date: 2005-02-11 05:01:56 $
* $State: Exp $
*/
package com.sun.media.jai.operator;
import com.sun.media.imageioimpl.common.I18NImpl;
final class I18N extends I18NImpl {
static String getString(String key) {
return getString("com.sun.media.jai.operator.I18N", key);
}
}
jai-imageio-core-1.2/src/share/classes/com/sun/media/imageioimpl/ 0000775 0001751 0001751 00000000000 11650556211 023753 5 ustar tille tille jai-imageio-core-1.2/src/share/classes/com/sun/media/imageioimpl/common/ 0000775 0001751 0001751 00000000000 11650556211 025243 5 ustar tille tille jai-imageio-core-1.2/src/share/classes/com/sun/media/imageioimpl/common/InvertedCMYKColorSpace.java 0000664 0001751 0001751 00000010665 10423235255 032334 0 ustar tille tille /*
* $RCSfile: InvertedCMYKColorSpace.java,v $
*
*
* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistribution of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any
* kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
* WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
* EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
* NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
* USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
* ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
* CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
* REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
* INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for
* use in the design, construction, operation or maintenance of any
* nuclear facility.
*
* $Revision: 1.1 $
* $Date: 2006-04-24 20:53:01 $
* $State: Exp $
*/
package com.sun.media.imageioimpl.common;
import java.awt.color.ColorSpace;
/**
* Singleton class representing a simple, mathematically defined
* inverted CMYK color space.
*/
public final class InvertedCMYKColorSpace extends ColorSpace {
private static ColorSpace theInstance = null;
private ColorSpace csRGB;
/** The exponent for gamma correction. */
private static final double power1 = 1.0 / 2.4;
public static final synchronized ColorSpace getInstance() {
if(theInstance == null) {
theInstance = new InvertedCMYKColorSpace();
}
return theInstance;
}
private InvertedCMYKColorSpace() {
super(TYPE_CMYK, 4);
csRGB = ColorSpace.getInstance(ColorSpace.CS_LINEAR_RGB);
}
public boolean equals(Object o) {
return o != null && o instanceof InvertedCMYKColorSpace;
}
public float[] toRGB(float[] colorvalue) {
float C = colorvalue[0];
float M = colorvalue[1];
float Y = colorvalue[2];
float K = colorvalue[3];
// Convert from CMYK to linear RGB.
float[] rgbvalue = new float[] {K*C, K*M, K*Y};
// Convert from linear RGB to sRGB.
for (int i = 0; i < 3; i++) {
float v = rgbvalue[i];
if (v < 0.0F) v = 0.0F;
if (v < 0.0031308F) {
rgbvalue[i] = 12.92F * v;
} else {
if (v > 1.0F) v = 1.0F;
rgbvalue[i] = (float)(1.055 * Math.pow(v, power1) - 0.055);
}
}
return rgbvalue;
}
public float[] fromRGB(float[] rgbvalue) {
// Convert from sRGB to linear RGB.
for (int i = 0; i < 3; i++) {
if (rgbvalue[i] < 0.040449936F) {
rgbvalue[i] /= 12.92F;
} else {
rgbvalue[i] =
(float)(Math.pow((rgbvalue[i] + 0.055)/1.055, 2.4));
}
}
// Convert from linear RGB to CMYK.
float C = rgbvalue[0];
float M = rgbvalue[1];
float Y = rgbvalue[2];
float K = Math.max(C, Math.max(M, Y));
// If K == 0.0F, then C = M = Y = 0.0F.
if(K != 0.0F) {
C = C/K;
M = M/K;
Y = Y/K;
} else { // K == 0.0F
C = M = Y = 1.0F;
}
return new float[] {C, M, Y, K};
}
public float[] toCIEXYZ(float[] colorvalue) {
return csRGB.toCIEXYZ(toRGB(colorvalue));
}
public float[] fromCIEXYZ(float[] xyzvalue) {
return fromRGB(csRGB.fromCIEXYZ(xyzvalue));
}
}
jai-imageio-core-1.2/src/share/classes/com/sun/media/imageioimpl/common/ImageUtil.java 0000664 0001751 0001751 00000157751 10665066462 030017 0 ustar tille tille /*
* $RCSfile: ImageUtil.java,v $
*
*
* Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistribution of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any
* kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
* WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
* EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
* NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
* USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
* ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
* CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
* REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
* INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for
* use in the design, construction, operation or maintenance of any
* nuclear facility.
*
* $Revision: 1.7 $
* $Date: 2007-08-28 18:45:06 $
* $State: Exp $
*/
package com.sun.media.imageioimpl.common;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Transparency;
import java.awt.color.ColorSpace;
import java.awt.color.ICC_ColorSpace;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.ComponentColorModel;
import java.awt.image.ComponentSampleModel;
import java.awt.image.DataBuffer;
import java.awt.image.DataBufferByte;
import java.awt.image.DataBufferInt;
import java.awt.image.DataBufferShort;
import java.awt.image.DataBufferUShort;
import java.awt.image.DirectColorModel;
import java.awt.image.IndexColorModel;
import java.awt.image.MultiPixelPackedSampleModel;
import java.awt.image.Raster;
import java.awt.image.RenderedImage;
import java.awt.image.SampleModel;
import java.awt.image.SinglePixelPackedSampleModel;
import java.awt.image.WritableRaster;
import java.io.IOException;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
//import javax.imageio.ImageTypeSpecifier;
import javax.imageio.IIOException;
import javax.imageio.IIOImage;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageTypeSpecifier;
import javax.imageio.ImageWriter;
import javax.imageio.spi.IIORegistry;
import javax.imageio.spi.ImageReaderSpi;
import javax.imageio.spi.ImageReaderWriterSpi;
import javax.imageio.spi.ImageWriterSpi;
import javax.imageio.spi.ServiceRegistry;
import javax.imageio.stream.ImageInputStream;
public class ImageUtil {
/* XXX testing only
public static void main(String[] args) {
ImageTypeSpecifier bilevel =
ImageTypeSpecifier.createIndexed(new byte[] {(byte)0, (byte)255},
new byte[] {(byte)0, (byte)255},
new byte[] {(byte)0, (byte)255},
null, 1,
DataBuffer.TYPE_BYTE);
ImageTypeSpecifier gray =
ImageTypeSpecifier.createGrayscale(8, DataBuffer.TYPE_BYTE, false);
ImageTypeSpecifier grayAlpha =
ImageTypeSpecifier.createGrayscale(8, DataBuffer.TYPE_BYTE, false,
false);
ImageTypeSpecifier rgb =
ImageTypeSpecifier.createInterleaved(ColorSpace.getInstance(ColorSpace.CS_sRGB),
new int[] {0, 1, 2},
DataBuffer.TYPE_BYTE,
false,
false);
ImageTypeSpecifier rgba =
ImageTypeSpecifier.createInterleaved(ColorSpace.getInstance(ColorSpace.CS_sRGB),
new int[] {0, 1, 2, 3},
DataBuffer.TYPE_BYTE,
true,
false);
ImageTypeSpecifier packed =
ImageTypeSpecifier.createPacked(ColorSpace.getInstance(ColorSpace.CS_sRGB),
0xff000000,
0x00ff0000,
0x0000ff00,
0x000000ff,
DataBuffer.TYPE_BYTE,
false);
SampleModel bandedSM =
new java.awt.image.BandedSampleModel(DataBuffer.TYPE_BYTE,
1, 1, 15);
System.out.println(createColorModel(bilevel.getSampleModel()));
System.out.println(createColorModel(gray.getSampleModel()));
System.out.println(createColorModel(grayAlpha.getSampleModel()));
System.out.println(createColorModel(rgb.getSampleModel()));
System.out.println(createColorModel(rgba.getSampleModel()));
System.out.println(createColorModel(packed.getSampleModel()));
System.out.println(createColorModel(bandedSM));
}
*/
/**
* Creates a ColorModel
that may be used with the
* specified SampleModel
. If a suitable
* ColorModel
cannot be found, this method returns
* null
.
*
* Suitable ColorModel
s are guaranteed to exist
* for all instances of ComponentSampleModel
.
* For 1- and 3- banded SampleModel
s, the returned
* ColorModel
will be opaque. For 2- and 4-banded
* SampleModel
s, the output will use alpha transparency
* which is not premultiplied. 1- and 2-banded data will use a
* grayscale ColorSpace
, and 3- and 4-banded data a sRGB
* ColorSpace
. Data with 5 or more bands will have a
* BogusColorSpace
.
An instance of DirectColorModel
will be created for
* instances of SinglePixelPackedSampleModel
with no more
* than 4 bands.
An instance of IndexColorModel
will be created for
* instances of MultiPixelPackedSampleModel
. The colormap
* will be a grayscale ramp with 1 << numberOfBits
* entries ranging from zero to at most 255.
ColorModel
that is suitable for
* the supplied SampleModel
, or null
.
*
* @throws IllegalArgumentException If sampleModel
is
* null
.
*/
public static final ColorModel createColorModel(SampleModel sampleModel) {
// Check the parameter.
if(sampleModel == null) {
throw new IllegalArgumentException("sampleModel == null!");
}
// Get the data type.
int dataType = sampleModel.getDataType();
// Check the data type
switch(dataType) {
case DataBuffer.TYPE_BYTE:
case DataBuffer.TYPE_USHORT:
case DataBuffer.TYPE_SHORT:
case DataBuffer.TYPE_INT:
case DataBuffer.TYPE_FLOAT:
case DataBuffer.TYPE_DOUBLE:
break;
default:
// Return null for other types.
return null;
}
// The return variable.
ColorModel colorModel = null;
// Get the sample size.
int[] sampleSize = sampleModel.getSampleSize();
// Create a Component ColorModel.
if(sampleModel instanceof ComponentSampleModel) {
// Get the number of bands.
int numBands = sampleModel.getNumBands();
// Determine the color space.
ColorSpace colorSpace = null;
if(numBands <= 2) {
colorSpace = ColorSpace.getInstance(ColorSpace.CS_GRAY);
} else if(numBands <= 4) {
colorSpace = ColorSpace.getInstance(ColorSpace.CS_sRGB);
} else {
colorSpace = new BogusColorSpace(numBands);
}
boolean hasAlpha = (numBands == 2) || (numBands == 4);
boolean isAlphaPremultiplied = false;
int transparency = hasAlpha ?
Transparency.TRANSLUCENT : Transparency.OPAQUE;
colorModel = new ComponentColorModel(colorSpace,
sampleSize,
hasAlpha,
isAlphaPremultiplied,
transparency,
dataType);
} else if (sampleModel.getNumBands() <= 4 &&
sampleModel instanceof SinglePixelPackedSampleModel) {
SinglePixelPackedSampleModel sppsm =
(SinglePixelPackedSampleModel)sampleModel;
int[] bitMasks = sppsm.getBitMasks();
int rmask = 0;
int gmask = 0;
int bmask = 0;
int amask = 0;
int numBands = bitMasks.length;
if (numBands <= 2) {
rmask = gmask = bmask = bitMasks[0];
if (numBands == 2) {
amask = bitMasks[1];
}
} else {
rmask = bitMasks[0];
gmask = bitMasks[1];
bmask = bitMasks[2];
if (numBands == 4) {
amask = bitMasks[3];
}
}
int bits = 0;
for (int i = 0; i < sampleSize.length; i++) {
bits += sampleSize[i];
}
return new DirectColorModel(bits, rmask, gmask, bmask, amask);
} else if(sampleModel instanceof MultiPixelPackedSampleModel) {
// Load the colormap with a ramp.
int bitsPerSample = sampleSize[0];
int numEntries = 1 << bitsPerSample;
byte[] map = new byte[numEntries];
for (int i = 0; i < numEntries; i++) {
map[i] = (byte)(i*255/(numEntries - 1));
}
colorModel = new IndexColorModel(bitsPerSample, numEntries,
map, map, map);
}
return colorModel;
}
/**
* For the case of binary data (isBinary()
returns
* true
), return the binary data as a packed byte array.
* The data will be packed as eight bits per byte with no bit offset,
* i.e., the first bit in each image line will be the left-most of the
* first byte of the line. The line stride in bytes will be
* (int)((getWidth()+7)/8)
. The length of the returned
* array will be the line stride multiplied by getHeight()
*
* @return the binary data as a packed array of bytes with zero offset
* of null
if the data are not binary.
* @throws IllegalArgumentException if isBinary()
returns
* false
with the SampleModel
of the
* supplied Raster
as argument.
*/
public static byte[] getPackedBinaryData(Raster raster,
Rectangle rect) {
SampleModel sm = raster.getSampleModel();
if(!isBinary(sm)) {
throw new IllegalArgumentException(I18N.getString("ImageUtil0"));
}
int rectX = rect.x;
int rectY = rect.y;
int rectWidth = rect.width;
int rectHeight = rect.height;
DataBuffer dataBuffer = raster.getDataBuffer();
int dx = rectX - raster.getSampleModelTranslateX();
int dy = rectY - raster.getSampleModelTranslateY();
MultiPixelPackedSampleModel mpp = (MultiPixelPackedSampleModel)sm;
int lineStride = mpp.getScanlineStride();
int eltOffset = dataBuffer.getOffset() + mpp.getOffset(dx, dy);
int bitOffset = mpp.getBitOffset(dx);
int numBytesPerRow = (rectWidth + 7)/8;
if(dataBuffer instanceof DataBufferByte &&
eltOffset == 0 && bitOffset == 0 &&
numBytesPerRow == lineStride &&
((DataBufferByte)dataBuffer).getData().length ==
numBytesPerRow*rectHeight) {
return ((DataBufferByte)dataBuffer).getData();
}
byte[] binaryDataArray = new byte[numBytesPerRow*rectHeight];
int b = 0;
if(bitOffset == 0) {
if(dataBuffer instanceof DataBufferByte) {
byte[] data = ((DataBufferByte)dataBuffer).getData();
int stride = numBytesPerRow;
int offset = 0;
for(int y = 0; y < rectHeight; y++) {
System.arraycopy(data, eltOffset,
binaryDataArray, offset,
stride);
offset += stride;
eltOffset += lineStride;
}
} else if(dataBuffer instanceof DataBufferShort ||
dataBuffer instanceof DataBufferUShort) {
short[] data = dataBuffer instanceof DataBufferShort ?
((DataBufferShort)dataBuffer).getData() :
((DataBufferUShort)dataBuffer).getData();
for(int y = 0; y < rectHeight; y++) {
int xRemaining = rectWidth;
int i = eltOffset;
while(xRemaining > 8) {
short datum = data[i++];
binaryDataArray[b++] = (byte)((datum >>> 8) & 0xFF);
binaryDataArray[b++] = (byte)(datum & 0xFF);
xRemaining -= 16;
}
if(xRemaining > 0) {
binaryDataArray[b++] = (byte)((data[i] >>> 8) & 0XFF);
}
eltOffset += lineStride;
}
} else if(dataBuffer instanceof DataBufferInt) {
int[] data = ((DataBufferInt)dataBuffer).getData();
for(int y = 0; y < rectHeight; y++) {
int xRemaining = rectWidth;
int i = eltOffset;
while(xRemaining > 24) {
int datum = data[i++];
binaryDataArray[b++] = (byte)((datum >>> 24) & 0xFF);
binaryDataArray[b++] = (byte)((datum >>> 16) & 0xFF);
binaryDataArray[b++] = (byte)((datum >>> 8) & 0xFF);
binaryDataArray[b++] = (byte)(datum & 0xFF);
xRemaining -= 32;
}
int shift = 24;
while(xRemaining > 0) {
binaryDataArray[b++] =
(byte)((data[i] >>> shift) & 0xFF);
shift -= 8;
xRemaining -= 8;
}
eltOffset += lineStride;
}
}
} else { // bitOffset != 0
if(dataBuffer instanceof DataBufferByte) {
byte[] data = ((DataBufferByte)dataBuffer).getData();
if((bitOffset & 7) == 0) {
int stride = numBytesPerRow;
int offset = 0;
for(int y = 0; y < rectHeight; y++) {
System.arraycopy(data, eltOffset,
binaryDataArray, offset,
stride);
offset += stride;
eltOffset += lineStride;
}
} else { // bitOffset % 8 != 0
int leftShift = bitOffset & 7;
int rightShift = 8 - leftShift;
for(int y = 0; y < rectHeight; y++) {
int i = eltOffset;
int xRemaining = rectWidth;
while(xRemaining > 0) {
if(xRemaining > rightShift) {
binaryDataArray[b++] =
(byte)(((data[i++]&0xFF) << leftShift) |
((data[i]&0xFF) >>> rightShift));
} else {
binaryDataArray[b++] =
(byte)((data[i]&0xFF) << leftShift);
}
xRemaining -= 8;
}
eltOffset += lineStride;
}
}
} else if(dataBuffer instanceof DataBufferShort ||
dataBuffer instanceof DataBufferUShort) {
short[] data = dataBuffer instanceof DataBufferShort ?
((DataBufferShort)dataBuffer).getData() :
((DataBufferUShort)dataBuffer).getData();
for(int y = 0; y < rectHeight; y++) {
int bOffset = bitOffset;
for(int x = 0; x < rectWidth; x += 8, bOffset += 8) {
int i = eltOffset + bOffset/16;
int mod = bOffset % 16;
int left = data[i] & 0xFFFF;
if(mod <= 8) {
binaryDataArray[b++] = (byte)(left >>> (8 - mod));
} else {
int delta = mod - 8;
int right = data[i+1] & 0xFFFF;
binaryDataArray[b++] =
(byte)((left << delta) |
(right >>> (16 - delta)));
}
}
eltOffset += lineStride;
}
} else if(dataBuffer instanceof DataBufferInt) {
int[] data = ((DataBufferInt)dataBuffer).getData();
for(int y = 0; y < rectHeight; y++) {
int bOffset = bitOffset;
for(int x = 0; x < rectWidth; x += 8, bOffset += 8) {
int i = eltOffset + bOffset/32;
int mod = bOffset % 32;
int left = data[i];
if(mod <= 24) {
binaryDataArray[b++] =
(byte)(left >>> (24 - mod));
} else {
int delta = mod - 24;
int right = data[i+1];
binaryDataArray[b++] =
(byte)((left << delta) |
(right >>> (32 - delta)));
}
}
eltOffset += lineStride;
}
}
}
return binaryDataArray;
}
/**
* Returns the binary data unpacked into an array of bytes.
* The line stride will be the width of the Raster
.
*
* @throws IllegalArgumentException if isBinary()
returns
* false
with the SampleModel
of the
* supplied Raster
as argument.
*/
public static byte[] getUnpackedBinaryData(Raster raster,
Rectangle rect) {
SampleModel sm = raster.getSampleModel();
if(!isBinary(sm)) {
throw new IllegalArgumentException(I18N.getString("ImageUtil0"));
}
int rectX = rect.x;
int rectY = rect.y;
int rectWidth = rect.width;
int rectHeight = rect.height;
DataBuffer dataBuffer = raster.getDataBuffer();
int dx = rectX - raster.getSampleModelTranslateX();
int dy = rectY - raster.getSampleModelTranslateY();
MultiPixelPackedSampleModel mpp = (MultiPixelPackedSampleModel)sm;
int lineStride = mpp.getScanlineStride();
int eltOffset = dataBuffer.getOffset() + mpp.getOffset(dx, dy);
int bitOffset = mpp.getBitOffset(dx);
byte[] bdata = new byte[rectWidth*rectHeight];
int maxY = rectY + rectHeight;
int maxX = rectX + rectWidth;
int k = 0;
if(dataBuffer instanceof DataBufferByte) {
byte[] data = ((DataBufferByte)dataBuffer).getData();
for(int y = rectY; y < maxY; y++) {
int bOffset = eltOffset*8 + bitOffset;
for(int x = rectX; x < maxX; x++) {
byte b = data[bOffset/8];
bdata[k++] =
(byte)((b >>> (7 - bOffset & 7)) & 0x0000001);
bOffset++;
}
eltOffset += lineStride;
}
} else if(dataBuffer instanceof DataBufferShort ||
dataBuffer instanceof DataBufferUShort) {
short[] data = dataBuffer instanceof DataBufferShort ?
((DataBufferShort)dataBuffer).getData() :
((DataBufferUShort)dataBuffer).getData();
for(int y = rectY; y < maxY; y++) {
int bOffset = eltOffset*16 + bitOffset;
for(int x = rectX; x < maxX; x++) {
short s = data[bOffset/16];
bdata[k++] =
(byte)((s >>> (15 - bOffset % 16)) &
0x0000001);
bOffset++;
}
eltOffset += lineStride;
}
} else if(dataBuffer instanceof DataBufferInt) {
int[] data = ((DataBufferInt)dataBuffer).getData();
for(int y = rectY; y < maxY; y++) {
int bOffset = eltOffset*32 + bitOffset;
for(int x = rectX; x < maxX; x++) {
int i = data[bOffset/32];
bdata[k++] =
(byte)((i >>> (31 - bOffset % 32)) &
0x0000001);
bOffset++;
}
eltOffset += lineStride;
}
}
return bdata;
}
/**
* Sets the supplied Raster
's data from an array
* of packed binary data of the form returned by
* getPackedBinaryData()
.
*
* @throws IllegalArgumentException if isBinary()
returns
* false
with the SampleModel
of the
* supplied Raster
as argument.
*/
public static void setPackedBinaryData(byte[] binaryDataArray,
WritableRaster raster,
Rectangle rect) {
SampleModel sm = raster.getSampleModel();
if(!isBinary(sm)) {
throw new IllegalArgumentException(I18N.getString("ImageUtil0"));
}
int rectX = rect.x;
int rectY = rect.y;
int rectWidth = rect.width;
int rectHeight = rect.height;
DataBuffer dataBuffer = raster.getDataBuffer();
int dx = rectX - raster.getSampleModelTranslateX();
int dy = rectY - raster.getSampleModelTranslateY();
MultiPixelPackedSampleModel mpp = (MultiPixelPackedSampleModel)sm;
int lineStride = mpp.getScanlineStride();
int eltOffset = dataBuffer.getOffset() + mpp.getOffset(dx, dy);
int bitOffset = mpp.getBitOffset(dx);
int b = 0;
if(bitOffset == 0) {
if(dataBuffer instanceof DataBufferByte) {
byte[] data = ((DataBufferByte)dataBuffer).getData();
if(data == binaryDataArray) {
// Optimal case: simply return.
return;
}
int stride = (rectWidth + 7)/8;
int offset = 0;
for(int y = 0; y < rectHeight; y++) {
System.arraycopy(binaryDataArray, offset,
data, eltOffset,
stride);
offset += stride;
eltOffset += lineStride;
}
} else if(dataBuffer instanceof DataBufferShort ||
dataBuffer instanceof DataBufferUShort) {
short[] data = dataBuffer instanceof DataBufferShort ?
((DataBufferShort)dataBuffer).getData() :
((DataBufferUShort)dataBuffer).getData();
for(int y = 0; y < rectHeight; y++) {
int xRemaining = rectWidth;
int i = eltOffset;
while(xRemaining > 8) {
data[i++] =
(short)(((binaryDataArray[b++] & 0xFF) << 8) |
(binaryDataArray[b++] & 0xFF));
xRemaining -= 16;
}
if(xRemaining > 0) {
data[i++] =
(short)((binaryDataArray[b++] & 0xFF) << 8);
}
eltOffset += lineStride;
}
} else if(dataBuffer instanceof DataBufferInt) {
int[] data = ((DataBufferInt)dataBuffer).getData();
for(int y = 0; y < rectHeight; y++) {
int xRemaining = rectWidth;
int i = eltOffset;
while(xRemaining > 24) {
data[i++] =
(int)(((binaryDataArray[b++] & 0xFF) << 24) |
((binaryDataArray[b++] & 0xFF) << 16) |
((binaryDataArray[b++] & 0xFF) << 8) |
(binaryDataArray[b++] & 0xFF));
xRemaining -= 32;
}
int shift = 24;
while(xRemaining > 0) {
data[i] |=
(int)((binaryDataArray[b++] & 0xFF) << shift);
shift -= 8;
xRemaining -= 8;
}
eltOffset += lineStride;
}
}
} else { // bitOffset != 0
int stride = (rectWidth + 7)/8;
int offset = 0;
if(dataBuffer instanceof DataBufferByte) {
byte[] data = ((DataBufferByte)dataBuffer).getData();
if((bitOffset & 7) == 0) {
for(int y = 0; y < rectHeight; y++) {
System.arraycopy(binaryDataArray, offset,
data, eltOffset,
stride);
offset += stride;
eltOffset += lineStride;
}
} else { // bitOffset % 8 != 0
int rightShift = bitOffset & 7;
int leftShift = 8 - rightShift;
int leftShift8 = 8 + leftShift;
int mask = (byte)(255<Raster
* from an array of unpacked data of the form returned by
* getUnpackedBinaryData()
.
*
* If the data are binary, then the target bit will be set if
* and only if the corresponding byte is non-zero.
*
* @throws IllegalArgumentException if The default implementation calls
* The returned Raster is semantically a copy. This means
* that updates to the source image will not be reflected in the
* returned Raster. For non-writable (immutable) source images,
* the returned value may be a reference to the image's internal
* data. The returned Raster should be considered non-writable;
* any attempt to alter its pixel data (such as by casting it to
* WritableRaster or obtaining and modifying its DataBuffer) may
* result in undefined behavior. The copyData method should be
* used if the returned Raster is to be modified.
*
* @return a Raster containing a copy of this image's data.
*/
public Raster getData() {
Rectangle rect = new Rectangle(getMinX(), getMinY(),
getWidth(), getHeight());
return getData(rect);
}
/**
* Returns an arbitrary rectangular region of the RenderedImage
* in a Raster. The rectangle of interest will be clipped against
* the image bounds.
*
* The returned Raster is semantically a copy. This means
* that updates to the source image will not be reflected in the
* returned Raster. For non-writable (immutable) source images,
* the returned value may be a reference to the image's internal
* data. The returned Raster should be considered non-writable;
* any attempt to alter its pixel data (such as by casting it to
* WritableRaster or obtaining and modifying its DataBuffer) may
* result in undefined behavior. The copyData method should be
* used if the returned Raster is to be modified.
*
* @param bounds the region of the RenderedImage to be returned.
*/
public Raster getData(Rectangle bounds) {
// Get the image bounds.
Rectangle imageBounds = getBounds();
// Check for parameter validity.
if(bounds == null) {
bounds = imageBounds;
} else if(!bounds.intersects(imageBounds)) {
throw new IllegalArgumentException(I18N.getString("SimpleRenderedImage0"));
}
// Determine tile limits for the prescribed bounds.
int startX = XToTileX(bounds.x);
int startY = YToTileY(bounds.y);
int endX = XToTileX(bounds.x + bounds.width - 1);
int endY = YToTileY(bounds.y + bounds.height - 1);
// If the bounds are contained in a single tile, return a child
// of that tile's Raster.
if ((startX == endX) && (startY == endY)) {
Raster tile = getTile(startX, startY);
return tile.createChild(bounds.x, bounds.y,
bounds.width, bounds.height,
bounds.x, bounds.y, null);
} else {
// Recalculate the tile limits if the data bounds are not a
// subset of the image bounds.
if(!imageBounds.contains(bounds)) {
Rectangle xsect = bounds.intersection(imageBounds);
startX = XToTileX(xsect.x);
startY = YToTileY(xsect.y);
endX = XToTileX(xsect.x + xsect.width - 1);
endY = YToTileY(xsect.y + xsect.height - 1);
}
// Create a WritableRaster of the desired size
SampleModel sm =
sampleModel.createCompatibleSampleModel(bounds.width,
bounds.height);
// Translate it
WritableRaster dest =
Raster.createWritableRaster(sm, bounds.getLocation());
// Loop over the tiles in the intersection.
for (int j = startY; j <= endY; j++) {
for (int i = startX; i <= endX; i++) {
// Retrieve the tile.
Raster tile = getTile(i, j);
// Create a child of the tile for the intersection of
// the tile bounds and the bounds of the requested area.
Rectangle tileRect = tile.getBounds();
Rectangle intersectRect =
bounds.intersection(tile.getBounds());
Raster liveRaster = tile.createChild(intersectRect.x,
intersectRect.y,
intersectRect.width,
intersectRect.height,
intersectRect.x,
intersectRect.y,
null);
// Copy the data from the child.
dest.setRect(liveRaster);
}
}
return dest;
}
}
/**
* Copies an arbitrary rectangular region of the RenderedImage
* into a caller-supplied WritableRaster. The region to be
* computed is determined by clipping the bounds of the supplied
* WritableRaster against the bounds of the image. The supplied
* WritableRaster must have a SampleModel that is compatible with
* that of the image.
*
* If the raster argument is null, the entire image will
* be copied into a newly-created WritableRaster with a SampleModel
* that is compatible with that of the image.
*
* @param dest a WritableRaster to hold the returned portion of
* the image.
* @return a reference to the supplied WritableRaster, or to a
* new WritableRaster if the supplied one was null.
*/
public WritableRaster copyData(WritableRaster dest) {
// Get the image bounds.
Rectangle imageBounds = getBounds();
Rectangle bounds;
if (dest == null) {
// Create a WritableRaster for the entire image.
bounds = imageBounds;
Point p = new Point(minX, minY);
SampleModel sm =
sampleModel.createCompatibleSampleModel(width, height);
dest = Raster.createWritableRaster(sm, p);
} else {
bounds = dest.getBounds();
}
// Determine tile limits for the intersection of the prescribed
// bounds with the image bounds.
Rectangle xsect = imageBounds.contains(bounds) ?
bounds : bounds.intersection(imageBounds);
int startX = XToTileX(xsect.x);
int startY = YToTileY(xsect.y);
int endX = XToTileX(xsect.x + xsect.width - 1);
int endY = YToTileY(xsect.y + xsect.height - 1);
// Loop over the tiles in the intersection.
for (int j = startY; j <= endY; j++) {
for (int i = startX; i <= endX; i++) {
// Retrieve the tile.
Raster tile = getTile(i, j);
// Create a child of the tile for the intersection of
// the tile bounds and the bounds of the requested area.
Rectangle tileRect = tile.getBounds();
Rectangle intersectRect =
bounds.intersection(tile.getBounds());
Raster liveRaster = tile.createChild(intersectRect.x,
intersectRect.y,
intersectRect.width,
intersectRect.height,
intersectRect.x,
intersectRect.y,
null);
// Copy the data from the child.
dest.setRect(liveRaster);
}
}
return dest;
}
}
jai-imageio-core-1.2/src/share/classes/com/sun/media/imageioimpl/common/LZWStringTable.java 0000664 0001751 0001751 00000021272 10203036165 030717 0 ustar tille tille /*
* $RCSfile: LZWStringTable.java,v $
*
*
* Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistribution of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any
* kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
* WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
* EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
* NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
* USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
* ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
* CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
* REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
* INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for
* use in the design, construction, operation or maintenance of any
* nuclear facility.
*
* $Revision: 1.1 $
* $Date: 2005-02-11 05:01:23 $
* $State: Exp $
*/
package com.sun.media.imageioimpl.common;
import java.io.PrintStream;
/**
* General purpose LZW String Table.
* Extracted from GIFEncoder by Adam Doppelt
* Comments added by Robin Luiten
* Extenders need only provide a static method
* isBinary()
returns
* false
with the SampleModel
of the
* supplied Raster
as argument.
*/
public static void setUnpackedBinaryData(byte[] bdata,
WritableRaster raster,
Rectangle rect) {
SampleModel sm = raster.getSampleModel();
if(!isBinary(sm)) {
throw new IllegalArgumentException(I18N.getString("ImageUtil0"));
}
int rectX = rect.x;
int rectY = rect.y;
int rectWidth = rect.width;
int rectHeight = rect.height;
DataBuffer dataBuffer = raster.getDataBuffer();
int dx = rectX - raster.getSampleModelTranslateX();
int dy = rectY - raster.getSampleModelTranslateY();
MultiPixelPackedSampleModel mpp = (MultiPixelPackedSampleModel)sm;
int lineStride = mpp.getScanlineStride();
int eltOffset = dataBuffer.getOffset() + mpp.getOffset(dx, dy);
int bitOffset = mpp.getBitOffset(dx);
int k = 0;
if(dataBuffer instanceof DataBufferByte) {
byte[] data = ((DataBufferByte)dataBuffer).getData();
for(int y = 0; y < rectHeight; y++) {
int bOffset = eltOffset*8 + bitOffset;
for(int x = 0; x < rectWidth; x++) {
if(bdata[k++] != (byte)0) {
data[bOffset/8] |=
(byte)(0x00000001 << (7 - bOffset & 7));
}
bOffset++;
}
eltOffset += lineStride;
}
} else if(dataBuffer instanceof DataBufferShort ||
dataBuffer instanceof DataBufferUShort) {
short[] data = dataBuffer instanceof DataBufferShort ?
((DataBufferShort)dataBuffer).getData() :
((DataBufferUShort)dataBuffer).getData();
for(int y = 0; y < rectHeight; y++) {
int bOffset = eltOffset*16 + bitOffset;
for(int x = 0; x < rectWidth; x++) {
if(bdata[k++] != (byte)0) {
data[bOffset/16] |=
(short)(0x00000001 <<
(15 - bOffset % 16));
}
bOffset++;
}
eltOffset += lineStride;
}
} else if(dataBuffer instanceof DataBufferInt) {
int[] data = ((DataBufferInt)dataBuffer).getData();
for(int y = 0; y < rectHeight; y++) {
int bOffset = eltOffset*32 + bitOffset;
for(int x = 0; x < rectWidth; x++) {
if(bdata[k++] != (byte)0) {
data[bOffset/32] |=
(int)(0x00000001 <<
(31 - bOffset % 32));
}
bOffset++;
}
eltOffset += lineStride;
}
}
}
public static boolean isBinary(SampleModel sm) {
return sm instanceof MultiPixelPackedSampleModel &&
((MultiPixelPackedSampleModel)sm).getPixelBitStride() == 1 &&
sm.getNumBands() == 1;
}
public static ColorModel createColorModel(ColorSpace colorSpace,
SampleModel sampleModel) {
ColorModel colorModel = null;
if(sampleModel == null) {
throw new IllegalArgumentException(I18N.getString("ImageUtil1"));
}
int numBands = sampleModel.getNumBands();
if (numBands < 1 || numBands > 4) {
return null;
}
int dataType = sampleModel.getDataType();
if (sampleModel instanceof ComponentSampleModel) {
if (dataType < DataBuffer.TYPE_BYTE ||
//dataType == DataBuffer.TYPE_SHORT ||
dataType > DataBuffer.TYPE_DOUBLE) {
return null;
}
if (colorSpace == null)
colorSpace =
numBands <= 2 ?
ColorSpace.getInstance(ColorSpace.CS_GRAY) :
ColorSpace.getInstance(ColorSpace.CS_sRGB);
boolean useAlpha = (numBands == 2) || (numBands == 4);
int transparency = useAlpha ?
Transparency.TRANSLUCENT : Transparency.OPAQUE;
boolean premultiplied = false;
int dataTypeSize = DataBuffer.getDataTypeSize(dataType);
int[] bits = new int[numBands];
for (int i = 0; i < numBands; i++) {
bits[i] = dataTypeSize;
}
colorModel = new ComponentColorModel(colorSpace,
bits,
useAlpha,
premultiplied,
transparency,
dataType);
} else if (sampleModel instanceof SinglePixelPackedSampleModel) {
SinglePixelPackedSampleModel sppsm =
(SinglePixelPackedSampleModel)sampleModel;
int[] bitMasks = sppsm.getBitMasks();
int rmask = 0;
int gmask = 0;
int bmask = 0;
int amask = 0;
numBands = bitMasks.length;
if (numBands <= 2) {
rmask = gmask = bmask = bitMasks[0];
if (numBands == 2) {
amask = bitMasks[1];
}
} else {
rmask = bitMasks[0];
gmask = bitMasks[1];
bmask = bitMasks[2];
if (numBands == 4) {
amask = bitMasks[3];
}
}
int[] sampleSize = sppsm.getSampleSize();
int bits = 0;
for (int i = 0; i < sampleSize.length; i++) {
bits += sampleSize[i];
}
if (colorSpace == null)
colorSpace = ColorSpace.getInstance(ColorSpace.CS_sRGB);
colorModel =
new DirectColorModel(colorSpace,
bits, rmask, gmask, bmask, amask,
false,
sampleModel.getDataType());
} else if (sampleModel instanceof MultiPixelPackedSampleModel) {
int bits =
((MultiPixelPackedSampleModel)sampleModel).getPixelBitStride();
int size = 1 << bits;
byte[] comp = new byte[size];
for (int i = 0; i < size; i++)
comp[i] = (byte)(255 * i / (size - 1));
colorModel = new IndexColorModel(bits, size, comp, comp, comp);
}
return colorModel;
}
public static int getElementSize(SampleModel sm) {
int elementSize = DataBuffer.getDataTypeSize(sm.getDataType());
if (sm instanceof MultiPixelPackedSampleModel) {
MultiPixelPackedSampleModel mppsm =
(MultiPixelPackedSampleModel)sm;
return mppsm.getSampleSize(0) * mppsm.getNumBands();
} else if (sm instanceof ComponentSampleModel) {
return sm.getNumBands() * elementSize;
} else if (sm instanceof SinglePixelPackedSampleModel) {
return elementSize;
}
return elementSize * sm.getNumBands();
}
public static long getTileSize(SampleModel sm) {
int elementSize = DataBuffer.getDataTypeSize(sm.getDataType());
if (sm instanceof MultiPixelPackedSampleModel) {
MultiPixelPackedSampleModel mppsm =
(MultiPixelPackedSampleModel)sm;
return (mppsm.getScanlineStride() * mppsm.getHeight() +
(mppsm.getDataBitOffset() + elementSize -1) / elementSize) *
((elementSize + 7) / 8);
} else if (sm instanceof ComponentSampleModel) {
ComponentSampleModel csm = (ComponentSampleModel)sm;
int[] bandOffsets = csm.getBandOffsets();
int maxBandOff = bandOffsets[0];
for (int i=1; iIndexColorModel
maps index
* i
to ((255*i)/icm.getMapSize()-1)
.
* @throws IllegalArgumentException if icm
is
* null
.
*/
public static boolean isGrayscaleMapping(IndexColorModel icm) {
if(icm == null) {
throw new IllegalArgumentException("icm == null!");
}
// Get colormap size and contents.
int mapSize = icm.getMapSize();
byte[] r = new byte[mapSize];
byte[] g = new byte[mapSize];
byte[] b = new byte[mapSize];
icm.getReds(r);
icm.getGreens(g);
icm.getBlues(b);
boolean isGrayToColor = true;
// Check ascending ramp.
for (int i = 0; i < mapSize; i++) {
byte temp = (byte)(i*255/(mapSize - 1));
if (r[i] != temp || g[i] != temp || b[i] != temp) {
isGrayToColor = false;
break;
}
}
if(!isGrayToColor) {
isGrayToColor = true;
// Check descending ramp.
for (int i = 0, j = mapSize - 1; i < mapSize; i++, j--) {
byte temp = (byte)(j*255/(mapSize - 1));
if (r[i] != temp || g[i] != temp || b[i] != temp) {
isGrayToColor = false;
break;
}
}
}
return isGrayToColor;
}
/**
* Tests whether the color indices represent a gray-scale image.
*
* @param r The red channel color indices.
* @param g The green channel color indices.
* @param b The blue channel color indices.
* @return If all the indices have 256 entries, and are identical mappings,
* return true
; otherwise, return false
.
*/
public static boolean isIndicesForGrayscale(byte[] r, byte[] g, byte[] b) {
if (r.length != g.length || r.length != b.length)
return false;
int size = r.length;
if (size != 256)
return false;
for (int i = 0; i < size; i++) {
byte temp = (byte) i;
if (r[i] != temp || g[i] != temp || b[i] != temp)
return false;
}
return true;
}
/** Converts the provided object to String
*/
public static String convertObjectToString(Object obj) {
if (obj == null)
return "";
String s = "";
if (obj instanceof byte[]) {
byte[] bArray = (byte[])obj;
for (int i = 0; i < bArray.length; i++)
s += bArray[i] + " ";
return s;
}
if (obj instanceof int[]) {
int[] iArray = (int[])obj;
for (int i = 0; i < iArray.length; i++)
s += iArray[i] + " " ;
return s;
}
if (obj instanceof short[]) {
short[] sArray = (short[])obj;
for (int i = 0; i < sArray.length; i++)
s += sArray[i] + " " ;
return s;
}
return obj.toString();
}
/** Checks that the provided ImageWriter
can encode
* the provided ImageTypeSpecifier
or not. If not, an
* IIOException
will be thrown.
* @param writer The provided ImageWriter
.
* @param type The image to be tested.
* @throws IIOException If the writer cannot encoded the provided image.
*/
public static final void canEncodeImage(ImageWriter writer,
ImageTypeSpecifier type)
throws IIOException {
ImageWriterSpi spi = writer.getOriginatingProvider();
if(type != null && spi != null && !spi.canEncodeImage(type)) {
throw new IIOException(I18N.getString("ImageUtil2")+" "+
writer.getClass().getName());
}
}
/** Checks that the provided ImageWriter
can encode
* the provided ColorModel
and SampleModel
.
* If not, an IIOException
will be thrown.
* @param writer The provided ImageWriter
.
* @param colorModel The provided ColorModel
.
* @param sampleModel The provided SampleModel
.
* @throws IIOException If the writer cannot encoded the provided image.
*/
public static final void canEncodeImage(ImageWriter writer,
ColorModel colorModel,
SampleModel sampleModel)
throws IIOException {
ImageTypeSpecifier type = null;
if (colorModel != null && sampleModel != null)
type = new ImageTypeSpecifier(colorModel, sampleModel);
canEncodeImage(writer, type);
}
/**
* Returns whether the image has contiguous data across rows.
*/
public static final boolean imageIsContiguous(RenderedImage image) {
SampleModel sm;
if(image instanceof BufferedImage) {
WritableRaster ras = ((BufferedImage)image).getRaster();
sm = ras.getSampleModel();
} else {
sm = image.getSampleModel();
}
if (sm instanceof ComponentSampleModel) {
// Ensure image rows samples are stored contiguously
// in a single bank.
ComponentSampleModel csm = (ComponentSampleModel)sm;
if (csm.getPixelStride() != csm.getNumBands()) {
return false;
}
int[] bandOffsets = csm.getBandOffsets();
for (int i = 0; i < bandOffsets.length; i++) {
if (bandOffsets[i] != i) {
return false;
}
}
int[] bankIndices = csm.getBankIndices();
for (int i = 0; i < bandOffsets.length; i++) {
if (bankIndices[i] != 0) {
return false;
}
}
return true;
}
// Otherwise true if and only if it's a bilevel image with
// a MultiPixelPackedSampleModel, 1 bit per pixel, and 1 bit
// pixel stride.
return ImageUtil.isBinary(sm);
}
/**
* Gets the destination image type.
*/
// NOTE: Code shamelessly copied from ImageReader.getDestination().
public static final ImageTypeSpecifier
getDestinationType(ImageReadParam param,
Iterator imageTypes) throws IIOException {
if (imageTypes == null || !imageTypes.hasNext()) {
throw new IllegalArgumentException("imageTypes null or empty!");
}
ImageTypeSpecifier imageType = null;
// If param is non-null, use it
if (param != null) {
imageType = param.getDestinationType();
}
// No info from param, use fallback image type
if (imageType == null) {
Object o = imageTypes.next();
if (!(o instanceof ImageTypeSpecifier)) {
throw new IllegalArgumentException
("Non-ImageTypeSpecifier retrieved from imageTypes!");
}
imageType = (ImageTypeSpecifier)o;
} else {
boolean foundIt = false;
while (imageTypes.hasNext()) {
ImageTypeSpecifier type =
(ImageTypeSpecifier)imageTypes.next();
if (type.equals(imageType)) {
foundIt = true;
break;
}
}
if (!foundIt) {
throw new IIOException
("Destination type from ImageReadParam does not match!");
}
}
return imageType;
}
/**
* Returns true
if the given ColorSpace
object
* is an instance of ICC_ColorSpace
but is not one of the
* standard ColorSpace
s returned by
* ColorSpace.getInstance()
.
*
* @param cs The ColorSpace
to test.
*/
public static boolean isNonStandardICCColorSpace(ColorSpace cs) {
boolean retval = false;
try {
// Check the standard ColorSpaces in decreasing order of
// likelihood except check CS_PYCC last as in some JREs
// PYCC.pf used not to be installed.
retval =
(cs instanceof ICC_ColorSpace) &&
!(cs.isCS_sRGB() ||
cs.equals(ColorSpace.getInstance(ColorSpace.CS_LINEAR_RGB)) ||
cs.equals(ColorSpace.getInstance(ColorSpace.CS_GRAY)) ||
cs.equals(ColorSpace.getInstance(ColorSpace.CS_CIEXYZ)) ||
cs.equals(ColorSpace.getInstance(ColorSpace.CS_PYCC)));
} catch(IllegalArgumentException e) {
// PYCC.pf not installed: ignore it - 'retval' is still 'false'.
}
return retval;
}
// Method to return JDK core ImageReaderSPI/ImageWriterSPI for a
// given formatName.
public static List getJDKImageReaderWriterSPI(ServiceRegistry registry,
String formatName,
boolean isReader) {
IIORegistry iioRegistry = (IIORegistry)registry;
Class spiClass;
String descPart;
if (isReader) {
spiClass = ImageReaderSpi.class;
descPart = " image reader";
} else {
spiClass = ImageWriterSpi.class;
descPart = " image writer";
}
Iterator iter = iioRegistry.getServiceProviders(spiClass,
true); // useOrdering
String formatNames[];
ImageReaderWriterSpi provider;
String desc = "standard " + formatName + descPart;
String jiioPath = "com.sun.media.imageioimpl";
Locale locale = Locale.getDefault();
ArrayList list = new ArrayList();
while (iter.hasNext()) {
provider = (ImageReaderWriterSpi)iter.next();
// Look for JDK core ImageWriterSpi's
if (provider.getVendorName().startsWith("Sun Microsystems") &&
desc.equalsIgnoreCase(provider.getDescription(locale)) &&
// not JAI Image I/O plugins
!provider.getPluginClassName().startsWith(jiioPath)) {
// Get the formatNames supported by this Spi
formatNames = provider.getFormatNames();
for (int i=0; ijava.awt.Image.UndefinedProperty
will be returned.
*
* @param name the name of the property to get, as a
* String
. @return a reference to the property
* Object
, or the value
* java.awt.Image.UndefinedProperty.
*/
public Object getProperty(String name) {
name = name.toLowerCase();
Object value = properties.get(name);
return value != null ? value : java.awt.Image.UndefinedProperty;
}
/**
* Returns a list of the properties recognized by this image. If
* no properties are available, null
will be
* returned.
*
* @return an array of String
s representing valid
* property names.
*/
public String[] getPropertyNames() {
String[] names = null;
if(properties.size() > 0) {
names = new String[properties.size()];
int index = 0;
Enumeration e = properties.keys();
while (e.hasMoreElements()) {
String name = (String)e.nextElement();
names[index++] = name;
}
}
return names;
}
/**
* Returns an array of String
s recognized as names by
* this property source that begin with the supplied prefix. If
* no property names match, null
will be returned.
* The comparison is done in a case-independent manner.
*
* getPropertyNames()
and searches the list of names
* for matches.
*
* @return an array of String
s giving the valid
* property names.
*/
public String[] getPropertyNames(String prefix) {
String propertyNames[] = getPropertyNames();
if (propertyNames == null) {
return null;
}
prefix = prefix.toLowerCase();
Vector names = new Vector();
for (int i = 0; i < propertyNames.length; i++) {
if (propertyNames[i].startsWith(prefix)) {
names.addElement(propertyNames[i]);
}
}
if (names.size() == 0) {
return null;
}
// Copy the strings from the Vector over to a String array.
String prefixNames[] = new String[names.size()];
int count = 0;
for (Iterator it = names.iterator(); it.hasNext(); ) {
prefixNames[count++] = (String)it.next();
}
return prefixNames;
}
// Utility methods.
/**
* Converts a pixel's X coordinate into a horizontal tile index
* relative to a given tile grid layout specified by its X offset
* and tile width.
*/
public static int XToTileX(int x, int tileGridXOffset, int tileWidth) {
x -= tileGridXOffset;
if (x < 0) {
x += 1 - tileWidth; // Force round to -infinity
}
return x/tileWidth;
}
/**
* Converts a pixel's Y coordinate into a vertical tile index
* relative to a given tile grid layout specified by its Y offset
* and tile height.
*/
public static int YToTileY(int y, int tileGridYOffset, int tileHeight) {
y -= tileGridYOffset;
if (y < 0) {
y += 1 - tileHeight; // Force round to -infinity
}
return y/tileHeight;
}
/**
* Converts a pixel's X coordinate into a horizontal tile index.
* This is a convenience method. No attempt is made to detect
* out-of-range coordinates.
*
* @param x the X coordinate of a pixel.
* @return the X index of the tile containing the pixel.
*/
public int XToTileX(int x) {
return XToTileX(x, getTileGridXOffset(), getTileWidth());
}
/**
* Converts a pixel's Y coordinate into a vertical tile index.
* This is a convenience method. No attempt is made to detect
* out-of-range coordinates.
*
* @param y the Y coordinate of a pixel.
* @return the Y index of the tile containing the pixel.
*/
public int YToTileY(int y) {
return YToTileY(y, getTileGridYOffset(), getTileHeight());
}
/**
* Converts a horizontal tile index into the X coordinate of its
* upper left pixel relative to a given tile grid layout specified
* by its X offset and tile width.
*/
public static int tileXToX(int tx, int tileGridXOffset, int tileWidth) {
return tx*tileWidth + tileGridXOffset;
}
/**
* Converts a vertical tile index into the Y coordinate of
* its upper left pixel relative to a given tile grid layout
* specified by its Y offset and tile height.
*/
public static int tileYToY(int ty, int tileGridYOffset, int tileHeight) {
return ty*tileHeight + tileGridYOffset;
}
/**
* Converts a horizontal tile index into the X coordinate of its
* upper left pixel. This is a convenience method. No attempt is made
* to detect out-of-range indices.
*
* @param tx the horizontal index of a tile.
* @return the X coordinate of the tile's upper left pixel.
*/
public int tileXToX(int tx) {
return tx*tileWidth + tileGridXOffset;
}
/**
* Converts a vertical tile index into the Y coordinate of its
* upper left pixel. This is a convenience method. No attempt is made
* to detect out-of-range indices.
*
* @param ty the vertical index of a tile.
* @return the Y coordinate of the tile's upper left pixel.
*/
public int tileYToY(int ty) {
return ty*tileHeight + tileGridYOffset;
}
public Vector getSources() {
return null;
}
/**
* Returns the entire image in a single Raster. For images with
* multiple tiles this will require making a copy.
*
* expandCode
added by Robin Luiten
* The strLen_ table to give quick access to the lenght of an expanded
* code for use by the expandCode
method added by Robin.
**/
public class LZWStringTable
{
/** codesize + Reserved Codes */
private final static int RES_CODES = 2;
private final static short HASH_FREE = (short)0xFFFF;
private final static short NEXT_FIRST = (short)0xFFFF;
private final static int MAXBITS = 12;
private final static int MAXSTR = (1 << MAXBITS);
private final static short HASHSIZE = 9973;
private final static short HASHSTEP = 2039;
byte[] strChr_; // after predecessor character
short[] strNxt_; // predecessor string
short[] strHsh_; // hash table to find predecessor + char pairs
short numStrings_; // next code if adding new prestring + char
/**
* each entry corresponds to a code and contains the length of data
* that the code expands to when decoded.
**/
int[] strLen_;
/**
* Constructor allocate memory for string store data
**/
public LZWStringTable()
{
strChr_ = new byte[MAXSTR];
strNxt_ = new short[MAXSTR];
strLen_ = new int[MAXSTR];
strHsh_ = new short[HASHSIZE];
}
/**
* @param index value of -1 indicates no predecessor [used in initialisation]
* @param b the byte [character] to add to the string store which follows
* the predecessor string specified the index.
* @return 0xFFFF if no space in table left for addition of predecesor
* index and byte b. Else return the code allocated for combination index + b.
**/
public int AddCharString(short index, byte b)
{
int hshidx;
if (numStrings_ >= MAXSTR) // if used up all codes
{
return 0xFFFF;
}
hshidx = Hash(index, b);
while (strHsh_[hshidx] != HASH_FREE)
hshidx = (hshidx + HASHSTEP) % HASHSIZE;
strHsh_[hshidx] = numStrings_;
strChr_[numStrings_] = b;
if (index == HASH_FREE)
{
strNxt_[numStrings_] = NEXT_FIRST;
strLen_[numStrings_] = 1;
}
else
{
strNxt_[numStrings_] = index;
strLen_[numStrings_] = strLen_[index] + 1;
}
return numStrings_++; // return the code and inc for next code
}
/**
* @param index index to prefix string
* @param b the character that follws the index prefix
* @return b if param index is HASH_FREE. Else return the code
* for this prefix and byte successor
**/
public short FindCharString(short index, byte b)
{
int hshidx, nxtidx;
if (index == HASH_FREE)
return (short)(b & 0xFF); // Rob fixed used to sign extend
hshidx = Hash(index, b);
while ((nxtidx = strHsh_[hshidx]) != HASH_FREE) // search
{
if (strNxt_[nxtidx] == index && strChr_[nxtidx] == b)
return (short)nxtidx;
hshidx = (hshidx + HASHSTEP) % HASHSIZE;
}
return (short)0xFFFF;
}
/**
* @param codesize the size of code to be preallocated for the
* string store.
**/
public void ClearTable(int codesize)
{
numStrings_ = 0;
for (int q = 0; q < HASHSIZE; q++)
strHsh_[q] = HASH_FREE;
int w = (1 << codesize) + RES_CODES;
for (int q = 0; q < w; q++)
AddCharString((short)0xFFFF, (byte)q); // init with no prefix
}
static public int Hash(short index, byte lastbyte)
{
return ((int)((short)(lastbyte << 8) ^ index) & 0xFFFF) % HASHSIZE;
}
/**
* If expanded data doesnt fit into array only what will fit is written
* to buf and the return value indicates how much of the expanded code has
* been written to the buf. The next call to expandCode() should be with
* the same code and have the skip parameter set the negated value of the
* previous return. Succesive negative return values should be negated and
* added together for next skip parameter value with same code.
*
* @param buf buffer to place expanded data into
* @param offset offset to place expanded data
* @param code the code to expand to the byte array it represents.
* PRECONDITION This code must allready be in the LZSS
* @param skipHead is the number of bytes at the start of the expanded code to
* be skipped before data is written to buf. It is possible that skipHead is
* equal to codeLen.
* @return the length of data expanded into buf. If the expanded code is longer
* than space left in buf then the value returned is a negative number which when
* negated is equal to the number of bytes that were used of the code being expanded.
* This negative value also indicates the buffer is full.
**/
public int expandCode(byte[] buf, int offset, short code, int skipHead)
{
if (offset == -2)
{
if (skipHead == 1) skipHead = 0;
}
if (code == (short)0xFFFF || // just in case
skipHead == strLen_[code]) // DONE no more unpacked
return 0;
int expandLen; // how much data we are actually expanding
int codeLen = strLen_[code] - skipHead; // length of expanded code left
int bufSpace = buf.length - offset; // how much space left
if (bufSpace > codeLen)
expandLen = codeLen; // only got this many to unpack
else
expandLen = bufSpace;
int skipTail = codeLen - expandLen; // only > 0 if codeLen > bufSpace [left overs]
int idx = offset + expandLen; // initialise to exclusive end address of buffer area
// NOTE: data unpacks in reverse direction and we are placing the
// unpacked data directly into the array in the correct location.
while ((idx > offset) && (code != (short)0xFFFF))
{
if (--skipTail < 0) // skip required of expanded data
{
buf[--idx] = strChr_[code];
}
code = strNxt_[code]; // to predecessor code
}
if (codeLen > expandLen)
return -expandLen; // indicate what part of codeLen used
else
return expandLen; // indicate length of dat unpacked
}
public void dump(PrintStream out)
{
int i;
for (i = 258; i < numStrings_; ++i)
out.println( " strNxt_[" + i + "] = " + strNxt_[i]
+ " strChr_ " + Integer.toHexString(strChr_[i] & 0xFF)
+ " strLen_ " + Integer.toHexString(strLen_[i]));
}
}
jai-imageio-core-1.2/src/share/classes/com/sun/media/imageioimpl/common/LZWCompressor.java 0000664 0001751 0001751 00000013164 10203036165 030636 0 ustar tille tille /*
* $RCSfile: LZWCompressor.java,v $
*
*
* Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistribution of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any
* kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
* WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
* EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
* NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
* USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
* ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
* CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
* REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
* INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for
* use in the design, construction, operation or maintenance of any
* nuclear facility.
*
* $Revision: 1.1 $
* $Date: 2005-02-11 05:01:22 $
* $State: Exp $
*/
package com.sun.media.imageioimpl.common;
import java.io.IOException;
import java.io.PrintStream;
import javax.imageio.stream.ImageOutputStream;
/**
* Modified from original LZWCompressor to change interface to passing a
* buffer of data to be compressed.
**/
public class LZWCompressor
{
/** base underlying code size of data being compressed 8 for TIFF, 1 to 8 for GIF **/
int codeSize_;
/** reserved clear code based on code size **/
int clearCode_;
/** reserved end of data code based on code size **/
int endOfInfo_;
/** current number bits output for each code **/
int numBits_;
/** limit at which current number of bits code size has to be increased **/
int limit_;
/** the prefix code which represents the predecessor string to current input point **/
short prefix_;
/** output destination for bit codes **/
BitFile bf_;
/** general purpose LZW string table **/
LZWStringTable lzss_;
/** modify the limits of the code values in LZW encoding due to TIFF bug / feature **/
boolean tiffFudge_;
/**
* @param out destination for compressed data
* @param codeSize the initial code size for the LZW compressor
* @param TIFF flag indicating that TIFF lzw fudge needs to be applied
* @exception IOException if underlying output stream error
**/
public LZWCompressor(ImageOutputStream out, int codeSize, boolean TIFF) throws IOException
{
bf_ = new BitFile(out, !TIFF); // set flag for GIF as NOT tiff
codeSize_ = codeSize;
tiffFudge_ = TIFF;
clearCode_ = 1 << codeSize_;
endOfInfo_ = clearCode_ + 1;
numBits_ = codeSize_ + 1;
limit_ = (1 << numBits_) - 1;
if (tiffFudge_)
--limit_;
prefix_ = (short)0xFFFF;
lzss_ = new LZWStringTable();
lzss_.ClearTable(codeSize_);
bf_.writeBits(clearCode_, numBits_);
}
/**
* @param buf data to be compressed to output stream
* @exception IOException if underlying output stream error
**/
public void compress(byte[] buf, int offset, int length)
throws IOException
{
int idx;
byte c;
short index;
int maxOffset = offset + length;
for (idx = offset; idx < maxOffset; ++idx)
{
c = buf[idx];
if ((index = lzss_.FindCharString(prefix_, c)) != -1)
prefix_ = index;
else
{
bf_.writeBits(prefix_, numBits_);
if (lzss_.AddCharString(prefix_, c) > limit_)
{
if (numBits_ == 12)
{
bf_.writeBits(clearCode_, numBits_);
lzss_.ClearTable(codeSize_);
numBits_ = codeSize_ + 1;
}
else
++numBits_;
limit_ = (1 << numBits_) - 1;
if (tiffFudge_)
--limit_;
}
prefix_ = (short)((short)c & 0xFF);
}
}
}
/**
* Indicate to compressor that no more data to go so write out
* any remaining buffered data.
*
* @exception IOException if underlying output stream error
**/
public void flush() throws IOException
{
if (prefix_ != -1)
bf_.writeBits(prefix_, numBits_);
bf_.writeBits(endOfInfo_, numBits_);
bf_.flush();
}
public void dump(PrintStream out)
{
lzss_.dump(out);
}
}
jai-imageio-core-1.2/src/share/classes/com/sun/media/imageioimpl/common/properties 0000664 0001751 0001751 00000001013 10203036165 027347 0 ustar tille tille #
# $RCSfile: properties,v $
#
# Copyright (c) 2005 Sun Microsystems, Inc. All rights reserved.
#
# Use is subject to license terms.
#
# $Revision: 1.1 $
# $Date: 2005-02-11 05:01:24 $
# $State: Exp $
#
# Internationalization file for com.sun.media.imageioimpl.common
ImageUtil0=The supplied Raster does not represent a binary data set.
ImageUtil1=The provided sample model is null.
ImageUtil2=The provided image cannot be encoded using:
SimpleRenderedImage0=The provided region doesn't intersect with the image bounds.
jai-imageio-core-1.2/src/share/classes/com/sun/media/imageioimpl/common/PackageUtil.java 0000664 0001751 0001751 00000011730 10413303155 030272 0 ustar tille tille /*
* $RCSfile: PackageUtil.java,v $
*
*
* Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistribution of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any
* kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
* WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
* EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
* NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
* USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
* ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
* CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
* REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
* INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for
* use in the design, construction, operation or maintenance of any
* nuclear facility.
*
* $Revision: 1.3 $
* $Date: 2006-03-31 19:43:38 $
* $State: Exp $
*/
package com.sun.media.imageioimpl.common;
import java.security.AccessController;
import java.security.PrivilegedAction;
import com.sun.medialib.codec.jiio.Util;
public class PackageUtil {
/**
* Flag indicating whether codecLib is available.
*/
private static boolean isCodecLibAvailable = false;
/**
* Implementation version derived from Manifest.
*/
private static String version = "1.0";
/**
* Implementation vendor derived from Manifest.
*/
private static String vendor = "Sun Microsystems, Inc.";
/**
* Specification Title derived from Manifest.
*/
private static String specTitle = "Java Advanced Imaging Image I/O Tools";
/**
* Set static flags.
*/
static {
// Set codecLib flag.
try {
// Check for codecLib availability.
isCodecLibAvailable = Util.isCodecLibAvailable();
} catch(Throwable e) {
// A Throwable is equivalent to unavailable. Throwable is used
// in case an Error rather than an Exception is thrown.
isCodecLibAvailable = false;
}
// Set version and vendor strings.
try {
Class thisClass =
Class.forName("com.sun.media.imageioimpl.common.PackageUtil");
Package thisPackage = thisClass.getPackage();
version = thisPackage.getImplementationVersion();
vendor = thisPackage.getImplementationVendor();
specTitle = thisPackage.getSpecificationTitle();
} catch(ClassNotFoundException e) {
}
}
/**
* Returns a boolean
indicating whether codecLib is available.
*/
public static final boolean isCodecLibAvailable() {
// Retrieve value of system property here to allow this to be
// modified dynamically.
Boolean result = (Boolean)
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
String property = null;
try {
property =
System.getProperty("com.sun.media.imageio.disableCodecLib");
} catch(SecurityException se) {
// Do nothing: leave 'property' null.
}
return (property != null &&
property.equalsIgnoreCase("true")) ?
Boolean.TRUE : Boolean.FALSE;
}
});
boolean isCodecLibDisabled = result.booleanValue();
return isCodecLibAvailable && !isCodecLibDisabled;
}
/**
* Return a version string for the package.
*/
public static final String getVersion() {
return version;
}
/**
* Return a vendor string for the package.
*/
public static final String getVendor() {
return vendor;
}
/**
* Return the Specification Title string for the package.
*/
public static final String getSpecificationTitle() {
return specTitle;
}
}
jai-imageio-core-1.2/src/share/classes/com/sun/media/imageioimpl/common/I18NImpl.java 0000664 0001751 0001751 00000006311 10203036165 027402 0 ustar tille tille /*
* $RCSfile: I18NImpl.java,v $
*
*
* Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistribution of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any
* kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
* WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
* EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
* NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
* USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
* ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
* CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
* REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
* INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for
* use in the design, construction, operation or maintenance of any
* nuclear facility.
*
* $Revision: 1.1 $
* $Date: 2005-02-11 05:01:22 $
* $State: Exp $
*/
package com.sun.media.imageioimpl.common;
import java.io.InputStream;
import java.util.PropertyResourceBundle;
/**
* Class to simplify use of internationalization message strings.
* Property files are constructed in terms of content as for JAI with
* one "key=value" pair per line. All such files however have the same
* name "properties". The resource extractor resolves the extraction of
* the file from the jar as the package name is included automatically.
*
* getString(String)
which calls the static method in this
* class with the name of the invoking class and returns a
* String
.
*/
public class I18NImpl {
/**
* Returns the message string with the specified key from the
* "properties" file in the package containing the class with
* the specified name.
*/
protected static final String getString(String className, String key) {
PropertyResourceBundle bundle = null;
try {
InputStream stream =
Class.forName(className).getResourceAsStream("properties");
bundle = new PropertyResourceBundle(stream);
} catch(Throwable e) {
throw new RuntimeException(e); // Chain the exception.
}
return (String)bundle.handleGetObject(key);
}
}
jai-imageio-core-1.2/src/share/classes/com/sun/media/imageioimpl/common/SimpleCMYKColorSpace.java 0000664 0001751 0001751 00000011155 10375417450 032005 0 ustar tille tille /*
* $RCSfile: SimpleCMYKColorSpace.java,v $
*
*
* Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistribution of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any
* kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
* WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
* EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
* NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
* USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
* ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
* CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
* REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
* INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for
* use in the design, construction, operation or maintenance of any
* nuclear facility.
*
* $Revision: 1.5 $
* $Date: 2006-02-17 19:08:24 $
* $State: Exp $
*/
package com.sun.media.imageioimpl.common;
import java.awt.color.ColorSpace;
/**
* Singleton class representing a simple, mathematically defined CMYK
* color space.
*/
public final class SimpleCMYKColorSpace extends ColorSpace {
private static ColorSpace theInstance = null;
private ColorSpace csRGB;
/** The exponent for gamma correction. */
private static final double power1 = 1.0 / 2.4;
public static final synchronized ColorSpace getInstance() {
if(theInstance == null) {
theInstance = new SimpleCMYKColorSpace();
}
return theInstance;
}
private SimpleCMYKColorSpace() {
super(TYPE_CMYK, 4);
csRGB = ColorSpace.getInstance(ColorSpace.CS_LINEAR_RGB);
}
public boolean equals(Object o) {
return o != null && o instanceof SimpleCMYKColorSpace;
}
public float[] toRGB(float[] colorvalue) {
float C = colorvalue[0];
float M = colorvalue[1];
float Y = colorvalue[2];
float K = colorvalue[3];
float K1 = 1.0F - K;
// Convert from CMYK to linear RGB.
float[] rgbvalue = new float[] {K1*(1.0F - C),
K1*(1.0F - M),
K1*(1.0F - Y)};
// Convert from linear RGB to sRGB.
for (int i = 0; i < 3; i++) {
float v = rgbvalue[i];
if (v < 0.0F) v = 0.0F;
if (v < 0.0031308F) {
rgbvalue[i] = 12.92F * v;
} else {
if (v > 1.0F) v = 1.0F;
rgbvalue[i] = (float)(1.055 * Math.pow(v, power1) - 0.055);
}
}
return rgbvalue;
}
public float[] fromRGB(float[] rgbvalue) {
// Convert from sRGB to linear RGB.
for (int i = 0; i < 3; i++) {
if (rgbvalue[i] < 0.040449936F) {
rgbvalue[i] /= 12.92F;
} else {
rgbvalue[i] =
(float)(Math.pow((rgbvalue[i] + 0.055)/1.055, 2.4));
}
}
// Convert from linear RGB to CMYK.
float C = 1.0F - rgbvalue[0];
float M = 1.0F - rgbvalue[1];
float Y = 1.0F - rgbvalue[2];
float K = Math.min(C, Math.min(M, Y));
// If K == 1.0F, then C = M = Y = 1.0F.
if(K != 1.0F) {
float K1 = 1.0F - K;
C = (C - K)/K1;
M = (M - K)/K1;
Y = (Y - K)/K1;
} else {
C = M = Y = 0.0F;
}
return new float[] {C, M, Y, K};
}
public float[] toCIEXYZ(float[] colorvalue) {
return csRGB.toCIEXYZ(toRGB(colorvalue));
}
public float[] fromCIEXYZ(float[] xyzvalue) {
return fromRGB(csRGB.fromCIEXYZ(xyzvalue));
}
}
././@LongLink 0000000 0000000 0000000 00000000145 00000000000 011565 L ustar root root jai-imageio-core-1.2/src/share/classes/com/sun/media/imageioimpl/common/SingleTileRenderedImage.java jai-imageio-core-1.2/src/share/classes/com/sun/media/imageioimpl/common/SingleTileRenderedImage.java0000664 0001751 0001751 00000006171 10203036165 032560 0 ustar tille tille /*
* $RCSfile: SingleTileRenderedImage.java,v $
*
*
* Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistribution of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any
* kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
* WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
* EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
* NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
* USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
* ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
* CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
* REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
* INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for
* use in the design, construction, operation or maintenance of any
* nuclear facility.
*
* $Revision: 1.1 $
* $Date: 2005-02-11 05:01:23 $
* $State: Exp $
*/
package com.sun.media.imageioimpl.common;
import java.awt.image.ColorModel;
import java.awt.image.Raster;
/**
* A simple class that provides RenderedImage functionality
* given a Raster and a ColorModel.
*/
public class SingleTileRenderedImage extends SimpleRenderedImage {
Raster ras;
/**
* Constructs a SingleTileRenderedImage based on a Raster
* and a ColorModel.
*
* @param ras A Raster that will define tile (0, 0) of the image.
* @param cm A ColorModel that will serve as the image's
* ColorModel.
*/
public SingleTileRenderedImage(Raster ras, ColorModel colorModel) {
this.ras = ras;
this.tileGridXOffset = this.minX = ras.getMinX();
this.tileGridYOffset = this.minY = ras.getMinY();
this.tileWidth = this.width = ras.getWidth();
this.tileHeight = this.height = ras.getHeight();
this.sampleModel = ras.getSampleModel();
this.colorModel = colorModel;
}
/**
* Returns the image's Raster as tile (0, 0).
*/
public Raster getTile(int tileX, int tileY) {
if (tileX != 0 || tileY != 0) {
throw new IllegalArgumentException("tileX != 0 || tileY != 0");
}
return ras;
}
}
jai-imageio-core-1.2/src/share/classes/com/sun/media/imageioimpl/common/BitFile.java 0000664 0001751 0001751 00000014143 10203036165 027421 0 ustar tille tille /*
* $RCSfile: BitFile.java,v $
*
*
* Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistribution of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any
* kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
* WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
* EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
* NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
* USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
* ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
* CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
* REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
* INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for
* use in the design, construction, operation or maintenance of any
* nuclear facility.
*
* $Revision: 1.1 $
* $Date: 2005-02-11 05:01:21 $
* $State: Exp $
*/
package com.sun.media.imageioimpl.common;
import java.io.IOException;
import javax.imageio.stream.ImageOutputStream;
/**
* Came from GIFEncoder initially.
* Modified - to allow for output compressed data without the block counts
* which breakup the compressed data stream for GIF.
**/
public class BitFile
{
ImageOutputStream output_;
byte buffer_[];
int index_;
int bitsLeft_; // bits left at current index that are avail.
/** note this also indicates gif format BITFile. **/
boolean blocks_ = false;
/**
* @param output destination for output data
* @param blocks GIF LZW requires block counts for output data
**/
public BitFile(ImageOutputStream output, boolean blocks)
{
output_ = output;
blocks_ = blocks;
buffer_ = new byte[256];
index_ = 0;
bitsLeft_ = 8;
}
public void flush() throws IOException
{
int numBytes = index_ + (bitsLeft_ == 8 ? 0 : 1);
if (numBytes > 0)
{
if (blocks_)
output_.write(numBytes);
output_.write(buffer_, 0, numBytes);
buffer_[0] = 0;
index_ = 0;
bitsLeft_ = 8;
}
}
public void writeBits(int bits, int numbits) throws IOException
{
int bitsWritten = 0;
int numBytes = 255; // gif block count
do
{
// This handles the GIF block count stuff
if ((index_ == 254 && bitsLeft_ == 0) || index_ > 254)
{
if (blocks_)
output_.write(numBytes);
output_.write(buffer_, 0, numBytes);
buffer_[0] = 0;
index_ = 0;
bitsLeft_ = 8;
}
if (numbits <= bitsLeft_) // bits contents fit in current index byte
{
if (blocks_) // GIF
{
buffer_[index_] |= (bits & ((1 << numbits) - 1)) << (8 - bitsLeft_);
bitsWritten += numbits;
bitsLeft_ -= numbits;
numbits = 0;
}
else
{
buffer_[index_] |= (bits & ((1 << numbits) - 1)) << (bitsLeft_ - numbits);
bitsWritten += numbits;
bitsLeft_ -= numbits;
numbits = 0;
}
}
else // bits overflow from current byte to next.
{
if (blocks_) // GIF
{
// if bits > space left in current byte then the lowest order bits
// of code are taken and put in current byte and rest put in next.
buffer_[index_] |= (bits & ((1 << bitsLeft_) - 1)) << (8 - bitsLeft_);
bitsWritten += bitsLeft_;
bits >>= bitsLeft_;
numbits -= bitsLeft_;
buffer_[++index_] = 0;
bitsLeft_ = 8;
}
else
{
// if bits > space left in current byte then the highest order bits
// of code are taken and put in current byte and rest put in next.
// at highest order bit location !!
int topbits = (bits >>> (numbits - bitsLeft_)) & ((1 << bitsLeft_) - 1);
buffer_[index_] |= topbits;
numbits -= bitsLeft_; // ok this many bits gone off the top
bitsWritten += bitsLeft_;
buffer_[++index_] = 0; // next index
bitsLeft_ = 8;
}
}
} while (numbits != 0);
}
}
jai-imageio-core-1.2/src/share/classes/com/sun/media/imageioimpl/common/I18N.java 0000664 0001751 0001751 00000004110 10203036165 026553 0 ustar tille tille /*
* $RCSfile: I18N.java,v $
*
*
* Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistribution of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any
* kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
* WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
* EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
* NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
* USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
* ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
* CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
* REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
* INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for
* use in the design, construction, operation or maintenance of any
* nuclear facility.
*
* $Revision: 1.1 $
* $Date: 2005-02-11 05:01:22 $
* $State: Exp $
*/
package com.sun.media.imageioimpl.common;
final class I18N extends I18NImpl {
static String getString(String key) {
return getString("com.sun.media.imageioimpl.common.I18N", key);
}
}
jai-imageio-core-1.2/src/share/classes/com/sun/media/imageioimpl/common/PaletteBuilder.java 0000775 0001751 0001751 00000035714 10665655550 031043 0 ustar tille tille /*
* $RCSfile: PaletteBuilder.java,v $
*
* Copyright (c) 2005 Sun Microsystems, Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistribution of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any
* kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
* WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
* EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
* NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
* USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
* ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
* CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
* REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
* INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for
* use in the design, construction, operation or maintenance of any
* nuclear facility.
*
* $Revision: 1.3 $
* $Date: 2007-08-31 00:06:00 $
* $State: Exp $
*/
package com.sun.media.imageioimpl.common;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.awt.image.ColorModel;
import java.awt.image.IndexColorModel;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;
import java.awt.Color;
import javax.imageio.ImageTypeSpecifier;
/**
* This class implements the octree quantization method
* as it is described in the "Graphics Gems"
* (ISBN 0-12-286166-3, Chapter 4, pages 297-293)
*/
public class PaletteBuilder {
/**
* maximum of tree depth
*/
protected static final int MAXLEVEL = 8;
protected RenderedImage src;
protected ColorModel srcColorModel;
protected Raster srcRaster;
protected int requiredSize;
protected ColorNode root;
protected int numNodes;
protected int maxNodes;
protected int currLevel;
protected int currSize;
protected ColorNode[] reduceList;
protected ColorNode[] palette;
protected int transparency;
protected ColorNode transColor;
/**
* Creates an image representing given image
* src
using IndexColorModel
.
*
* Lossless conversion is not always possible (e.g. if number
* of colors in the given image exceeds maximum palette size).
* Result image then is an approximation constructed by octree
* quantization method.
*
* @exception IllegalArgumentException if
src
is
* null
.
*
* @exception UnsupportedOperationException if implemented method
* is unable to create approximation of src
* and canCreatePalette
returns false
.
*
* @see createIndexColorModel
*
* @see canCreatePalette
*
*/
public static RenderedImage createIndexedImage(RenderedImage src) {
PaletteBuilder pb = new PaletteBuilder(src);
pb.buildPalette();
return pb.getIndexedImage();
}
/**
* Creates an palette representing colors from given image
* img
. If number of colors in the given image exceeds
* maximum palette size closest colors would be merged.
*
* @exception IllegalArgumentException if img
is
* null
.
*
* @exception UnsupportedOperationException if implemented method
* is unable to create approximation of img
* and canCreatePalette
returns false
.
*
* @see createIndexedImage
*
* @see canCreatePalette
*
*/
public static IndexColorModel createIndexColorModel(RenderedImage img) {
PaletteBuilder pb = new PaletteBuilder(img);
pb.buildPalette();
return pb.getIndexColorModel();
}
/**
* Returns true
if PaletteBuilder is able to create
* palette for given image type.
*
* @param type an instance of ImageTypeSpecifier
to be
* indexed.
*
* @return true
if the PaletteBuilder
* is likely to be able to create palette for this image type.
*
* @exception IllegalArgumentException if type
* is null
.
*/
public static boolean canCreatePalette(ImageTypeSpecifier type) {
if (type == null) {
throw new IllegalArgumentException("type == null");
}
return true;
}
/**
* Returns true
if PaletteBuilder is able to create
* palette for given rendered image.
*
* @param image an instance of RenderedImage
to be
* indexed.
*
* @return true
if the PaletteBuilder
* is likely to be able to create palette for this image type.
*
* @exception IllegalArgumentException if image
* is null
.
*/
public static boolean canCreatePalette(RenderedImage image) {
if (image == null) {
throw new IllegalArgumentException("image == null");
}
ImageTypeSpecifier type = new ImageTypeSpecifier(image);
return canCreatePalette(type);
}
protected RenderedImage getIndexedImage() {
IndexColorModel icm = getIndexColorModel();
BufferedImage dst =
new BufferedImage(src.getWidth(), src.getHeight(),
BufferedImage.TYPE_BYTE_INDEXED, icm);
WritableRaster wr = dst.getRaster();
int minX = src.getMinX();
int minY = src.getMinY();
for (int y =0; y < dst.getHeight(); y++) {
for (int x = 0; x < dst.getWidth(); x++) {
Color aColor = getSrcColor(x + minX, y + minY);
wr.setSample(x, y, 0, findColorIndex(root, aColor));
}
}
return dst;
}
protected PaletteBuilder(RenderedImage src) {
this(src, 256);
}
protected PaletteBuilder(RenderedImage src, int size) {
this.src = src;
this.srcColorModel = src.getColorModel();
this.srcRaster = src.getData();
this.transparency =
srcColorModel.getTransparency();
if (transparency != Transparency.OPAQUE) {
this.requiredSize = size - 1;
transColor = new ColorNode();
transColor.isLeaf = true;
} else {
this.requiredSize = size;
}
}
private Color getSrcColor(int x, int y) {
int argb = srcColorModel.getRGB(srcRaster.getDataElements(x, y, null));
return new Color(argb, transparency != Transparency.OPAQUE);
}
protected int findColorIndex(ColorNode aNode, Color aColor) {
if (transparency != Transparency.OPAQUE &&
aColor.getAlpha() != 0xff)
{
return 0; // default transparnt pixel
}
if (aNode.isLeaf) {
return aNode.paletteIndex;
} else {
int childIndex = getBranchIndex(aColor, aNode.level);
return findColorIndex(aNode.children[childIndex], aColor);
}
}
protected void buildPalette() {
reduceList = new ColorNode[MAXLEVEL + 1];
for (int i = 0; i < reduceList.length; i++) {
reduceList[i] = null;
}
numNodes = 0;
maxNodes = 0;
root = null;
currSize = 0;
currLevel = MAXLEVEL;
/*
from the book
*/
int w = src.getWidth();
int h = src.getHeight();
int minX = src.getMinX();
int minY = src.getMinY();
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
Color aColor = getSrcColor(w - x + minX - 1, h - y + minY - 1);
/*
* If transparency of given image is not opaque we assume all
* colors with alpha less than 1.0 as fully transparent.
*/
if (transparency != Transparency.OPAQUE &&
aColor.getAlpha() != 0xff)
{
transColor = insertNode(transColor, aColor, 0);
} else {
root = insertNode(root, aColor, 0);
}
if (currSize > requiredSize) {
reduceTree();
}
}
}
}
protected ColorNode insertNode(ColorNode aNode, Color aColor, int aLevel) {
if (aNode == null) {
aNode = new ColorNode();
numNodes++;
if (numNodes > maxNodes) {
maxNodes = numNodes;
}
aNode.level = aLevel;
aNode.isLeaf = (aLevel > MAXLEVEL);
if (aNode.isLeaf) {
currSize++;
}
}
aNode.colorCount++;
aNode.red += aColor.getRed();
aNode.green += aColor.getGreen();
aNode.blue += aColor.getBlue();
if (!aNode.isLeaf) {
int branchIndex = getBranchIndex(aColor, aLevel);
if (aNode.children[branchIndex] == null) {
aNode.childCount++;
if (aNode.childCount == 2) {
aNode.nextReducible = reduceList[aLevel];
reduceList[aLevel] = aNode;
}
}
aNode.children[branchIndex] =
insertNode(aNode.children[branchIndex], aColor, aLevel + 1);
}
return aNode;
}
protected IndexColorModel getIndexColorModel() {
int size = currSize;
if (transparency != Transparency.OPAQUE) {
size ++; // we need place for transparent color;
}
byte[] red = new byte[size];
byte[] green = new byte[size];
byte[] blue = new byte[size];
int index = 0;
palette = new ColorNode[size];
if (transparency != Transparency.OPAQUE) {
index ++;
}
int lastIndex = findPaletteEntry(root, index, red, green, blue);
IndexColorModel icm = null;
if (transparency != Transparency.OPAQUE) {
icm = new IndexColorModel(8, size, red, green, blue, 0);
} else {
icm = new IndexColorModel(8, currSize, red, green, blue);
}
return icm;
}
protected int findPaletteEntry(ColorNode aNode, int index,
byte[] red, byte[] green, byte[] blue)
{
if (aNode.isLeaf) {
red[index] = (byte)(aNode.red/aNode.colorCount);
green[index] = (byte)(aNode.green/aNode.colorCount);
blue[index] = (byte)(aNode.blue/aNode.colorCount);
aNode.paletteIndex = index;
palette[index] = aNode;
index++;
} else {
for (int i = 0; i < 8; i++) {
if (aNode.children[i] != null) {
index = findPaletteEntry(aNode.children[i], index,
red, green, blue);
}
}
}
return index;
}
protected int getBranchIndex(Color aColor, int aLevel) {
if (aLevel > MAXLEVEL || aLevel < 0) {
throw new IllegalArgumentException("Invalid octree node depth: " +
aLevel);
}
int shift = MAXLEVEL - aLevel;
int red_index = 0x1 & ((0xff & aColor.getRed()) >> shift);
int green_index = 0x1 & ((0xff & aColor.getGreen()) >> shift);
int blue_index = 0x1 & ((0xff & aColor.getBlue()) >> shift);
int index = (red_index << 2) | (green_index << 1) | blue_index;
return index;
}
protected void reduceTree() {
int level = reduceList.length - 1;
while (reduceList[level] == null && level >= 0) {
level--;
}
ColorNode thisNode = reduceList[level];
if (thisNode == null) {
// nothing to reduce
return;
}
// look for element with lower color count
ColorNode pList = thisNode;
int minColorCount = pList.colorCount;
int cnt = 1;
while (pList.nextReducible != null) {
if (minColorCount > pList.nextReducible.colorCount) {
thisNode = pList;
minColorCount = pList.colorCount;
}
pList = pList.nextReducible;
cnt++;
}
// save pointer to first reducible node
// NB: current color count for node could be changed in future
if (thisNode == reduceList[level]) {
reduceList[level] = thisNode.nextReducible;
} else {
pList = thisNode.nextReducible; // we need to process it
thisNode.nextReducible = pList.nextReducible;
thisNode = pList;
}
if (thisNode.isLeaf) {
return;
}
// reduce node
int leafChildCount = thisNode.getLeafChildCount();
thisNode.isLeaf = true;
currSize -= (leafChildCount - 1);
int aDepth = thisNode.level;
for (int i = 0; i < 8; i++) {
thisNode.children[i] = freeTree(thisNode.children[i]);
}
thisNode.childCount = 0;
}
protected ColorNode freeTree(ColorNode aNode) {
if (aNode == null) {
return null;
}
for (int i = 0; i < 8; i++) {
aNode.children[i] = freeTree(aNode.children[i]);
}
numNodes--;
return null;
}
/**
* The node of color tree.
*/
protected class ColorNode {
public boolean isLeaf;
public int childCount;
ColorNode[] children;
public int colorCount;
public long red;
public long blue;
public long green;
public int paletteIndex;
public int level;
ColorNode nextReducible;
public ColorNode() {
isLeaf = false;
level = 0;
childCount = 0;
children = new ColorNode[8];
for (int i = 0; i < 8; i++) {
children[i] = null;
}
colorCount = 0;
red = green = blue = 0;
paletteIndex = 0;
}
public int getLeafChildCount() {
if (isLeaf) {
return 0;
}
int cnt = 0;
for (int i = 0; i < children.length; i++) {
if (children[i] != null) {
if (children[i].isLeaf) {
cnt ++;
} else {
cnt += children[i].getLeafChildCount();
}
}
}
return cnt;
}
public int getRGB() {
int r = (int)red/colorCount;
int g = (int)green/colorCount;
int b = (int)blue/colorCount;
int c = 0xff << 24 | (0xff&r) << 16 | (0xff&g) << 8 | (0xff&b);
return c;
}
}
}
jai-imageio-core-1.2/src/share/classes/com/sun/media/imageioimpl/common/BogusColorSpace.java 0000664 0001751 0001751 00000012140 10203036165 031130 0 ustar tille tille /*
* $RCSfile: BogusColorSpace.java,v $
*
*
* Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistribution of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any
* kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
* WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
* EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
* NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
* USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
* ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
* CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
* REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
* INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for
* use in the design, construction, operation or maintenance of any
* nuclear facility.
*
* $Revision: 1.1 $
* $Date: 2005-02-11 05:01:22 $
* $State: Exp $
*/
package com.sun.media.imageioimpl.common;
import java.awt.color.ColorSpace;
/**
* A dummy ColorSpace
to enable ColorModel
* for image data which do not have an innate color representation.
*/
public class BogusColorSpace extends ColorSpace {
/**
* Return the type given the number of components.
*
* @param numComponents The number of components in the
* ColorSpace
.
* @exception IllegalArgumentException if numComponents
* is less than 1.
*/
private static int getType(int numComponents) {
if(numComponents < 1) {
throw new IllegalArgumentException("numComponents < 1!");
}
int type;
switch(numComponents) {
case 1:
type = ColorSpace.TYPE_GRAY;
break;
default:
// Based on the constant definitions TYPE_2CLR=12 through
// TYPE_FCLR=25. This will return unknown types for
// numComponents > 15.
type = numComponents + 10;
}
return type;
}
/**
* Constructs a bogus ColorSpace
.
*
* @param numComponents The number of components in the
* ColorSpace
.
* @exception IllegalArgumentException if numComponents
* is less than 1.
*/
public BogusColorSpace(int numComponents) {
super(getType(numComponents), numComponents);
}
//
// The following methods simply copy the input array to the
// output array while otherwise attempting to adhere to the
// specified behavior of the methods vis-a-vis exceptions.
//
public float[] toRGB(float[] colorvalue) {
if(colorvalue.length < getNumComponents()) {
throw new ArrayIndexOutOfBoundsException
("colorvalue.length < getNumComponents()");
}
float[] rgbvalue = new float[3];
System.arraycopy(colorvalue, 0, rgbvalue, 0,
Math.min(3, getNumComponents()));
return colorvalue;
}
public float[] fromRGB(float[] rgbvalue) {
if(rgbvalue.length < 3) {
throw new ArrayIndexOutOfBoundsException
("rgbvalue.length < 3");
}
float[] colorvalue = new float[getNumComponents()];
System.arraycopy(rgbvalue, 0, colorvalue, 0,
Math.min(3, colorvalue.length));
return rgbvalue;
}
public float[] toCIEXYZ(float[] colorvalue) {
if(colorvalue.length < getNumComponents()) {
throw new ArrayIndexOutOfBoundsException
("colorvalue.length < getNumComponents()");
}
float[] xyzvalue = new float[3];
System.arraycopy(colorvalue, 0, xyzvalue, 0,
Math.min(3, getNumComponents()));
return colorvalue;
}
public float[] fromCIEXYZ(float[] xyzvalue) {
if(xyzvalue.length < 3) {
throw new ArrayIndexOutOfBoundsException
("xyzvalue.length < 3");
}
float[] colorvalue = new float[getNumComponents()];
System.arraycopy(xyzvalue, 0, colorvalue, 0,
Math.min(3, colorvalue.length));
return xyzvalue;
}
}
jai-imageio-core-1.2/src/share/classes/com/sun/media/imageioimpl/stream/ 0000775 0001751 0001751 00000000000 11650556211 025246 5 ustar tille tille ././@LongLink 0000000 0000000 0000000 00000000150 00000000000 011561 L ustar root root jai-imageio-core-1.2/src/share/classes/com/sun/media/imageioimpl/stream/ChannelImageInputStreamSpi.java jai-imageio-core-1.2/src/share/classes/com/sun/media/imageioimpl/stream/ChannelImageInputStreamSpi.j0000664 0001751 0001751 00000007111 10203036165 032576 0 ustar tille tille /*
* $RCSfile: ChannelImageInputStreamSpi.java,v $
*
*
* Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistribution of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any
* kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
* WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
* EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
* NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
* USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
* ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
* CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
* REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
* INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for
* use in the design, construction, operation or maintenance of any
* nuclear facility.
*
* $Revision: 1.1 $
* $Date: 2005-02-11 05:01:53 $
* $State: Exp $
*/
package com.sun.media.imageioimpl.stream;
import java.io.File;
import java.io.InputStream;
import java.io.IOException;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.util.Locale;
import javax.imageio.spi.ImageInputStreamSpi;
import javax.imageio.stream.FileCacheImageInputStream;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.MemoryCacheImageInputStream;
import com.sun.media.imageio.stream.FileChannelImageInputStream;
import com.sun.media.imageioimpl.common.PackageUtil;
public class ChannelImageInputStreamSpi extends ImageInputStreamSpi {
public ChannelImageInputStreamSpi() {
super(PackageUtil.getVendor(),
PackageUtil.getVersion(),
ReadableByteChannel.class);
}
public ImageInputStream createInputStreamInstance(Object input,
boolean useCache,
File cacheDir)
throws IOException {
if(input == null ||
!(input instanceof ReadableByteChannel)) {
throw new IllegalArgumentException("XXX");
}
ImageInputStream stream = null;
if(input instanceof FileChannel) {
stream = new FileChannelImageInputStream((FileChannel)input);
} else {
InputStream inStream =
Channels.newInputStream((ReadableByteChannel)input);
if(useCache) {
try {
stream = new FileCacheImageInputStream(inStream,
cacheDir);
} catch(IOException e) {
// Cache file could not be created.
}
}
if(stream == null) {
stream = new MemoryCacheImageInputStream(inStream);
}
}
return stream;
}
public String getDescription(Locale locale) {
return "NIO Channel ImageInputStream";
}
}
././@LongLink 0000000 0000000 0000000 00000000151 00000000000 011562 L ustar root root jai-imageio-core-1.2/src/share/classes/com/sun/media/imageioimpl/stream/ChannelImageOutputStreamSpi.java jai-imageio-core-1.2/src/share/classes/com/sun/media/imageioimpl/stream/ChannelImageOutputStreamSpi.0000664 0001751 0001751 00000010205 10203036165 032623 0 ustar tille tille /*
* $RCSfile: ChannelImageOutputStreamSpi.java,v $
*
*
* Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistribution of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any
* kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
* WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
* EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
* NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
* USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
* ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
* CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
* REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
* INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for
* use in the design, construction, operation or maintenance of any
* nuclear facility.
*
* $Revision: 1.1 $
* $Date: 2005-02-11 05:01:53 $
* $State: Exp $
*/
package com.sun.media.imageioimpl.stream;
import java.io.File;
import java.io.OutputStream;
import java.io.IOException;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.NonReadableChannelException;
import java.nio.channels.WritableByteChannel;
import java.util.Locale;
import javax.imageio.spi.ImageOutputStreamSpi;
import javax.imageio.stream.FileCacheImageOutputStream;
import javax.imageio.stream.ImageOutputStream;
import javax.imageio.stream.MemoryCacheImageOutputStream;
import com.sun.media.imageio.stream.FileChannelImageOutputStream;
import com.sun.media.imageioimpl.common.PackageUtil;
public class ChannelImageOutputStreamSpi extends ImageOutputStreamSpi {
public ChannelImageOutputStreamSpi() {
super(PackageUtil.getVendor(),
PackageUtil.getVersion(),
WritableByteChannel.class);
}
public ImageOutputStream createOutputStreamInstance(Object output,
boolean useCache,
File cacheDir)
throws IOException {
if(output == null ||
!(output instanceof WritableByteChannel)) {
throw new IllegalArgumentException
("Cannot create ImageOutputStream from "+
output.getClass().getName());
}
ImageOutputStream stream = null;
if(output instanceof FileChannel) {
FileChannel channel = (FileChannel)output;
try {
// The Channel must be readable.
channel.map(FileChannel.MapMode.READ_ONLY,
channel.position(),
1);
stream = new FileChannelImageOutputStream((FileChannel)output);
} catch(NonReadableChannelException nrce) {
// Ignore it.
}
}
if(stream == null) {
OutputStream outStream =
Channels.newOutputStream((WritableByteChannel)output);
if(useCache) {
try {
stream = new FileCacheImageOutputStream(outStream,
cacheDir);
} catch(IOException e) {
// Cache file could not be created.
}
}
if(stream == null) {
stream = new MemoryCacheImageOutputStream(outStream);
}
}
return stream;
}
public String getDescription(Locale locale) {
return "NIO Channel ImageOutputStream";
}
}
jai-imageio-core-1.2/src/share/classes/com/sun/media/imageioimpl/plugins/ 0000775 0001751 0001751 00000000000 11650556211 025434 5 ustar tille tille jai-imageio-core-1.2/src/share/classes/com/sun/media/imageioimpl/plugins/pcx/ 0000775 0001751 0001751 00000000000 11650556211 026226 5 ustar tille tille jai-imageio-core-1.2/src/share/classes/com/sun/media/imageioimpl/plugins/pcx/PCXMetadata.java 0000664 0001751 0001751 00000020277 10670321231 031165 0 ustar tille tille /*
* $RCSfile: PCXMetadata.java,v $
*
*
* Copyright (c) 2007 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistribution of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any
* kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
* WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
* EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
* NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
* USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
* ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
* CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
* REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
* INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for
* use in the design, construction, operation or maintenance of any
* nuclear facility.
*
* $Revision: 1.2 $
* $Date: 2007-09-07 19:12:25 $
* $State: Exp $
*/
package com.sun.media.imageioimpl.plugins.pcx;
import javax.imageio.metadata.IIOInvalidTreeException;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.metadata.IIOMetadataFormatImpl;
import javax.imageio.metadata.IIOMetadataNode;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import com.sun.media.imageioimpl.common.ImageUtil;
public class PCXMetadata extends IIOMetadata implements Cloneable, PCXConstants {
short version;
byte bitsPerPixel;
boolean gotxmin, gotymin;
short xmin, ymin;
int vdpi, hdpi;
int hsize,vsize;
PCXMetadata() {
super(true, null, null, null, null);
reset();
}
public Node getAsTree(String formatName) {
if (formatName.equals(IIOMetadataFormatImpl.standardMetadataFormatName)) {
return getStandardTree();
} else {
throw new IllegalArgumentException("Not a recognized format!");
}
}
public boolean isReadOnly() {
return false;
}
public void mergeTree(String formatName, Node root) throws IIOInvalidTreeException {
if (formatName.equals(IIOMetadataFormatImpl.standardMetadataFormatName)) {
if (root == null) {
throw new IllegalArgumentException("root == null!");
}
mergeStandardTree(root);
} else {
throw new IllegalArgumentException("Not a recognized format!");
}
}
public void reset() {
version = VERSION_3_0;
bitsPerPixel = 0;
gotxmin = false;
gotymin = false;
xmin = 0;
ymin = 0;
vdpi = 72;
hdpi = 72;
hsize = 0;
vsize = 0;
}
public IIOMetadataNode getStandardDocumentNode() {
String versionString;
switch(version) {
case VERSION_2_5:
versionString = "2.5";
break;
case VERSION_2_8_W_PALETTE:
versionString = "2.8 with palette";
break;
case VERSION_2_8_WO_PALETTE:
versionString = "2.8 without palette";
break;
case VERSION_PC_WINDOWS:
versionString = "PC Paintbrush for Windows";
break;
case VERSION_3_0:
versionString = "3.0";
break;
default:
// unknown
versionString = null;
}
IIOMetadataNode documentNode = null;
if(versionString != null) {
documentNode = new IIOMetadataNode("Document");
IIOMetadataNode node = new IIOMetadataNode("FormatVersion");
node.setAttribute("value", versionString);
documentNode.appendChild(node);
}
return documentNode;
}
public IIOMetadataNode getStandardDimensionNode() {
IIOMetadataNode dimensionNode = new IIOMetadataNode("Dimension");
IIOMetadataNode node = null; // scratch node
node = new IIOMetadataNode("HorizontalPixelOffset");
node.setAttribute("value", String.valueOf(xmin));
dimensionNode.appendChild(node);
node = new IIOMetadataNode("VerticalPixelOffset");
node.setAttribute("value", String.valueOf(ymin));
dimensionNode.appendChild(node);
node = new IIOMetadataNode("HorizontalPixelSize");
node.setAttribute("value", String.valueOf(254.0/hdpi));
dimensionNode.appendChild(node);
node = new IIOMetadataNode("VerticalPixelSize");
node.setAttribute("value", String.valueOf(254.0/vdpi));
dimensionNode.appendChild(node);
if(hsize != 0) {
node = new IIOMetadataNode("HorizontalScreenSize");
node.setAttribute("value", String.valueOf(hsize));
dimensionNode.appendChild(node);
}
if(vsize != 0) {
node = new IIOMetadataNode("VerticalScreenSize");
node.setAttribute("value", String.valueOf(vsize));
dimensionNode.appendChild(node);
}
return dimensionNode;
}
private void mergeStandardTree(Node root) throws IIOInvalidTreeException {
Node node = root;
if (!node.getNodeName().equals(IIOMetadataFormatImpl.standardMetadataFormatName))
throw new IIOInvalidTreeException("Root must be " +
IIOMetadataFormatImpl.standardMetadataFormatName,
node);
node = node.getFirstChild();
while (node != null) {
String name = node.getNodeName();
if (name.equals("Dimension")) {
Node child = node.getFirstChild();
while (child != null) {
String childName = child.getNodeName();
if (childName.equals("HorizontalPixelOffset")) {
String hpo = getAttribute(child, "value");
xmin = Short.valueOf(hpo).shortValue();
gotxmin = true;
} else if (childName.equals("VerticalPixelOffset")) {
String vpo = getAttribute(child, "value");
ymin = Short.valueOf(vpo).shortValue();
gotymin = true;
} else if (childName.equals("HorizontalPixelSize")) {
String hps = getAttribute(child, "value");
hdpi = (int)(254.0F/Float.parseFloat(hps) + 0.5F);
} else if (childName.equals("VerticalPixelSize")) {
String vps = getAttribute(child, "value");
vdpi = (int)(254.0F/Float.parseFloat(vps) + 0.5F);
} else if (childName.equals("HorizontalScreenSize")) {
String hss = getAttribute(child, "value");
hsize = Integer.valueOf(hss).intValue();
} else if (childName.equals("VerticalScreenSize")) {
String vss = getAttribute(child, "value");
vsize = Integer.valueOf(vss).intValue();
}
child = child.getNextSibling();
}
}
node = node.getNextSibling();
}
}
private static String getAttribute(Node node, String attrName) {
NamedNodeMap attrs = node.getAttributes();
Node attr = attrs.getNamedItem(attrName);
return attr != null ? attr.getNodeValue() : null;
}
}
jai-imageio-core-1.2/src/share/classes/com/sun/media/imageioimpl/plugins/pcx/PCXImageWriter.java 0000664 0001751 0001751 00000030354 10671577166 031706 0 ustar tille tille /*
* $RCSfile: PCXImageWriter.java,v $
*
*
* Copyright (c) 2007 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistribution of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any
* kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
* WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
* EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
* NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
* USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
* ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
* CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
* REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
* INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for
* use in the design, construction, operation or maintenance of any
* nuclear facility.
*
* $Revision: 1.2 $
* $Date: 2007-09-11 20:45:42 $
* $State: Exp $
*/
package com.sun.media.imageioimpl.plugins.pcx;
import java.awt.Rectangle;
import java.awt.color.ColorSpace;
import java.awt.image.*;
import java.io.IOException;
import java.nio.ByteOrder;
import javax.imageio.*;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.stream.ImageOutputStream;
import com.sun.media.imageioimpl.common.ImageUtil;
public class PCXImageWriter extends ImageWriter implements PCXConstants {
private ImageOutputStream ios;
private Rectangle sourceRegion;
private Rectangle destinationRegion;
private int colorPlanes,bytesPerLine;
private Raster inputRaster = null;
private int scaleX,scaleY;
public PCXImageWriter(PCXImageWriterSpi imageWriterSpi) {
super(imageWriterSpi);
}
public void setOutput(Object output) {
super.setOutput(output); // validates output
if (output != null) {
if (!(output instanceof ImageOutputStream))
throw new IllegalArgumentException("output not instance of ImageOutputStream");
ios = (ImageOutputStream) output;
ios.setByteOrder(ByteOrder.LITTLE_ENDIAN);
} else
ios = null;
}
public IIOMetadata convertImageMetadata(IIOMetadata inData, ImageTypeSpecifier imageType, ImageWriteParam param) {
if(inData instanceof PCXMetadata)
return inData;
return null;
}
public IIOMetadata convertStreamMetadata(IIOMetadata inData, ImageWriteParam param) {
return null;
}
public IIOMetadata getDefaultImageMetadata(ImageTypeSpecifier imageType, ImageWriteParam param) {
PCXMetadata md = new PCXMetadata();
md.bitsPerPixel = (byte) imageType.getSampleModel().getSampleSize()[0];
return md;
}
public IIOMetadata getDefaultStreamMetadata(ImageWriteParam param) {
return null;
}
public void write(IIOMetadata streamMetadata, IIOImage image, ImageWriteParam param) throws IOException {
if (ios == null) {
throw new IllegalStateException("output stream is null");
}
if (image == null) {
throw new IllegalArgumentException("image is null");
}
clearAbortRequest();
processImageStarted(0);
if (param == null)
param = getDefaultWriteParam();
boolean writeRaster = image.hasRaster();
sourceRegion = param.getSourceRegion();
SampleModel sampleModel = null;
ColorModel colorModel = null;
if (writeRaster) {
inputRaster = image.getRaster();
sampleModel = inputRaster.getSampleModel();
colorModel = ImageUtil.createColorModel(null, sampleModel);
if (sourceRegion == null)
sourceRegion = inputRaster.getBounds();
else
sourceRegion = sourceRegion.intersection(inputRaster.getBounds());
} else {
RenderedImage input = image.getRenderedImage();
inputRaster = input.getData();
sampleModel = input.getSampleModel();
colorModel = input.getColorModel();
Rectangle rect = new Rectangle(input.getMinX(), input.getMinY(),
input.getWidth(), input.getHeight());
if (sourceRegion == null)
sourceRegion = rect;
else
sourceRegion = sourceRegion.intersection(rect);
}
if (sourceRegion.isEmpty())
throw new IllegalArgumentException("source region is empty");
IIOMetadata imageMetadata = image.getMetadata();
PCXMetadata pcxImageMetadata = null;
ImageTypeSpecifier imageType = new ImageTypeSpecifier(colorModel, sampleModel);
if(imageMetadata != null) {
// Convert metadata.
pcxImageMetadata = (PCXMetadata)convertImageMetadata(imageMetadata, imageType, param);
} else {
// Use default.
pcxImageMetadata = (PCXMetadata)getDefaultImageMetadata(imageType, param);
}
scaleX = param.getSourceXSubsampling();
scaleY = param.getSourceYSubsampling();
int xOffset = param.getSubsamplingXOffset();
int yOffset = param.getSubsamplingYOffset();
// cache the data type;
int dataType = sampleModel.getDataType();
sourceRegion.translate(xOffset, yOffset);
sourceRegion.width -= xOffset;
sourceRegion.height -= yOffset;
int minX = sourceRegion.x / scaleX;
int minY = sourceRegion.y / scaleY;
int w = (sourceRegion.width + scaleX - 1) / scaleX;
int h = (sourceRegion.height + scaleY - 1) / scaleY;
xOffset = sourceRegion.x % scaleX;
yOffset = sourceRegion.y % scaleY;
destinationRegion = new Rectangle(minX, minY, w, h);
boolean noTransform = destinationRegion.equals(sourceRegion);
// Raw data can only handle bytes, everything greater must be ASCII.
int[] sourceBands = param.getSourceBands();
boolean noSubband = true;
int numBands = sampleModel.getNumBands();
if (sourceBands != null) {
sampleModel = sampleModel.createSubsetSampleModel(sourceBands);
colorModel = null;
noSubband = false;
numBands = sampleModel.getNumBands();
} else {
sourceBands = new int[numBands];
for (int i = 0; i < numBands; i++)
sourceBands[i] = i;
}
ios.writeByte(MANUFACTURER);
ios.writeByte(VERSION_3_0);
ios.writeByte(ENCODING);
int bitsPerPixel = sampleModel.getSampleSize(0);
ios.writeByte(bitsPerPixel);
ios.writeShort(destinationRegion.x); // xmin
ios.writeShort(destinationRegion.y); // ymin
ios.writeShort(destinationRegion.x+destinationRegion.width-1); // xmax
ios.writeShort(destinationRegion.y+destinationRegion.height-1); // ymax
ios.writeShort(pcxImageMetadata.hdpi);
ios.writeShort(pcxImageMetadata.vdpi);
byte[] smallpalette = createSmallPalette(colorModel);
ios.write(smallpalette);
ios.writeByte(0); // reserved
colorPlanes = sampleModel.getNumBands();
ios.writeByte(colorPlanes);
bytesPerLine = destinationRegion.width*bitsPerPixel/8;
bytesPerLine += bytesPerLine %2;
ios.writeShort(bytesPerLine);
if(colorModel.getColorSpace().getType()==ColorSpace.TYPE_GRAY)
ios.writeShort(PALETTE_GRAYSCALE);
else
ios.writeShort(PALETTE_COLOR);
ios.writeShort(pcxImageMetadata.hsize);
ios.writeShort(pcxImageMetadata.vsize);
for(int i=0;i<54;i++)
ios.writeByte(0);
// write image data
if(colorPlanes==1 && bitsPerPixel==1) {
write1Bit();
}
else if(colorPlanes==1 && bitsPerPixel==4) {
write4Bit();
}
else {
write8Bit();
}
// write 256 color palette if needed
if(colorPlanes==1 && bitsPerPixel==8 &&
colorModel.getColorSpace().getType()!=ColorSpace.TYPE_GRAY){
ios.writeByte(12); // Magic number preceding VGA 256 Color Palette Information
ios.write(createLargePalette(colorModel));
}
if (abortRequested()) {
processWriteAborted();
} else {
processImageComplete();
}
}
private void write4Bit() throws IOException {
int[] unpacked = new int[sourceRegion.width];
int[] samples = new int[bytesPerLine];
for (int line = 0; line < sourceRegion.height; line += scaleY) {
inputRaster.getSamples(sourceRegion.x, line + sourceRegion.y, sourceRegion.width, 1, 0, unpacked);
int val=0,dst=0;
for(int x=0,nibble=0;x