示例#1
0
  public static BufferedImage getImage(File imageFile) {

    BufferedImage al = null;

    try {

      String imageFileName = imageFile.getName();

      String imageFormat = imageFileName.substring(imageFileName.lastIndexOf('.') + 1);

      Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(imageFormat);

      ImageReader reader = readers.next();
      if (reader == null) {

        JOptionPane.showConfirmDialog(
            null, "Need to install JAI Image I/O package./nhttps://jai-imageio.dev.java.net");

        return null;
      }
      ImageInputStream iis = ImageIO.createImageInputStream(imageFile);
      reader.setInput(iis);
      al = reader.read(0);
      reader.dispose();

    } catch (IOException ioe) {
      System.err.println(ioe.getMessage());
    } catch (Exception e) {
      System.err.println(e.getMessage());
    }
    return al;
  }
示例#2
0
  /**
   * 图片文件转换为tif格式
   *
   * @param imageFile 文件路径
   * @param imageFormat 文件扩展名
   * @return
   */
  public static File createImage(File imageFile, String imageFormat) {
    File tempFile = null;
    try {
      Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(imageFormat);
      ImageReader reader = readers.next();

      ImageInputStream iis = ImageIO.createImageInputStream(imageFile);
      reader.setInput(iis);
      // Read the stream metadata
      IIOMetadata streamMetadata = reader.getStreamMetadata();

      // Set up the writeParam
      TIFFImageWriteParam tiffWriteParam = new TIFFImageWriteParam(Locale.CHINESE);
      tiffWriteParam.setCompressionMode(ImageWriteParam.MODE_DISABLED);

      // Get tif writer and set output to file
      Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("tiff");
      ImageWriter writer = writers.next();

      BufferedImage bi = reader.read(0);
      IIOImage image = new IIOImage(bi, null, reader.getImageMetadata(0));
      tempFile = tempImageFile(imageFile);
      ImageOutputStream ios = ImageIO.createImageOutputStream(tempFile);
      writer.setOutput(ios);
      writer.write(streamMetadata, image, tiffWriteParam);
      ios.close();

      writer.dispose();
      reader.dispose();

    } catch (IOException e) {
      e.printStackTrace();
    }
    return tempFile;
  }
示例#3
0
    @Override
    protected void ensureContentAvailable() {
      if (!isContentAvailable()) {
        try {
          contentURL = createWadoURL(getMimeType(), -1);
        } catch (Exception e) {
          log.error("Unable to get image document WADO URL!", e);
        }
        try {
          Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName("dicom");
          if (readers != null && readers.hasNext()) {
            List<org.dcm4chee.archive.entity.File> files =
                ((TCQueryLocal) JNDIUtils.lookup(TCQueryLocal.JNDI_NAME))
                    .findInstanceByUID(getSOPInstanceUID())
                    .getFiles();
            String fsId = files.get(0).getFileSystem().getDirectoryPath();
            String fileId = files.get(0).getFilePath();

            ImageReader reader = readers.next();
            reader.setInput(
                ImageIO.createImageInputStream(
                    fsId.startsWith("tar:")
                        ? TarRetrieveDelegate.getInstance().retrieveFileFromTar(fsId, fileId)
                        : FileUtils.resolve(new File(fsId, fileId))),
                true);
            contentImage = reader.read(0);
            thumbnailImage = toThumbnailImage(contentImage);
          }
        } catch (Exception e) {
          log.error("Unable to convert encapsulated image to image!", e);
        }
      }
    }
  /**
   * Gets a list of <code>IIOImage</code> objects for an image file.
   *
   * @param imageFile input image file. It can be any of the supported formats, including TIFF,
   *     JPEG, GIF, PNG, BMP, JPEG, and PDF if GPL Ghostscript is installed
   * @return a list of <code>IIOImage</code> objects
   * @throws Exception
   */
  public static List<IIOImage> getIIOImageList(File imageFile) throws IOException {
    File workingTiffFile = null;

    ImageReader reader = null;
    ImageInputStream iis = null;

    try {
      // convert PDF to TIFF
      if (imageFile.getName().toLowerCase().endsWith(".pdf")) {
        workingTiffFile = PdfUtilities.convertPdf2Tiff(imageFile);
        imageFile = workingTiffFile;
      }

      List<IIOImage> iioImageList = new ArrayList<IIOImage>();

      String imageFileName = imageFile.getName();
      String imageFormat = imageFileName.substring(imageFileName.lastIndexOf('.') + 1);
      if (imageFormat.matches("(pbm|pgm|ppm)")) {
        imageFormat = "pnm";
      } else if (imageFormat.equals("jp2")) {
        imageFormat = "jpeg2000";
      }
      Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(imageFormat);
      reader = readers.next();

      if (reader == null) {
        throw new RuntimeException(
            "Need to install JAI Image I/O package.\nhttps://jai-imageio.dev.java.net");
      }

      iis = ImageIO.createImageInputStream(imageFile);
      reader.setInput(iis);

      int imageTotal = reader.getNumImages(true);

      for (int i = 0; i < imageTotal; i++) {
        //                IIOImage oimage = new IIOImage(reader.read(i), null,
        // reader.getImageMetadata(i));
        IIOImage oimage = reader.readAll(i, reader.getDefaultReadParam());
        iioImageList.add(oimage);
      }

      return iioImageList;
    } finally {
      try {
        if (iis != null) {
          iis.close();
        }
        if (reader != null) {
          reader.dispose();
        }
      } catch (Exception e) {
        // ignore
      }
      if (workingTiffFile != null && workingTiffFile.exists()) {
        workingTiffFile.delete();
      }
    }
  }
