Exemplo n.º 1
0
  /**
   * Loads an image from the supplied input stream. Supports formats supported by {@link ImageIO}
   * but not {@link FastImageIO}.
   */
  protected static BufferedImage loadImage(InputStream iis) throws IOException {
    BufferedImage image;

    if (iis instanceof ImageInputStream) {
      image = ImageIO.read(iis);

    } else {
      // if we don't already have an image input stream, create a memory cache image input
      // stream to avoid causing freakout if we're used in a sandbox because ImageIO
      // otherwise use FileCacheImageInputStream which tries to create a temp file
      MemoryCacheImageInputStream mciis = new MemoryCacheImageInputStream(iis);
      image = ImageIO.read(mciis);
      try {
        // this doesn't close the underlying stream
        mciis.close();
      } catch (IOException ioe) {
        // ImageInputStreamImpl.close() throws an IOException if it's already closed;
        // there's no way to find out if it's already closed or not, so we have to check
        // the exception message to determine if this is actually warning worthy
        if (!"closed".equals(ioe.getMessage())) {
          log.warning("Failure closing image input '" + iis + "'.", ioe);
        }
      }
    }

    // finally close our input stream
    StreamUtil.close(iis);

    return image;
  }
Exemplo n.º 2
0
  /**
   * 计算文件的contextType
   *
   * @param fileName
   * @param mapObj
   * @return
   */
  private static String getContentType(String fileName, byte[] mapObj) {
    String contextType = null;
    if (fileName != null) {
      contextType = new MimetypesFileTypeMap().getContentType(fileName);
    }
    if (contextType != null) {
      return contextType;
    }
    ByteArrayInputStream bais = null;
    MemoryCacheImageInputStream mcis = null;
    try {
      bais = new ByteArrayInputStream(mapObj);
      mcis = new MemoryCacheImageInputStream(bais);
      Iterator<ImageReader> itr = ImageIO.getImageReaders(mcis);
      while (itr.hasNext()) {
        ImageReader reader = itr.next();
        if (reader instanceof GIFImageReader) {
          contextType = "image/gif";
        } else if (reader instanceof JPEGImageReader) {
          contextType = "image/jpeg";
        } else if (reader instanceof PNGImageReader) {
          contextType = "image/png";
        } else if (reader instanceof BMPImageReader) {
          contextType = "application/x-bmp";
        }
      }
    } finally {
      if (bais != null) {
        try {
          bais.close();
        } catch (IOException ioe) {

        }
      }
      if (mcis != null) {
        try {
          mcis.close();
        } catch (IOException ioe) {

        }
      }
    }
    return contextType;
  }