Develop and Download Open Source Software

Browse Subversion Repository

Contents of /dvibrowser-1.2.0/trunk/dvicore/src/main/java/jp/sourceforge/dvibrowser/dvicore/cli/tools/ConvertToImage.java

Parent Directory Parent Directory | Revision Log Revision Log


Revision 123 - (show annotations) (download) (as text)
Fri Mar 4 13:56:55 2011 UTC (13 years, 2 months ago) by nagaotakeyuki
File MIME type: text/x-java
File size: 12701 byte(s)
Applet support.
1 /*
2 * Copyright (c) 2009, Takeyuki Nagao
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or
6 * without modification, are permitted provided that the
7 * following conditions are met:
8 *
9 * * Redistributions of source code must retain the above
10 * copyright notice, this list of conditions and the
11 * following disclaimer.
12 * * Redistributions in binary form must reproduce the above
13 * copyright notice, this list of conditions and the
14 * following disclaimer in the documentation and/or other
15 * materials provided with the distribution.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
18 * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
19 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
20 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
22 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
24 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
25 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
27 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
29 * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
30 * OF SUCH DAMAGE.
31 */
32 package jp.sourceforge.dvibrowser.dvicore.cli.tools;
33
34 import java.awt.image.BufferedImage;
35 import java.io.File;
36 import java.io.FileOutputStream;
37 import java.io.FilterOutputStream;
38 import java.io.OutputStream;
39 import java.io.PrintWriter;
40 import java.io.StringWriter;
41 import java.net.URL;
42 import java.util.ArrayList;
43 import java.util.Set;
44 import java.util.logging.Level;
45 import java.util.logging.Logger;
46
47 import javax.imageio.ImageIO;
48
49 import jp.sourceforge.dvibrowser.dvicore.DviException;
50 import jp.sourceforge.dvibrowser.dvicore.DviObject;
51 import jp.sourceforge.dvibrowser.dvicore.DviPaperSize;
52 import jp.sourceforge.dvibrowser.dvicore.DviRect;
53 import jp.sourceforge.dvibrowser.dvicore.DviResolution;
54 import jp.sourceforge.dvibrowser.dvicore.api.DviContext;
55 import jp.sourceforge.dvibrowser.dvicore.api.DviContextSupport;
56 import jp.sourceforge.dvibrowser.dvicore.api.DviDocument;
57 import jp.sourceforge.dvibrowser.dvicore.api.DviPage;
58 import jp.sourceforge.dvibrowser.dvicore.ctx.DefaultDviContext;
59 import jp.sourceforge.dvibrowser.dvicore.gui.swing.ViewSpec;
60 import jp.sourceforge.dvibrowser.dvicore.image.split.ImageFileConfig;
61 import jp.sourceforge.dvibrowser.dvicore.util.Benchmark;
62 import jp.sourceforge.dvibrowser.dvicore.util.DviUtils;
63 import jp.sourceforge.dvibrowser.dvicore.util.ZipBuilder;
64
65
66 public class ConvertToImage
67 extends DviObject
68 {
69 private static final String OPT_SHRINK_FACTOR = "--shrink-factor=";
70 private static final String OPT_DPI = "--dpi=";
71 private static final String OPT_OUTPUT_FILE = "--output-file=";
72 private static final String OPT_RESOURCES_FILE = "--resources-file=";
73 private static final String OPT_PAPER_SIZE = "--paper-size=";
74 private static final String OPT_USE_BBOX = "--use-bbox=";
75 private static final String OPT_PADDING = "--padding=";
76 private static final Logger LOGGER = Logger.getLogger(ConvertToImage.class
77 .getName());
78
79 public static class Config
80 extends DviObject
81 {
82 private final ViewSpec viewSpec;
83 private final ArrayList<File> inputs = new ArrayList<File>();
84 private boolean useBoundingBox;
85 private File outputFile;
86 private DviPaperSize paperSize;
87 private ImageFileConfig imageFileConfig;
88 private int padding;
89 private File resourcesFile;
90
91 public Config(DviContextSupport dcs) {
92 super(dcs);
93 viewSpec = new ViewSpec(dcs);
94 try {
95 setPaperSize(getDviContext().getDefaultPaperSize());
96 } catch (DviException e) {
97 DviUtils.logStackTrace(LOGGER, Level.WARNING, e);
98 setPaperSize(DviPaperSize.FALLBACK);
99 }
100 // TODO: outsource the config.
101 imageFileConfig = ImageFileConfig.PNG;
102 padding = 0;
103 }
104
105 public void setDpi(int dpi)
106 {
107 viewSpec.setResolution(new DviResolution(dpi, viewSpec.getResolution().shrinkFactor()));
108 }
109
110 public void setShrinkFactor(int sf)
111 {
112 viewSpec.setResolution(new DviResolution(viewSpec.getResolution().dpi(), sf));
113 }
114
115 public ViewSpec getViewSpec() {
116 return viewSpec;
117 }
118
119 public void setUseBoundingBox(boolean crop) {
120 this.useBoundingBox = crop;
121 }
122
123 public boolean useBoundingBox() { return useBoundingBox; }
124
125 public void setOutputFile(File outputFile) {
126 if (outputFile != null) {
127 this.outputFile = outputFile;
128 } else {
129 this.outputFile = null;
130 }
131 }
132
133 public void addInputFile(File file)
134 {
135 if (file != null) {
136 inputs.add(file);
137 } else {
138 LOGGER.warning("Input file is null. Ignored.");
139 }
140 }
141
142 public File getOutputFile() {
143 return outputFile;
144 }
145
146 public DviPaperSize getPaperSize() {
147 return paperSize;
148 }
149
150
151 public ArrayList<File> getInputs() {
152 return inputs;
153 }
154
155 public void parseArguments(String [] args) throws DviException
156 {
157 final DviContext ctx = getDviContext();
158 for (int i=0; i<args.length; i++) {
159 String a = args[i];
160 if (a.startsWith(OPT_DPI)) {
161 int dpi = Integer.parseInt(a.substring(OPT_DPI.length()));
162 setShrinkFactor(dpi);
163 } else if (a.startsWith(OPT_SHRINK_FACTOR)) {
164 int sf = Integer.parseInt(a.substring(OPT_SHRINK_FACTOR.length()));
165 setShrinkFactor(sf);
166 } else if (a.startsWith(OPT_PADDING)) {
167 int padding = Integer.parseInt(a.substring(OPT_PADDING.length()));
168 setPaddingSize(padding);
169 } else if (a.startsWith(OPT_PAPER_SIZE)) {
170 String s = a.substring(OPT_PAPER_SIZE.length());
171 DviPaperSize paperSize = ctx.findPaperSizeByName(s);
172 if (paperSize == null) {
173 throw new DviException("Unrecognized papersize: " + s);
174 }
175 } else if (a.startsWith(OPT_RESOURCES_FILE)) {
176 String s = a.substring(OPT_RESOURCES_FILE.length()).trim();
177 if (!"".equals(s)) {
178 setResourcesFile(new File(s));
179 } else {
180 throw new DviException("Output filename is empty.");
181 }
182 } else if (a.startsWith(OPT_OUTPUT_FILE)) {
183 String s = a.substring(OPT_OUTPUT_FILE.length()).trim();
184 if (!"".equals(s)) {
185 setOutputFile(new File(s));
186 } else {
187 throw new DviException("Output filename is empty.");
188 }
189 } else if (a.startsWith(OPT_USE_BBOX)) {
190 String s = a.substring(OPT_USE_BBOX.length()).trim();
191 if ("yes".equalsIgnoreCase(s)) {
192 setUseBoundingBox(true);
193 } else if ("no".equalsIgnoreCase(s)) {
194 setUseBoundingBox(false);
195 } else {
196 throw new DviException("Invalid parameter value: " + a);
197 }
198 } else if (a.startsWith("-")) {
199 throw new DviException("Unrecognized commandline option: " + a);
200 } else {
201 for (; i<args.length; i++) {
202 a = args[i];
203 addInputFile(new File(a));
204 }
205 }
206 }
207 }
208
209 private void setResourcesFile(File file) {
210 this.resourcesFile = file;
211 }
212
213 public File getResourcesFile() {
214 return resourcesFile;
215 }
216
217 private void setPaddingSize(int padding) {
218 this.setPadding(padding);
219 }
220
221 public void setPaperSize(DviPaperSize paperSize) {
222 this.paperSize = paperSize;
223 }
224
225 public ImageFileConfig getImageFileConfig()
226 {
227 return imageFileConfig;
228 }
229
230 public void setImageFileConfig(ImageFileConfig imageFileConfig) {
231 this.imageFileConfig = imageFileConfig;
232 }
233
234 public static String getUsage()
235 {
236 StringWriter sw = new StringWriter();
237 PrintWriter pw = new PrintWriter(sw);
238 pw.println("usage: java " + ConvertToImage.class.getName() + " [options] <input-files>");
239 pw.println(" options: ");
240 pw.println(" --dpi=N Set output DPI to N");
241 pw.println(" --shrink-factor=N Set shrink factor to N (1--1024)");
242 pw.println(" --output-file=F Set output zip file to F");
243 pw.println(" --resources-file=F Set resources file to F");
244 pw.println(" --padding=N Set padding size to N");
245 return sw.toString();
246 }
247
248 public void showUsage()
249 {
250 System.err.println(getUsage());
251 }
252
253 public boolean isValid() {
254 return getInputs().size() > 0;
255 }
256
257 public void setPadding(int padding) {
258 this.padding = padding;
259 }
260
261 public int getPadding() {
262 return padding;
263 }
264 }
265
266 public ConvertToImage(DviContextSupport dcs) {
267 super(dcs);
268 }
269
270 public int convert(Config config) throws Exception {
271 DviContext ctx = getDviContext();
272 ViewSpec vs = config.getViewSpec();
273 DviResolution res = vs.getResolution();
274 File outputFile = config.getOutputFile();
275 OutputStream os = null;
276 if (outputFile != null) {
277 if (!outputFile.getName().toLowerCase().endsWith(".zip")) {
278 outputFile = new File(outputFile.getParentFile(), outputFile.getName() + ".zip");
279 }
280 os = new FileOutputStream(outputFile);
281 LOGGER.info("Writing outputs to " + outputFile);
282 } else {
283 os = new FilterOutputStream(System.out) {
284 @Override
285 public void close()
286 {
287 // We don't close the stdout.
288 }
289 };
290 }
291 ZipBuilder zb = new ZipBuilder(os);
292
293 try {
294 for (File file : config.getInputs()) {
295 try {
296 DviDocument doc = ctx.openDviDocument(file);
297 LOGGER.info("Processing file: " + file);
298 for (int i=0; i<doc.getTotalPages(); i++) {
299 DviPage page = doc.getPage(i);
300 LOGGER.info("Processing page " + (i + 1) + "/" + doc.getTotalPages());
301 DviRect bbox;
302 if (config.useBoundingBox()) {
303 bbox =
304 ctx.getDviToolkit().computeBoundingBox(page, res);
305 } else {
306 bbox = config.getPaperSize().toBoundingBox(res);
307 }
308 bbox = bbox.addPadding(config.getPadding());
309
310 BufferedImage img = ctx.getDviToolkit().renderToBufferedImage(page, bbox, vs);
311 if (img == null) {
312 throw new DviException("Failed to render page " + (i + 1));
313 }
314
315 OutputStream imageOut = zb.openOutputStream
316 (String.format("%04d%s", i+1, config.getImageFileConfig().getImageExtension()));
317 try {
318 ImageIO.write(img, config.getImageFileConfig().getImageType(), imageOut);
319 } finally {
320 DviUtils.silentClose(imageOut);
321 }
322 }
323 } catch (DviException e) {
324 DviUtils.logStackTrace(LOGGER, Level.SEVERE, e);
325 throw e;
326 }
327 }
328 } finally {
329 DviUtils.silentClose(zb);
330 }
331 return 0;
332 }
333
334 public static void main(String[] args)
335 {
336 try {
337 DefaultDviContext ctx = new DefaultDviContext();
338
339 Config config = new Config(ctx);
340 config.parseArguments(args);
341
342 if (!config.isValid()) {
343 config.showUsage();
344 throw new DviException
345 ("Unrecognized command line: " + DviUtils.join(" ", args));
346 }
347
348 File resourcesFile = config.getResourcesFile();
349
350 if (resourcesFile != null) {
351 ctx.setRecordResources(true);
352 }
353
354 Benchmark benchmark = new Benchmark();
355 benchmark.begin("dvi rendering");
356 benchmark.addSample();
357 ConvertToImage app = new ConvertToImage(ctx);
358 int retcode = app.convert(config);
359 benchmark.end();
360
361 if (resourcesFile != null) {
362 Set<URL> resources = ctx.getRecordedResources();
363 FileOutputStream fos = new FileOutputStream(resourcesFile);
364 PrintWriter out = new PrintWriter(fos);
365 for (URL url : resources) {
366 out.println(url);
367 }
368 out.flush();
369 out.close();
370 fos.close();
371 }
372
373 LOGGER.info("Finished: " + benchmark.format());
374 // INT_ARGB: Finished: Benchmark result: dvi rendering: 1 samples in 68.182 sec. 0.015 samples/sec. 68182 msec./sample.
375 // INT_RGB: Finished: Benchmark result: dvi rendering: 1 samples in 62.976 sec. 0.016 samples/sec. 62976 msec./sample.
376 System.exit(retcode);
377 } catch (Exception e) {
378 DviUtils.logStackTrace(LOGGER, Level.WARNING, e);
379 System.exit(1);
380 }
381 }
382
383 }

Back to OSDN">Back to OSDN
ViewVC Help
Powered by ViewVC 1.1.26