示例#5
0
  public ImageIODecoder(String formatName) {
    super();
    this.formatName = formatName;

    if (!ImageIO.getImageReadersByFormatName(formatName).hasNext()) {
      throw new RuntimeException("No ImageIO reader found for " + formatName);
    }
  }
示例#6
0
 @Test
 public void metaDataTest() throws IOException {
   Iterator<ImageReader> itrR = ImageIO.getImageReadersByFormatName("jpg");
   ImageReader imageReader = itrR.next();
   ImageInputStream imageInputStream = ImageIO.createImageInputStream(new File(SRCIMG));
   imageReader.setInput(imageInputStream, true);
   IIOMetadata ioMetadata = imageReader.getImageMetadata(0);
   System.out.println(ioMetadata.toString());
 }
  /**
   * Write world image extensions : TFW, PRJ, TAB
   *
   * @param request
   * @param file
   * @param in
   * @throws IOException
   */
  private void writeWorldImageExt(WcsReaderRequest request, File file) throws IOException {

    String baseFilePath = file.getPath().substring(0, file.getPath().lastIndexOf('.'));

    // Compute image size and image transformed BBOX
    ReferencedEnvelope transformedBBox;
    AffineTransform transform;

    int width = -1;
    int height = -1;
    String ext = FileUtils.extension(file);

    try {
      final Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(ext.substring(1));

      while (readers.hasNext() && width < 0 && height < 0) {
        ImageInputStream stream = null;
        try {
          ImageReader reader = readers.next();
          stream = ImageIO.createImageInputStream(file.getAbsoluteFile());
          reader.setInput(stream, true, false);
          width = reader.getWidth(0);
          height = reader.getHeight(0);
          break;
        } catch (Exception e) {
          width = -1;
          height = -1;
          // try next reader;
        } finally {
          if (stream != null) {
            stream.close();
          }
        }
      }

      transformedBBox = request.requestBbox.transform(request.responseCRS, true, 10);
      if (width < 0) {
        width = (int) Math.round(transformedBBox.getWidth() / request.crsResolution());
      }

      if (height < 0) {
        height = (int) Math.round(transformedBBox.getHeight() / request.crsResolution());
      }

      Rectangle imageSize = new Rectangle(width, height);
      transform = RendererUtilities.worldToScreenTransform(transformedBBox, imageSize);
      transform.invert();

    } catch (Exception e) {
      throw new ExtractorException(e);
    }

    // Generate TFW TAB PRJ files
    createWorldFile(transform, ext, baseFilePath);
    createTABFile(transformedBBox, width, height, baseFilePath, ext);
    createPrjFile(request.responseCRS, baseFilePath);
  }
 static {
   final Iterator<ImageReader> imageReaders = ImageIO.getImageReadersByFormatName("png");
   if (!imageReaders.hasNext()) {
     throw new SolrException(
         SolrException.ErrorCode.SERVER_ERROR,
         "Can't find png image reader, neaded for heatmaps!");
   }
   ImageReader imageReader = imageReaders.next();
   imageReaderSpi = imageReader.getOriginatingProvider();
 }
 /**
  * Decode JBIG2 data using Java ImageIO library.
  *
  * <p>{@inheritDoc}
  */
 public void decode(
     InputStream compressedData, OutputStream result, COSDictionary options, int filterIndex)
     throws IOException {
   /**
    * A working JBIG2 ImageIO plugin is needed to decode JBIG2 encoded streams. The following is
    * known to be working. It can't be bundled with PDFBox because of an incompatible license.
    * http://code.google.com/p/jbig2-imageio/
    */
   Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName("JBIG2");
   if (!readers.hasNext()) {
     LOG.error("Can't find an ImageIO plugin to decode the JBIG2 encoded datastream.");
     return;
   }
   ImageReader reader = readers.next();
   COSDictionary decodeP = (COSDictionary) options.getDictionaryObject(COSName.DECODE_PARMS);
   COSInteger bits = (COSInteger) options.getDictionaryObject(COSName.BITS_PER_COMPONENT);
   COSStream st = null;
   if (decodeP != null) {
     st = (COSStream) decodeP.getDictionaryObject(COSName.JBIG2_GLOBALS);
   }
   if (st != null) {
     reader.setInput(
         ImageIO.createImageInputStream(
             new SequenceInputStream(st.getFilteredStream(), compressedData)));
   } else {
     reader.setInput(ImageIO.createImageInputStream(compressedData));
   }
   BufferedImage bi = reader.read(0);
   reader.dispose();
   if (bi != null) {
     // I am assuming since JBIG2 is always black and white
     // depending on your renderer this might or might be needed
     if (bi.getColorModel().getPixelSize() != bits.intValue()) {
       if (bits.intValue() != 1) {
         LOG.error("Do not know how to deal with JBIG2 with more than 1 bit");
         return;
       }
       BufferedImage packedImage =
           new BufferedImage(bi.getWidth(), bi.getHeight(), BufferedImage.TYPE_BYTE_BINARY);
       Graphics graphics = packedImage.getGraphics();
       graphics.drawImage(bi, 0, 0, null);
       graphics.dispose();
       bi = packedImage;
     }
     DataBuffer dBuf = bi.getData().getDataBuffer();
     if (dBuf.getDataType() == DataBuffer.TYPE_BYTE) {
       result.write(((DataBufferByte) dBuf).getData());
     } else {
       LOG.error("Image data buffer not of type byte but type " + dBuf.getDataType());
     }
   } else {
     LOG.error("Something went wrong when decoding the JBIG2 encoded datastream.");
   }
 }
