View Javadoc

1   package com.atlassian.core.util.thumbnail.loader;
2   
3   import com.atlassian.core.util.ImageInfo;
4   import com.atlassian.core.util.ReusableBufferedInputStream;
5   import com.google.common.base.Optional;
6   import com.google.common.collect.ImmutableList;
7   
8   import java.awt.image.BufferedImage;
9   import java.io.IOException;
10  import java.util.List;
11  
12  public class ImageFactory
13  {
14  
15      /**
16       * Instances of all available image loaders. Loaders will be run in sequence and
17       * first not null BufferedImage instance will be returned.
18       * <p/>
19       * Sequence of Loaders is important!
20       */
21      private static final List<ImageLoader> imageLoaders = ImmutableList.of(
22              new DefaultImageLoader(),
23  			new FixedImageLoader(),
24              new CMYKImageLoader(),
25              new JAIImageLoader()
26      );
27  
28      /**
29       * Loads image to memory from specified inputStream.
30       *
31       * @return Loaded Image or null if none of Loaders could load the image
32       */
33      public BufferedImage loadImage(ReusableBufferedInputStream inputStream) throws IOException
34      {
35          IOException lastException = null;
36          Optional<BufferedImage> image = Optional.absent();
37          final ImageInfo imageInfo = getImageInfo(inputStream);
38  
39          for (ImageLoader imageLoader : imageLoaders)
40          {
41              try
42              {
43                  image = imageLoader.loadImage(inputStream, imageInfo);
44                  if (image.isPresent())
45                  {
46  					break;
47  				}
48              }
49              catch (IOException e)
50              {
51                  lastException = e;
52              }
53              finally
54              {
55                  inputStream.reset();
56              }
57          }
58          if (image.isPresent())
59          {
60              return image.get();
61          }
62          throw new IOException("Cannot read image - none of loaders was able to create image", lastException);
63      }
64  
65      private ImageInfo getImageInfo(ReusableBufferedInputStream inputStream) throws IOException
66      {
67          final ImageInfo imageInfo = new ImageInfo();
68          try
69          {
70              imageInfo.setInput(inputStream);
71              if(!imageInfo.check())
72              {
73                  return null;
74              }
75          }
76          finally
77          {
78              inputStream.reset();
79          }
80          return imageInfo;
81      }
82  }