1 10 package org.mmbase.util.images; 11 12 import java.util.*; 13 import java.io.*; 14 import java.util.regex.*; 15 16 import org.mmbase.util.externalprocess.CommandLauncher; 17 import org.mmbase.util.externalprocess.ProcessException; 18 19 import org.mmbase.util.logging.Logging; 20 import org.mmbase.util.logging.Logger; 21 22 29 public class ImageMagickImageInformer implements ImageInformer { 30 31 private static final Logger log = Logging.getLoggerInstance(ImageMagickImageInformer.class); 32 33 private static String identifyPath = "identify"; 36 private static final Pattern IDENTIFY_PATTERN = Pattern.compile(".+?\\s.*?\\s(\\d+)x(\\d+).*"); 37 38 public void init(Map params) { 39 String identifyCommand = "identify"; 40 41 if(System.getProperty("os.name") != null && System.getProperty("os.name").startsWith("Windows")) { 42 identifyCommand += ".exe"; 45 } 46 47 } 48 49 50 public Dimension getDimension(byte[] input) throws IOException { 51 52 File file = File.createTempFile("ImageMagickImageInformer", null); 53 FileOutputStream image = new FileOutputStream(file); 54 image.write(input); 55 image.close(); 56 57 try { 58 CommandLauncher launcher = new CommandLauncher("ImageMagick's identify"); 59 ByteArrayOutputStream errorStream = new ByteArrayOutputStream(); 60 ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); 61 62 launcher.execute(identifyPath, new String [] {file.getCanonicalPath()}); 63 launcher.waitAndRead(outputStream, errorStream); 64 String result = new String (outputStream.toByteArray()).trim(); 65 Matcher matcher = IDENTIFY_PATTERN.matcher(result); 66 if (! matcher.matches()) throw new IOException("'" + result + "' doesn't match " + IDENTIFY_PATTERN); 67 return new Dimension(Integer.parseInt(matcher.group(1)), Integer.parseInt(matcher.group(2))); 68 } catch (UnsupportedEncodingException uee) { 69 log.error(uee.toString()); 70 } catch (ProcessException pe) { 71 log.error(pe.toString()); 72 } finally { 73 file.delete(); 74 } 75 return new Dimension(0, 0); 76 77 } 78 public static void main(String [] args) { 79 try { 80 File file = new File(args[0]); 81 FileInputStream input = new FileInputStream(file); 82 ByteArrayOutputStream bytes = new ByteArrayOutputStream(); 83 int b = input.read(); 84 while (b != -1) { 85 bytes.write(b); 86 b = input.read(); 87 } 88 input.close(); 89 byte[] ba = bytes.toByteArray(); 90 ImageInformer imii = new ImageMagickImageInformer(); 91 ImageInformer jaiii = new JAIImageInformer(); 92 ImageInformer dii = new DummyImageInformer(); 93 System.out.println("Image magick " + imii.getDimension(ba)); 94 System.out.println("JAI " + jaiii.getDimension(ba)); 95 System.out.println("Dummy " + dii.getDimension(ba)); 96 } catch (IOException ioe) { 97 throw new RuntimeException (ioe); 98 } 99 100 } 101 102 } 103 | Popular Tags |