示例#10
0
  @Test
  public void imageReaderTest() throws IOException {
    Iterator<ImageReader> irs = ImageIO.getImageReadersByFormatName("jpg");
    ImageReader imageReader = irs.next();

    ImageInputStream imageInputStream = ImageIO.createImageInputStream(new File(SRCIMG));

    imageReader.setInput(imageInputStream, true);

    BufferedImage bufferedImage = imageReader.read(0);
    System.out.println(bufferedImage.getWidth());
  }
示例#11
0
文件: ImageUtil.java 项目: gahzl/bbs
 /*
  * 图片裁剪通用接口
  */
 public static void cutImage(String src, String dest, int x, int y, int w, int h)
     throws IOException {
   Iterator iterator = ImageIO.getImageReadersByFormatName("jpg");
   ImageReader reader = (ImageReader) iterator.next();
   InputStream in = new FileInputStream(src);
   ImageInputStream iis = ImageIO.createImageInputStream(in);
   reader.setInput(iis, true);
   ImageReadParam param = reader.getDefaultReadParam();
   Rectangle rect = new Rectangle(x, y, w, h);
   param.setSourceRegion(rect);
   BufferedImage bi = reader.read(0, param);
   ImageIO.write(bi, "jpg", new File(dest));
 }
  /**
   * Creates a list of TIFF image files from an image file. It basically converts images of other
   * formats to TIFF format, or a multi-page TIFF image to multiple TIFF image files.
   *
   * @param imageFile input image file
   * @param index an index of the page; -1 means all pages, as in a multi-page TIFF image
   * @return a list of TIFF image files
   * @throws Exception
   */
  public static List<File> createTiffFiles(File imageFile, int index) throws IOException {
    List<File> tiffFiles = new ArrayList<File>();

    String imageFileName = imageFile.getName();
    String imageFormat = imageFileName.substring(imageFileName.lastIndexOf('.') + 1);

    Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(imageFormat);
    ImageReader reader = readers.next();

    if (reader == null) {
      throw new RuntimeException(
          "Need to install JAI Image I/O package.\nhttps://jai-imageio.dev.java.net");
    }

    ImageInputStream iis = ImageIO.createImageInputStream(imageFile);
    reader.setInput(iis);
    // Read the stream metadata
    //        IIOMetadata streamMetadata = reader.getStreamMetadata();

    // Set up the writeParam
    TIFFImageWriteParam tiffWriteParam = new TIFFImageWriteParam(Locale.US);
    tiffWriteParam.setCompressionMode(ImageWriteParam.MODE_DISABLED);

    // Get tif writer and set output to file
    Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName(TIFF_FORMAT);
    ImageWriter writer = writers.next();

    // Read the stream metadata
    IIOMetadata streamMetadata = writer.getDefaultStreamMetadata(tiffWriteParam);

    int imageTotal = reader.getNumImages(true);

    for (int i = 0; i < imageTotal; i++) {
      // all if index == -1; otherwise, only index-th
      if (index == -1 || i == index) {
        //                BufferedImage bi = reader.read(i);
        //                IIOImage oimage = new IIOImage(bi, null, reader.getImageMetadata(i));
        IIOImage oimage = reader.readAll(i, reader.getDefaultReadParam());
        File tiffFile = File.createTempFile(OUTPUT_FILE_NAME, TIFF_EXT);
        ImageOutputStream ios = ImageIO.createImageOutputStream(tiffFile);
        writer.setOutput(ios);
        writer.write(streamMetadata, oimage, tiffWriteParam);
        ios.close();
        tiffFiles.add(tiffFile);
      }
    }
    writer.dispose();
    reader.dispose();

    return tiffFiles;
  }
