/**
   * Gets pixel data of an <code>IIOImage</code> object.
   *
   * @param image an <code>IIOImage</code> object
   * @return a byte buffer of pixel data
   * @throws Exception
   */
  public static ByteBuffer getImageByteBuffer(IIOImage image) throws IOException {
    // 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();

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

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

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    ImageOutputStream ios = ImageIO.createImageOutputStream(outputStream);
    writer.setOutput(ios);
    writer.write(
        streamMetadata, new IIOImage(image.getRenderedImage(), null, null), tiffWriteParam);
    //        writer.write(image.getRenderedImage());
    writer.dispose();
    //        ImageIO.write(image.getRenderedImage(), "tiff", ios); // this can be used in lieu of
    // writer
    ios.seek(0);
    BufferedImage bi = ImageIO.read(ios);
    return convertImageData(bi);
  }
Example #2
0
  /**
   * Gets pixel data of an <code>IIOImage</code> object.
   *
   * @param oimage an <code>IIOImage</code> object
   * @return a byte buffer of pixel data
   * @throws Exception
   */
  public static ByteBuffer getImageByteBuffer(BufferedImage oimage) throws IOException {
    // Get tif writer and set output to file
    ImageWriter writer = new TIFFImageWriterSpi().createWriterInstance();

    // Set up the writeParam
    // We are using the old JAI ImageIO plugin, because for some reason, OCR don't work with
    // TwelveMonkeys' plugin
    ImageWriteParam tiffWriteParam = new TIFFImageWriteParam(Locale.US);
    tiffWriteParam.setCompressionMode(ImageWriteParam.MODE_DISABLED);

    // Get the stream metadata
    IIOMetadata streamMetadata = writer.getDefaultStreamMetadata(tiffWriteParam);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    ImageOutputStream ios = ImageIO.createImageOutputStream(outputStream);
    writer.setOutput(ios);
    writer.write(streamMetadata, new IIOImage(oimage, null, null), tiffWriteParam);
    writer.dispose();

    // Read the writed image
    ios.seek(0);
    ImageReader reader = new TIFFImageReaderSpi().createReaderInstance();
    ImageReadParam param = reader.getDefaultReadParam();
    reader.setInput(ios, true, true);
    BufferedImage bi;
    try {
      bi = reader.read(0, param);
    } finally {
      reader.dispose();
      ios.close();
    }

    return convertImageData(bi);
  }
  /**
   * 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;
  }
  public static List<File> createTiffFiles(List<IIOImage> imageList, int index, int dpiX, int dpiY)
      throws IOException {
    List<File> tiffFiles = new ArrayList<File>();

    // 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();

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

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

    // all if index == -1; otherwise, only index-th
    for (IIOImage oimage : (index == -1 ? imageList : imageList.subList(index, index + 1))) {
      if (dpiX != 0 && dpiY != 0) {
        // Get the default image metadata.
        ImageTypeSpecifier imageType =
            ImageTypeSpecifier.createFromRenderedImage(oimage.getRenderedImage());
        IIOMetadata imageMetadata = writer.getDefaultImageMetadata(imageType, null);
        imageMetadata = setDPIViaAPI(imageMetadata, dpiX, dpiY);
        oimage.setMetadata(imageMetadata);
      }

      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();

    return tiffFiles;
  }
  /**
   * Merges multiple images into one TIFF image.
   *
   * @param inputImages an array of image files
   * @param outputTiff the output TIFF file
   * @throws Exception
   */
  public static void mergeTiff(File[] inputImages, File outputTiff) throws IOException {
    List<IIOImage> imageList = new ArrayList<IIOImage>();

    for (int i = 0; i < inputImages.length; i++) {
      imageList.addAll(getIIOImageList(inputImages[i]));
    }

    if (imageList.isEmpty()) {
      // if no image
      return;
    }

    Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName(TIFF_FORMAT);
    ImageWriter writer = writers.next();

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

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

    ImageOutputStream ios = ImageIO.createImageOutputStream(outputTiff);
    writer.setOutput(ios);

    IIOImage firstIioImage = imageList.remove(0);
    writer.write(streamMetadata, firstIioImage, tiffWriteParam);

    int i = 1;
    for (IIOImage iioImage : imageList) {
      writer.writeInsert(i++, iioImage, tiffWriteParam);
    }
    ios.close();

    writer.dispose();
  }
Example #6
0
  /**
   * Encodes a BufferedImage using JAI in <code>format</code> format and sends it to <code>outStream
   * </code>.
   *
   * @param format the MIME type of the output image in which to encode <code>image</code> through
   *     JAI
   * @param image the actual image to be encoded in <code>format</code> format.
   * @param outStream the encoded image destination.
   * @throws IOException if the image writing to <code>outStream</code> fails.
   * @throws IllegalArgumentException if <code>format</code> is not a supported output format for
   *     the installed JAI library.
   */
  public static void encode(String format, BufferedImage image, OutputStream outStream)
      throws IOException {
    if (format.equalsIgnoreCase("jpeg")) {
      format = "image/jpeg";
    }

    Iterator it = ImageIO.getImageWritersByMIMEType(format);

    if (!it.hasNext()) {
      throw new IllegalArgumentException("Format not supported: " + format);
    }

    ImageWriter writer = (ImageWriter) it.next();
    ImageOutputStream ioutstream = null;

    IIOMetadata meta = writer.getDefaultStreamMetadata(writer.getDefaultWriteParam());
    ImageWriteParam param = writer.getDefaultWriteParam();

    // DJB: jpeg does not support ARGB (alpha) colour
    //      this converts the image from ARGB to RGB
    // TODO: make this more abstract - it should be smarter for more image
    //       writer types (Ie. ask the writer what it supports)
    //       Alternately, make a jpeg writer and png writer, as these are
    //       mostly what we get from jai!
    if (format.equalsIgnoreCase("image/jpeg")) {
      param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
      param.setCompressionQuality(
          0.9f); // DJB: only do this for jpegs - png freaks when you do this!

      meta = writer.getDefaultStreamMetadata(param);

      //           WritableRaster raster = image.getRaster();
      //           WritableRaster newRaster = raster.createWritableChild(0, 0, image.getWidth(),
      // image.getHeight(), 0, 0, new int[] {0, 1, 2});
      //             create a ColorModel that represents the one of the ARGB except the alpha
      // channel:
      //            DirectColorModel cm = (DirectColorModel)image.getColorModel();
      //           DirectColorModel newCM = new DirectColorModel(cm.getPixelSize(), cm.getRedMask(),
      // cm.getGreenMask(), cm.getBlueMask());
      //             now create the new buffer that is used ot write the image:
      // BufferedImage rgbBuffer = new BufferedImage(newCM, newRaster, false, null);
      BufferedImage curImage =
          new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_3BYTE_BGR);
      Graphics2D g = (Graphics2D) curImage.createGraphics();
      g.drawImage(image, 0, 0, null);

      image = curImage;

      ioutstream = ImageIOExt.createImageOutputStream(image, outStream);
      writer.setOutput(ioutstream);
      writer.write(image);
      ioutstream.close();
      writer.dispose();

      return;
    }

    ioutstream = ImageIOExt.createImageOutputStream(image, outStream);
    writer.setOutput(ioutstream);
    writer.write(meta, new IIOImage(image, null, meta), param);
    ioutstream.close();
    writer.dispose();
  }