01: /*
02: * Copyright 2001-2007 Geert Bevin <gbevin[remove] at uwyn dot com>
03: * Distributed under the terms of either:
04: * - the common development and distribution license (CDDL), v1.0; or
05: * - the GNU Lesser General Public License, v2.1 or later
06: * $Id: JMagickLoader.java 3634 2007-01-08 21:42:24Z gbevin $
07: */
08: package com.uwyn.rife.cmf.loader.image;
09:
10: import com.uwyn.rife.cmf.dam.exceptions.ContentManagerException;
11: import com.uwyn.rife.cmf.loader.ImageContentLoaderBackend;
12: import com.uwyn.rife.config.RifeConfig;
13: import com.uwyn.rife.tools.ExceptionUtils;
14: import com.uwyn.rife.tools.FileUtils;
15: import com.uwyn.rife.tools.ImageWaiter;
16: import java.awt.Image;
17: import java.awt.Toolkit;
18: import java.io.File;
19: import java.util.Set;
20: import magick.ImageInfo;
21: import magick.MagickImage;
22: import magick.MagickProducer;
23:
24: /**
25: * This is an image loader back-end that uses JMagick to load image files, if its
26: * classes are present in the classpath.
27: * <p>More information about JMagick can be obtained from <a
28: * href="http://www.yeo.id.au/jmagick">http://www.yeo.id.au/jmagick</a>.
29: *
30: * @author Geert Bevin (gbevin[remove] at uwyn dot com)
31: * @version $Revision: 3634 $
32: * @since 1.0
33: */
34: public class JMagickLoader extends ImageContentLoaderBackend {
35: public Image loadFromBytes(byte[] data, Set<String> errors)
36: throws ContentManagerException {
37: return new LoaderDelegate().load(data, errors);
38: }
39:
40: public boolean isBackendPresent() {
41: try {
42: return null != Class.forName("magick.ImageInfo");
43: } catch (Throwable e) {
44: return false;
45: }
46: }
47:
48: private static class LoaderDelegate {
49: public Image load(byte[] data, Set<String> errors)
50: throws ContentManagerException {
51: Image image = null;
52: File tmp_file = null;
53: try {
54:
55: tmp_file = File.createTempFile("cmfjmagick", "",
56: new File(RifeConfig.Global.getTempPath()));
57: FileUtils.writeBytes(data, tmp_file);
58:
59: ImageInfo image_info = new ImageInfo(tmp_file
60: .getAbsolutePath());
61: MagickImage magick = new MagickImage();
62: magick.readImage(image_info);
63:
64: // if it's an unsupported JMagick image, return null
65: if (0 == magick.getMagick().length()) {
66: return null;
67: }
68:
69: // create an awt image from it and wait 'till it's fully loaded
70: MagickProducer producer = new MagickProducer(magick);
71: image = Toolkit.getDefaultToolkit().createImage(
72: producer);
73: ImageWaiter.wait(image);
74: } catch (Throwable e) {
75: if (errors != null) {
76: errors
77: .add(ExceptionUtils
78: .getExceptionStackTrace(e));
79: }
80:
81: image = null;
82: } finally {
83: if (tmp_file != null) {
84: tmp_file.delete();
85: }
86: }
87:
88: return image;
89: }
90: }
91: }
|