示例#13
0
 /**
  * 1、�?过ImageIO获得ImageReader 2、�?过ImageReader获得ImageInputStream 3、指定ImageReader的source 4、获得缩略图的数�?
  * 5、若缩略图大�?,读取缩略图
  */
 @Test
 public void thumbnailTest() throws IOException {
   Iterator<ImageReader> itr = ImageIO.getImageReadersByFormatName("jpg");
   ImageReader imageReader = itr.next();
   ImageInputStream imageInputStream = ImageIO.createImageInputStream(new File(SRCIMG));
   imageReader.setInput(imageInputStream, true);
   int thumbnailNum = imageReader.getNumThumbnails(0);
   System.out.println(thumbnailNum);
   if (thumbnailNum > 0) {
     BufferedImage bufferedImage = imageReader.readThumbnail(0, 0);
     // TODO 图片其它处理
     System.out.println(bufferedImage.getWidth());
   }
 }
示例#14
0
文件: ImageUtil.java 项目: gahzl/bbs
 /*
  * 图片裁剪二分之一
  */
 public static void cutHalfImage(String src, String dest) throws IOException {
   Iterator iterator = ImageIO.getImageReadersByFormatName("jpg");
   ImageReader reader = (ImageReader) iterator.next();
   InputStream in = new FileInputStream(src);
   ImageInputStream iis = ImageIO.createImageInputStream(in);
   reader.setInput(iis, true);
   ImageReadParam param = reader.getDefaultReadParam();
   int imageIndex = 0;
   int width = reader.getWidth(imageIndex) / 2;
   int height = reader.getHeight(imageIndex) / 2;
   Rectangle rect = new Rectangle(width / 2, height / 2, width, height);
   param.setSourceRegion(rect);
   BufferedImage bi = reader.read(0, param);
   ImageIO.write(bi, "jpg", new File(dest));
 }
