Source Code Cross Referenced for ImageToRawTool.java in  » 6.0-JDK-Modules » j2me » com » sun » midp » imageutil » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » 6.0 JDK Modules » j2me » com.sun.midp.imageutil 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


001:        /*
002:         *   
003:         *
004:         * Copyright  1990-2007 Sun Microsystems, Inc. All Rights Reserved.
005:         * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
006:         * 
007:         * This program is free software; you can redistribute it and/or
008:         * modify it under the terms of the GNU General Public License version
009:         * 2 only, as published by the Free Software Foundation.
010:         * 
011:         * This program is distributed in the hope that it will be useful, but
012:         * WITHOUT ANY WARRANTY; without even the implied warranty of
013:         * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
014:         * General Public License version 2 for more details (a copy is
015:         * included at /legal/license.txt).
016:         * 
017:         * You should have received a copy of the GNU General Public License
018:         * version 2 along with this work; if not, write to the Free Software
019:         * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
020:         * 02110-1301 USA
021:         * 
022:         * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
023:         * Clara, CA 95054 or visit www.sun.com if you need additional
024:         * information or have any questions.
025:         *
026:         */
027:
028:        /**
029:         * This tool takes list of input images and XML description of raw image
030:         * format and then converts the input images into raw format images stored
031:         * in the specified output directory.
032:         *
033:         * It understands following command line arguments:
034:         * -format <filename> : XML file with raw image format description
035:         * -out <dirname>     : output folder to place converted images to
036:         * <filename>+        : filenames of input images
037:         *
038:         */package com.sun.midp.imageutil;
039:
040:        import java.io.*;
041:
042:        import javax.xml.parsers.*;
043:
044:        import org.w3c.dom.*;
045:
046:        import java.awt.image.*;
047:        import java.awt.*;
048:        import java.util.Vector;
049:
050:        /**
051:         * Represents image to raw conversion job
052:         */
053:        class ImageToRawJob {
054:            /** XML file name with raw image format */
055:            public String formatXMLFileName = "";
056:
057:            /** Input images file list */
058:            public Vector inImagesFiles = new Vector();
059:
060:            /** Output images directory name */
061:            public String outImagesDirName = "";
062:        }
063:
064:        /**
065:         * Main tool class
066:         */
067:        public class ImageToRawTool {
068:            /**
069:             * for converting image into raw format
070:             */
071:            com.sun.midp.imageutil.ImageToRawConverter converter;
072:
073:            /**
074:             * Romization job to perform
075:             */
076:            private static ImageToRawJob imageToRawJob = null;
077:
078:            /**
079:             * Print debug output while running
080:             */
081:            private static boolean debug = false;
082:
083:            /**
084:             * Print usage info and exit
085:             */
086:            private static boolean printHelp = false;
087:
088:            /**
089:             * raw image file format
090:             */
091:            int rawFormat = ImageToRawConverter.FORMAT_INVALID;
092:
093:            /**
094:             * raw image color format
095:             */
096:            int colorFormat = ImageToRawConverter.FORMAT_INVALID;
097:
098:            /**
099:             * raw image data endianess
100:             */
101:            int endianFormat = ImageToRawConverter.FORMAT_INVALID;
102:
103:            /**
104:             * array of strings used in XML file to specify raw image format
105:             */
106:            static String[] imageFormatStrings = {
107:            // raw file formats
108:                    "Putpixel", "ARGB",
109:                    // endianess
110:                    "Little", "Big",
111:                    // supported pixel formats
112:                    "565", "888", };
113:
114:            /**
115:             * array of constants corresponding to strings above
116:             */
117:            static int[] imageFormats = {
118:                    // raw file formats
119:                    ImageToRawConverter.RAW_FORMAT_PP,
120:                    ImageToRawConverter.RAW_FORMAT_ARGB,
121:                    // endianess
122:                    ImageToRawConverter.INT_FORMAT_LITTLE_ENDIAN,
123:                    ImageToRawConverter.INT_FORMAT_BIG_ENDIAN,
124:                    // supported pixel formats
125:                    ImageToRawConverter.COLOR_FORMAT_565,
126:                    ImageToRawConverter.COLOR_FORMAT_888 };
127:
128:            /**
129:             * Main method
130:             *
131:             * @param args Command line arguments
132:             */
133:            public static void main(String[] args) {
134:                try {
135:                    parseArgs(args);
136:                    if (printHelp) {
137:                        printHelp();
138:                        return;
139:                    }
140:                    if (!validateParsedArgs()) {
141:                        System.exit(1);
142:                    }
143:                    ImageToRawTool tool = new ImageToRawTool();
144:                    tool.convert(imageToRawJob);
145:
146:                } catch (Exception e) {
147:                    e.printStackTrace();
148:                    System.exit(1);
149:                }
150:            }
151:
152:            /**
153:             * Parses command line arguments
154:             *
155:             * @param args command line arguments
156:             */
157:            private static void parseArgs(String[] args) {
158:                imageToRawJob = new ImageToRawJob();
159:
160:                if (args.length < 1)
161:                    printHelp = true;
162:                for (int i = 0; i < args.length; ++i) {
163:                    String arg = args[i];
164:                    if (arg.equals("-format")) {
165:                        imageToRawJob.formatXMLFileName = args[++i];
166:                    } else if (arg.equals("-out")) {
167:                        imageToRawJob.outImagesDirName = args[++i];
168:                    } else if (arg.equals("-debug")) {
169:                        debug = true;
170:                    } else if (arg.equals("-help")) {
171:                        printHelp = true;
172:                    } else {
173:                        imageToRawJob.inImagesFiles.add(arg);
174:                    }
175:                }
176:            }
177:
178:            /**
179:             * Creates a directory structure.
180:             *
181:             * @param fullDirName Full directory path to be created.
182:             * @throws IOException is thrown if directory couldn't be created
183:             */
184:            private static void makeDirectoryTree(String fullDirName)
185:                    throws IOException {
186:
187:                if (debug) {
188:                    System.out.println("mkdir: " + fullDirName);
189:                }
190:            }
191:
192:            /**
193:             * Validates parsed arguments, printing error message
194:             * if some arg is invalid.
195:             *
196:             * @return true, if all arguments are valid
197:             */
198:            private static boolean validateParsedArgs() {
199:                // XML file with raw image format description
200:                File f = new File(imageToRawJob.formatXMLFileName);
201:                if (!f.isFile()) {
202:                    System.err
203:                            .println("Couldn't find raw image format XML file: "
204:                                    + '"'
205:                                    + imageToRawJob.formatXMLFileName
206:                                    + '"');
207:
208:                    return false;
209:                }
210:                // input images file list
211:                if (imageToRawJob.inImagesFiles.isEmpty()) {
212:                    System.err.println("No input images are specified");
213:                    return false;
214:                }
215:
216:                // output images directory
217:                try {
218:                    File outDir = new File(imageToRawJob.outImagesDirName);
219:                    if (!(outDir).exists()) {
220:                        if (!(outDir).mkdirs()) {
221:                            System.err
222:                                    .println("Failed to create output directory: "
223:                                            + '"'
224:                                            + imageToRawJob.outImagesDirName
225:                                            + '"');
226:
227:                            return false;
228:                        }
229:                    }
230:                    imageToRawJob.outImagesDirName = outDir.getCanonicalPath();
231:                } catch (IOException ioe) {
232:                    return false;
233:                }
234:                return true;
235:            }
236:
237:            /**
238:             * Prints usage information
239:             */
240:            private static void printHelp() {
241:                /**
242:                 * Following options are recognized:
243:                 * -format:     XML file describing raw image format.
244:                 * -out:        Output images folder.
245:                 * -help:       Print usage information
246:                 * -debug:      Be verbose: print some debug info while running.
247:                 */
248:                System.err.println("\n" + "  ImageToRawTool arguments:\n\n"
249:                        + "    [-help] \n" + "    [-debug] \n"
250:                        + "    -format <formatXMLFile> \n"
251:                        + "    -out <outputImagesDirectory> \n"
252:                        + "    <imageToConvert>+");
253:            }
254:
255:            /**
256:             * Does the actual romization
257:             *
258:             * @param imageToRawJob romization to perform
259:             * @throws Exception if there was an error during romization
260:             */
261:            public void convert(ImageToRawJob imageToRawJob) throws Exception {
262:
263:                // load XML file as DOM tree
264:                DocumentBuilderFactory domFactory = DocumentBuilderFactory
265:                        .newInstance();
266:
267:                // do not validate input XML file,
268:                // we assume it has been validated before
269:                domFactory.setValidating(false);
270:
271:                DocumentBuilder domBuilder = domFactory.newDocumentBuilder();
272:                Document domDoc = domBuilder.parse(new File(
273:                        imageToRawJob.formatXMLFileName));
274:                if (!searchImageFormat(domDoc.getDocumentElement())) {
275:                    throw new Exception(
276:                            "XML document contains no raw image format description");
277:                }
278:                ;
279:                converter = new ImageToRawConverter(rawFormat, colorFormat,
280:                        endianFormat);
281:
282:                // convert and save images
283:                Vector images = imageToRawJob.inImagesFiles;
284:                for (int i = 0; i < images.size(); i++) {
285:                    String inputFile = (String) images.elementAt(i);
286:                    String fileName = new File(inputFile).getName();
287:                    if (fileName.lastIndexOf('.') > 0) {
288:                        fileName = fileName.replaceFirst("\\.[^.]*?$", ".raw");
289:                    } else
290:                        fileName += ".raw";
291:                    String outputFile = imageToRawJob.outImagesDirName
292:                            + File.separator + fileName;
293:                    convertImageToRaw(inputFile, outputFile);
294:                }
295:            }
296:
297:            /**
298:             * Utility method. Gets BuffredImage data as in array.
299:             *
300:             * @param image BufferedImage to return data for
301:             * @return image data as byte array
302:             */
303:            private int[] getBufferedImageData(BufferedImage image) {
304:                int width = image.getWidth(null);
305:                int height = image.getHeight(null);
306:                BufferedImage bi = new BufferedImage(width, height,
307:                        BufferedImage.TYPE_INT_ARGB);
308:
309:                Graphics g = bi.getGraphics();
310:                try {
311:                    g.drawImage(image, 0, 0, width, height, null);
312:                } finally {
313:                    g.dispose();
314:                }
315:
316:                DataBuffer srcBuf = bi.getData().getDataBuffer();
317:                return ((DataBufferInt) srcBuf).getData();
318:            }
319:
320:            private void convertImageToRaw(String sourceName, String destName)
321:                    throws Exception {
322:
323:                // load image
324:                BufferedImage image = javax.imageio.ImageIO.read(new File(
325:                        sourceName));
326:                int width = image.getWidth(null);
327:                int height = image.getHeight(null);
328:                boolean hasAlpha = image.getColorModel().hasAlpha();
329:                int[] imageData = getBufferedImageData(image);
330:
331:                // convert image
332:                byte[] rawData = converter.convertToRaw(imageData, width,
333:                        height, hasAlpha);
334:
335:                // save image
336:                if (new File(destName).exists())
337:                    System.out.println("Overwrite raw image: " + destName);
338:                else
339:                    System.out.println("Produce raw image: " + destName);
340:
341:                FileOutputStream writer = new FileOutputStream(destName);
342:                writer.write(rawData);
343:                writer.close();
344:            }
345:
346:            /**
347:             * Walks the XML tree and search for raw image format node
348:             *
349:             * @param n current DOM node in document
350:             */
351:            private boolean searchImageFormat(Node n) throws Exception {
352:
353:                if (n.getNodeName().equals("rawimage")
354:                        && (n instanceof  Element)) {
355:                    readRawImageFormat(n);
356:                    return true;
357:                } else {
358:                    NodeList list = n.getChildNodes();
359:                    for (int i = 0; i < list.getLength(); i++) {
360:                        if (searchImageFormat(list.item(i)))
361:                            return true;
362:                    }
363:                }
364:                // Image format description is not found
365:                return false;
366:            }
367:
368:            /**
369:             * Collects raw image format specification
370:             *
371:             * @param n current DOM node in document
372:             * @throws Exception if there was an error during romization
373:             */
374:            private void readRawImageFormat(Node n) throws Exception {
375:                Element e = (Element) n;
376:
377:                String rawFormatStr = e.getAttribute("Format");
378:                rawFormat = ImageToRawConverter.FORMAT_INVALID;
379:                for (int i = 0; i < imageFormatStrings.length; ++i) {
380:                    if (imageFormatStrings[i].equals(rawFormatStr)) {
381:                        rawFormat = imageFormats[i];
382:                        break;
383:                    }
384:                }
385:                if (rawFormat == ImageToRawConverter.FORMAT_INVALID) {
386:                    throw new IllegalArgumentException(
387:                            "Invalid raw file format " + '"' + rawFormatStr
388:                                    + '"');
389:                }
390:
391:                String colorFormatStr = e.getAttribute("Colors");
392:                colorFormat = ImageToRawConverter.FORMAT_INVALID;
393:                for (int i = 0; i < imageFormatStrings.length; ++i) {
394:                    if (imageFormatStrings[i].equals(colorFormatStr)) {
395:                        colorFormat = imageFormats[i];
396:                        break;
397:                    }
398:                }
399:                if (colorFormat == ImageToRawConverter.FORMAT_INVALID) {
400:                    throw new IllegalArgumentException("Invalid color format "
401:                            + '"' + colorFormatStr + '"');
402:                }
403:
404:                String endianFormatStr = e.getAttribute("Endian");
405:                endianFormat = ImageToRawConverter.FORMAT_INVALID;
406:                for (int i = 0; i < imageFormatStrings.length; ++i) {
407:                    if (imageFormatStrings[i].equals(endianFormatStr)) {
408:                        endianFormat = imageFormats[i];
409:                        break;
410:                    }
411:                }
412:                if (endianFormat == ImageToRawConverter.FORMAT_INVALID) {
413:                    throw new IllegalArgumentException("Invalid color format "
414:                            + '"' + endianFormatStr + '"');
415:                }
416:
417:                if (!ImageToRawConverter.isFormatSupported(rawFormat,
418:                        colorFormat)) {
419:                    throw new IllegalArgumentException(
420:                            "Unsupported row image type: " + " format " + '"'
421:                                    + rawFormat + '"' + ", color " + '"'
422:                                    + colorFormat + '"');
423:                }
424:            }
425:
426:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.