示例#15
0
  @Test
  public void imageReadParam2() throws IOException {
    Iterator<ImageReader> itr = ImageIO.getImageReadersByFormatName("jpg");
    ImageReader imageReader = itr.next();

    ImageInputStream imageInputStream = ImageIO.createImageInputStream(new File(SRCIMG));
    imageReader.setInput(imageInputStream, true);

    ImageReadParam imageReadParam = imageReader.getDefaultReadParam();
    imageReadParam.setSourceSubsampling(3, 3, 0, 0);

    BufferedImage bufferedImage = imageReader.read(0, imageReadParam);

    boolean b = ImageIO.write(bufferedImage, "jpg", new File(CONTEXT + "1.jpg"));
    System.out.println(b);
  }
示例#16
0
  @Test
  public void imageReadParam() throws IOException {
    Iterator<ImageReader> itr = ImageIO.getImageReadersByFormatName("jpg");
    ImageReader imageReader = itr.next();

    ImageInputStream imageInputStream = ImageIO.createImageInputStream(new File(SRCIMG));

    imageReader.setInput(imageInputStream, true);

    ImageReadParam imageReadParam = imageReader.getDefaultReadParam();
    int halfWidth = imageReader.getWidth(0) / 2;
    int halfHeight = imageReader.getHeight(0) / 2;
    Rectangle rectangle = new Rectangle(0, 0, halfWidth, halfHeight);
    imageReadParam.setSourceRegion(rectangle);

    BufferedImage bufferedImage = imageReader.read(0, imageReadParam);
    System.out.println(bufferedImage.getWidth());

    boolean result = ImageIO.write(bufferedImage, "png", new File(CONTEXT + "999.png"));
    System.out.println(result);
  }
  /**
   * Standard constructor: needs a PictureFileDataPolicy.
   *
   * @param file The files which data are to be handled by this instance.
   * @param root The root directory, to calculate the relative dir (see {@link #getRelativeDir()}.
   * @param uploadPolicy The current upload policy
   * @throws JUploadIOException Encapsulation of the IOException, if any would occurs.
   */
  public PictureFileData(File file, File root, PictureUploadPolicy uploadPolicy)
      throws JUploadIOException {
    super(file, root, uploadPolicy);
    // EGR Should be useless
    // this.uploadPolicy = (PictureUploadPolicy) super.uploadPolicy;
    this.storeBufferedImage = uploadPolicy.hasToStoreBufferedImage();

    String fileExtension = getFileExtension();

    // Is it a picture?
    Iterator<ImageReader> iter = ImageIO.getImageReadersByFormatName(fileExtension);
    if (iter.hasNext()) {
      // It's a picture: we store its original width and height, for
      // further calculation (rescaling and rotation).
      this.isPicture = true;
      try {
        FileImageInputStream fiis = new FileImageInputStream(getFile());
        ImageReader ir = iter.next();
        ir.setInput(fiis);
        this.originalHeight = ir.getHeight(0);
        this.originalWidth = ir.getWidth(0);
        ir.dispose();
        fiis.close();
      } catch (IOException e) {
        throw new JUploadIOException("PictureFileData()", e);
      }
    } else {
      this.isPicture = false;
    }
    // Let's log the test result
    uploadPolicy.displayDebug(
        "isPicture=" + this.isPicture + " (" + file.getName() + "), extension=" + fileExtension,
        75);

    // If it's a picture, we override the default mime type:
    if (this.isPicture) {
      setMimeTypeByExtension(fileExtension);
    }
  }
示例#18
0
  /**
   * 图片截取
   *
   * @param file
   * @param newName
   * @param path
   * @param x
   * @param y
   * @param width
   * @param height
   * @return author:caobo date:Oct 14, 2009 12:38:05 PM
   */
  public static File cutting(
      File file, String newName, String path, int x, int y, int width, int height) {
    ImageOutputStream out = null;
    InputStream is = null;
    ImageInputStream iis = null;
    try {
      String endName = file.getName();
      endName = endName.substring(endName.lastIndexOf(".") + 1);
      Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(endName);
      ImageReader reader = (ImageReader) readers.next();
      is = new FileInputStream(file);
      iis = ImageIO.createImageInputStream(is);
      reader.setInput(iis, true);

      ImageReadParam param = reader.getDefaultReadParam();
      Rectangle rect = new Rectangle(x, y, width, height);
      param.setSourceRegion(rect);
      BufferedImage bi = reader.read(0, param);
      File newFile = new File(path);

      if (!newFile.exists()) newFile.mkdirs();
      newFile = new File(path, newName);
      out = ImageIO.createImageOutputStream(new FileOutputStream(newFile));
      ImageIO.write(bi, endName, out);
      file = newFile;
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        iis.close();
        is.close();
        out.close();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    return file;
  }
示例#19
0
  /**
   * 1、�?过ImageIO获得ImageWriter对象 2、�?过ImageIO获得ImageOutputStream对象
   * 3、�?过给定的ImageOutputStream设定ImageWriter的输出源 4、写图片
   *
   * @throws IOException
   */
  @Test
  public void teatImageWriter() throws IOException {

    // ~:指定配置imageReader
    Iterator<ImageReader> itrReads = ImageIO.getImageReadersByFormatName("png");
    ImageReader imageReader = itrReads.next();
    ImageInputStream imageInputSteam =
        ImageIO.createImageInputStream(new File(CONTEXT + "999.png"));
    imageReader.setInput(imageInputSteam, true);
    // ~~

    BufferedImage bufferedImage = imageReader.read(0);

    // ~:指定配置imageWriter
    Iterator<ImageWriter> itr = ImageIO.getImageWritersByFormatName("jpg");
    ImageWriter imageWriter = itr.next();

    ImageOutputStream imageOutputStream =
        ImageIO.createImageOutputStream(new File(CONTEXT + "213.jpg"));
    imageWriter.setOutput(imageOutputStream);
    // ~~

    imageWriter.write(bufferedImage);
  }
示例#20
0
 private static boolean isImageIODicomReaderAvailable() {
   Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName("dicom");
   return readers != null && readers.hasNext();
 }
示例#21
0
 /**
  * Parses teh TIFF contained in the response as a {@link RenderedImage}
  *
  * @param response
  * @return
  * @throws IOException
  */
 RenderedImage readTiff(MockHttpServletResponse response) throws IOException {
   ImageReader reader = ImageIO.getImageReadersByFormatName("tiff").next();
   reader.setInput(ImageIO.createImageInputStream(getBinaryInputStream(response)));
   return reader.read(0);
 }
示例#22
0
  /**
   * 根据指定坐标和长宽裁剪图片
   *
   * @param inputFilePath 源图片
   * @param outputFilePath 产生新图片路径
   * @param x x轴的开始坐标
   * @param y y轴的开始坐标
   * @param width 所裁剪的宽度
   * @param height 所裁剪的高度
   */
  public static void cut(
      String inputFilePath, String outputFilePath, int x, int y, int width, int height) {

    FileInputStream fileInputStream = null;
    ImageInputStream imageInputStream = null;
    try {
      // 获得源文件
      File inputFile = new File(inputFilePath);
      if (!inputFile.exists()) {
        logger.fatal(new FileNotFoundException());
        return;
      }

      // 读取图片文件
      fileInputStream = new FileInputStream(inputFilePath);

      String format = FileUtil.getFileSuffix(inputFilePath);
      // System.out.println(format);
      // ImageReader声称能够解码指定格式
      Iterator<ImageReader> it = ImageIO.getImageReadersByFormatName(format);
      ImageReader reader = it.next();

      // 获取图片流
      imageInputStream = ImageIO.createImageInputStream(fileInputStream);

      // 输入源中的图像将只按顺序读取
      reader.setInput(imageInputStream, true);

      // 描述如何对流进行解码
      ImageReadParam param = reader.getDefaultReadParam();

      // 图片裁剪区域
      Rectangle rect = new Rectangle(x, y, width, height);

      // 提供一个 BufferedImage,将其用作解码像素数据的目标
      param.setSourceRegion(rect);

      // 使用所提供的 ImageReadParam 读取通过索引 imageIndex 指定的对象
      BufferedImage bi = reader.read(0, param);

      // 保存新图片
      // File tempOutFile = new File(outputFilePath);
      // if (!tempOutFile.exists()) {
      // tempOutFile.mkdirs();
      // }
      ImageIO.write(bi, format, new File(outputFilePath));
    } catch (Exception e) {
      e.printStackTrace();
      logger.fatal(e);
    } finally {
      try {
        if (fileInputStream != null) {
          fileInputStream.close();
        }
        if (imageInputStream != null) {
          imageInputStream.close();
        }
      } catch (IOException e) {
        e.printStackTrace();
        logger.fatal(e);
      }
    }
  }
示例#23
0
  /**
   * Initializes these instance variables from the image metadata:
   *
   * <pre>
   * compression
   * width
   * height
   * samplesPerPixel
   * numBands
   * colorMap
   * photometricInterpretation
   * sampleFormat
   * bitsPerSample
   * extraSamples
   * tileOrStripWidth
   * tileOrStripHeight
   * </pre>
   */
  private void initializeFromMetadata() {
    TIFFField f;

    // Compression
    f = imageMetadata.getTIFFField(BaselineTIFFTagSet.TAG_COMPRESSION);
    if (f == null) {
      processWarningOccurred("Compression field is missing; assuming no compression");
      compression = BaselineTIFFTagSet.COMPRESSION_NONE;
    } else {
      compression = f.getAsInt(0);
    }

    // Whether key dimensional information is absent.
    boolean isMissingDimension = false;

    // ImageWidth -> width
    f = imageMetadata.getTIFFField(BaselineTIFFTagSet.TAG_IMAGE_WIDTH);
    if (f != null) {
      this.width = f.getAsInt(0);
    } else {
      processWarningOccurred("ImageWidth field is missing.");
      isMissingDimension = true;
    }

    // ImageLength -> height
    f = imageMetadata.getTIFFField(BaselineTIFFTagSet.TAG_IMAGE_LENGTH);
    if (f != null) {
      this.height = f.getAsInt(0);
    } else {
      processWarningOccurred("ImageLength field is missing.");
      isMissingDimension = true;
    }

    // SamplesPerPixel
    f = imageMetadata.getTIFFField(BaselineTIFFTagSet.TAG_SAMPLES_PER_PIXEL);
    if (f != null) {
      samplesPerPixel = f.getAsInt(0);
    } else {
      samplesPerPixel = 1;
      isMissingDimension = true;
    }

    // If any dimension is missing and there is a JPEG stream available
    // get the information from it.
    int defaultBitDepth = 1;
    if (isMissingDimension
        && (f = imageMetadata.getTIFFField(BaselineTIFFTagSet.TAG_JPEG_INTERCHANGE_FORMAT))
            != null) {
      Iterator iter = ImageIO.getImageReadersByFormatName("JPEG");
      if (iter != null && iter.hasNext()) {
        ImageReader jreader = (ImageReader) iter.next();
        try {
          stream.mark();
          stream.seek(f.getAsLong(0));
          jreader.setInput(stream);
          if (imageMetadata.getTIFFField(BaselineTIFFTagSet.TAG_IMAGE_WIDTH) == null) {
            this.width = jreader.getWidth(0);
          }
          if (imageMetadata.getTIFFField(BaselineTIFFTagSet.TAG_IMAGE_LENGTH) == null) {
            this.height = jreader.getHeight(0);
          }
          ImageTypeSpecifier imageType = jreader.getRawImageType(0);
          if (imageMetadata.getTIFFField(BaselineTIFFTagSet.TAG_SAMPLES_PER_PIXEL) == null) {
            this.samplesPerPixel = imageType.getSampleModel().getNumBands();
          }
          stream.reset();
          defaultBitDepth = imageType.getColorModel().getComponentSize(0);
        } catch (IOException e) {
          // Ignore it and proceed: an error will occur later.
        }
        jreader.dispose();
      }
    }

    if (samplesPerPixel < 1) {
      processWarningOccurred("Samples per pixel < 1!");
    }

    // SamplesPerPixel -> numBands
    numBands = samplesPerPixel;

    // ColorMap
    this.colorMap = null;
    f = imageMetadata.getTIFFField(BaselineTIFFTagSet.TAG_COLOR_MAP);
    if (f != null) {
      // Grab color map
      colorMap = f.getAsChars();
    }

    // PhotometricInterpretation
    f = imageMetadata.getTIFFField(BaselineTIFFTagSet.TAG_PHOTOMETRIC_INTERPRETATION);
    if (f == null) {
      if (compression == BaselineTIFFTagSet.COMPRESSION_CCITT_RLE
          || compression == BaselineTIFFTagSet.COMPRESSION_CCITT_T_4
          || compression == BaselineTIFFTagSet.COMPRESSION_CCITT_T_6) {
        processWarningOccurred(
            "PhotometricInterpretation field is missing; " + "assuming WhiteIsZero");
        photometricInterpretation = BaselineTIFFTagSet.PHOTOMETRIC_INTERPRETATION_WHITE_IS_ZERO;
      } else if (this.colorMap != null) {
        photometricInterpretation = BaselineTIFFTagSet.PHOTOMETRIC_INTERPRETATION_PALETTE_COLOR;
      } else if (samplesPerPixel == 3 || samplesPerPixel == 4) {
        photometricInterpretation = BaselineTIFFTagSet.PHOTOMETRIC_INTERPRETATION_RGB;
      } else {
        processWarningOccurred(
            "PhotometricInterpretation field is missing; " + "assuming BlackIsZero");
        photometricInterpretation = BaselineTIFFTagSet.PHOTOMETRIC_INTERPRETATION_BLACK_IS_ZERO;
      }
    } else {
      photometricInterpretation = f.getAsInt(0);
    }

    // SampleFormat
    boolean replicateFirst = false;
    int first = -1;

    f = imageMetadata.getTIFFField(BaselineTIFFTagSet.TAG_SAMPLE_FORMAT);
    sampleFormat = new int[samplesPerPixel];
    replicateFirst = false;
    if (f == null) {
      replicateFirst = true;
      first = BaselineTIFFTagSet.SAMPLE_FORMAT_UNDEFINED;
    } else if (f.getCount() != samplesPerPixel) {
      replicateFirst = true;
      first = f.getAsInt(0);
    }

    for (int i = 0; i < samplesPerPixel; i++) {
      sampleFormat[i] = replicateFirst ? first : f.getAsInt(i);
      if (sampleFormat[i] != BaselineTIFFTagSet.SAMPLE_FORMAT_UNSIGNED_INTEGER
          && sampleFormat[i] != BaselineTIFFTagSet.SAMPLE_FORMAT_SIGNED_INTEGER
          && sampleFormat[i] != BaselineTIFFTagSet.SAMPLE_FORMAT_FLOATING_POINT
          && sampleFormat[i] != BaselineTIFFTagSet.SAMPLE_FORMAT_UNDEFINED) {
        processWarningOccurred("Illegal value for SAMPLE_FORMAT, assuming SAMPLE_FORMAT_UNDEFINED");
        sampleFormat[i] = BaselineTIFFTagSet.SAMPLE_FORMAT_UNDEFINED;
      }
    }

    // BitsPerSample
    f = imageMetadata.getTIFFField(BaselineTIFFTagSet.TAG_BITS_PER_SAMPLE);
    this.bitsPerSample = new int[samplesPerPixel];
    replicateFirst = false;
    if (f == null) {
      replicateFirst = true;
      first = defaultBitDepth;
    } else if (f.getCount() != samplesPerPixel) {
      replicateFirst = true;
      first = f.getAsInt(0);
    }

    for (int i = 0; i < samplesPerPixel; i++) {
      // Replicate initial value if not enough values provided
      bitsPerSample[i] = replicateFirst ? first : f.getAsInt(i);

      if (DEBUG) {
        System.out.println("bitsPerSample[" + i + "] = " + bitsPerSample[i]);
      }
    }

    // ExtraSamples
    this.extraSamples = null;
    f = imageMetadata.getTIFFField(BaselineTIFFTagSet.TAG_EXTRA_SAMPLES);
    if (f != null) {
      extraSamples = f.getAsInts();
    }

    //         System.out.println("colorMap = " + colorMap);
    //         if (colorMap != null) {
    //             for (int i = 0; i < colorMap.length; i++) {
    //              System.out.println("colorMap[" + i + "] = " + (int)(colorMap[i]));
    //             }
    //         }

  }