@Test
  public void lossyWrite() throws Exception {
    File f = File.createTempFile("test-jpeg2000-lossy", ".jp2");
    f.deleteOnExit();
    Iterator<ImageWriter> writers = ImageIO.getImageWritersBySuffix("jp2");
    assertTrue(writers.hasNext());
    ImageWriter writer = writers.next();
    J2KImageWriteParam writeParams = (J2KImageWriteParam) writer.getDefaultWriteParam();
    writeParams.setLossless(false);
    writeParams.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    writeParams.setCompressionType("JPEG2000");
    //        writeParams.setFilter(J2KImageWriteParam.FILTER_97);

    writeParams.setCompressionQuality(0.0f);
    writeParams.setEncodingRate(0.5f);
    ImageOutputStream ios = ImageIO.createImageOutputStream(f);
    writer.setOutput(ios);
    writer.write(null, new IIOImage(image, null, null), writeParams);
    writer.dispose();
    ios.close();
    assertTrue("Expected file size < 1MB", f.length() < 128 * 1024);
    // System.out.println(f.length());
    BufferedImage read = ImageIO.read(f);
    assertEquals(SIZE, read.getWidth());
  }
Ejemplo n.º 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;
  }
Ejemplo n.º 3
0
  /**
   * 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);
  }
  @Override
  public void writeImage(RenderedImage image, String mimeType, float quality, OutputStream out)
      throws IOException {
    if ("image/jpeg".equals(mimeType)) {
      // Find a JPEG writer.
      ImageWriter writer = null;
      Iterator<ImageWriter> iter = ImageIO.getImageWritersByMIMEType(mimeType);
      if (iter.hasNext()) {
        writer = iter.next();
      }
      JPEGImageWriteParam iwp = new JPEGImageWriteParam(null);
      iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
      iwp.setCompressionQuality(quality);

      // Prepare output file.
      ImageOutputStream ios = ImageIO.createImageOutputStream(out);
      writer.setOutput(ios);

      // Write the image.
      writer.write(null, new IIOImage(image, null, null), iwp);

      // Cleanup.
      ios.flush();
      writer.dispose();
      ios.close();
    } else {
      ImageIO.write(image, "png", out);
    }
  }
Ejemplo n.º 5
0
 /**
  * store BufferedImage to file
  *
  * @param image BufferedImage
  * @param outputFile output image file
  * @param quality quality of output image
  * @return true success, else fail
  */
 public static boolean storeImage(BufferedImage image, File outputFile, float quality) {
   try {
     // reconstruct folder structure for image file output
     if (outputFile.getParentFile() != null && !outputFile.getParentFile().exists()) {
       outputFile.getParentFile().mkdirs();
     }
     if (outputFile.exists()) {
       outputFile.delete();
     }
     // get image file suffix
     String extName = "gif";
     // get registry ImageWriter for specified image suffix
     Iterator writers = ImageIO.getImageWritersByFormatName(extName);
     ImageWriter imageWriter = (ImageWriter) writers.next();
     // set image output params
     ImageWriteParam params = new JPEGImageWriteParam(null);
     params.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
     params.setCompressionQuality(quality);
     params.setProgressiveMode(javax.imageio.ImageWriteParam.MODE_DISABLED);
     params.setDestinationType(
         new ImageTypeSpecifier(
             IndexColorModel.getRGBdefault(),
             IndexColorModel.getRGBdefault().createCompatibleSampleModel(16, 16)));
     // writer image to file
     ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(outputFile);
     imageWriter.setOutput(imageOutputStream);
     imageWriter.write(null, new IIOImage(image, null, null), params);
     imageOutputStream.close();
     imageWriter.dispose();
     return true;
   } catch (Exception e) {
     e.printStackTrace();
   }
   return false;
 }
  /**
   * Salva BufferedImage no arquivo informado na prop<br>
   *
   * <p><b>Exemplo:><br>
   * <code>salvarImagem(img)</code>
   *
   * @param img BufferedImage a ser salva
   * @author roberto
   */
  private void salvarImagem(BufferedImage img) {

    ImageWriter writer = null;
    Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName(formatoImagem);

    if (iter.hasNext()) {

      writer = (ImageWriter) iter.next();
    }

    ImageOutputStream ios;
    try {

      ios = ImageIO.createImageOutputStream(new File(prop.getProp("dirImg")));
      writer.setOutput(ios);

      ImageWriteParam param = new JPEGImageWriteParam(java.util.Locale.getDefault());
      param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
      param.setCompressionQuality(1);

      writer.write(null, new IIOImage(img, null, null), param);

    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 7
0
  /**
   * Compress and save an image to the disk. Currently this method only supports JPEG images.
   *
   * @param image The image to save
   * @param toFileName The filename to use
   * @param type The image type. Use <code>ImageUtils.IMAGE_JPEG</code> to save as JPEG images, or
   *     <code>ImageUtils.IMAGE_PNG</code> to save as PNG.
   */
  public static void saveCompressedImage(BufferedImage image, String toFileName, int type) {
    try {
      if (type == IMAGE_PNG) {
        throw new UnsupportedOperationException("PNG compression not implemented");
      }

      Iterator iter = ImageIO.getImageWritersByFormatName("jpg");
      ImageWriter writer;
      writer = (ImageWriter) iter.next();

      ImageOutputStream ios = ImageIO.createImageOutputStream(new File(toFileName));
      writer.setOutput(ios);

      ImageWriteParam iwparam = new JPEGImageWriteParam(Locale.getDefault());

      iwparam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
      iwparam.setCompressionQuality(0.7F);

      writer.write(null, new IIOImage(image, null, null), iwparam);

      ios.flush();
      writer.dispose();
      ios.close();
    } catch (IOException e) {
      throw new ForumException(e);
    }
  }
Ejemplo n.º 8
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);
  }
Ejemplo n.º 9
0
  @SuppressWarnings("unchecked")
  public void write() throws IOException {
    Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName(EXTENSION);
    ImageWriter writer = writers.next();

    ImageWriteParam param = writer.getDefaultWriteParam();

    IIOMetadata metadata = writer.getDefaultImageMetadata(new ImageTypeSpecifier(image), param);

    if (metadata instanceof com.sun.imageio.plugins.png.PNGMetadata) {
      com.sun.imageio.plugins.png.PNGMetadata pngMetadata =
          (com.sun.imageio.plugins.png.PNGMetadata) metadata;

      ArrayList keyword = pngMetadata.tEXt_keyword;
      ArrayList text = pngMetadata.tEXt_text;

      for (String key : this.metadata.keySet()) {
        if (keyword == null) keyword = new ArrayList();
        if (text == null) text = new ArrayList();

        keyword.add(key);
        text.add(this.metadata.get(key));
      }

      pngMetadata.tEXt_keyword = keyword;
      pngMetadata.tEXt_text = text;
    }

    IIOImage iioi = new IIOImage(image, null, metadata);

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

    writer.write(iioi);
  }
Ejemplo n.º 10
0
  /**
   * Test Writing capabilities.
   *
   * @throws FileNotFoundException
   * @throws IOException
   */
  @Test
  public void write() throws IOException, FileNotFoundException {
    if (!isGDALAvailable) {
      return;
    }
    final File outputFile = TestData.temp(this, "writetest.tif", false);
    outputFile.deleteOnExit();
    final File inputFile = TestData.file(this, "utmByte.tif");

    ImageReadParam rparam = new ImageReadParam();
    rparam.setSourceRegion(new Rectangle(1, 1, 300, 500));
    rparam.setSourceSubsampling(1, 2, 0, 0);
    ImageReader reader = new GeoTiffImageReaderSpi().createReaderInstance();
    reader.setInput(inputFile);
    final IIOMetadata metadata = reader.getImageMetadata(0);

    final ParameterBlockJAI pbjImageRead = new ParameterBlockJAI("ImageRead");
    pbjImageRead.setParameter("Input", inputFile);
    pbjImageRead.setParameter("reader", reader);
    pbjImageRead.setParameter("readParam", rparam);

    final ImageLayout l = new ImageLayout();
    l.setTileGridXOffset(0).setTileGridYOffset(0).setTileHeight(256).setTileWidth(256);

    RenderedOp image =
        JAI.create("ImageRead", pbjImageRead, new RenderingHints(JAI.KEY_IMAGE_LAYOUT, l));

    if (TestData.isInteractiveTest()) Viewer.visualizeAllInformation(image, "geotiff");

    // ////////////////////////////////////////////////////////////////
    // preparing to write
    // ////////////////////////////////////////////////////////////////
    final ParameterBlockJAI pbjImageWrite = new ParameterBlockJAI("ImageWrite");
    ImageWriter writer = new GeoTiffImageWriterSpi().createWriterInstance();
    pbjImageWrite.setParameter("Output", outputFile);
    pbjImageWrite.setParameter("writer", writer);
    pbjImageWrite.setParameter("ImageMetadata", metadata);
    pbjImageWrite.setParameter("Transcode", false);
    ImageWriteParam param = new ImageWriteParam(Locale.getDefault());
    param.setSourceRegion(new Rectangle(10, 10, 100, 100));
    param.setSourceSubsampling(2, 1, 0, 0);
    pbjImageWrite.setParameter("writeParam", param);

    pbjImageWrite.addSource(image);
    final RenderedOp op = JAI.create("ImageWrite", pbjImageWrite);
    final ImageWriter writer2 =
        (ImageWriter) op.getProperty(ImageWriteDescriptor.PROPERTY_NAME_IMAGE_WRITER);
    writer2.dispose();

    // ////////////////////////////////////////////////////////////////
    // preparing to read again
    // ////////////////////////////////////////////////////////////////
    final ParameterBlockJAI pbjImageReRead = new ParameterBlockJAI("ImageRead");
    pbjImageReRead.setParameter("Input", outputFile);
    pbjImageReRead.setParameter("Reader", new GeoTiffImageReaderSpi().createReaderInstance());
    final RenderedOp image2 = JAI.create("ImageRead", pbjImageReRead);
    if (TestData.isInteractiveTest()) Viewer.visualizeAllInformation(image2, "geotif2");
    else Assert.assertNotNull(image2.getTiles());
  }
Ejemplo n.º 11
0
 /**
  * Creates an image file of the specified format.
  *
  * @param file The file where to write the image.
  * @param format One of the follow types: jpeg, png.
  * @throws Exception Thrown if an error occurred while encoding the image.
  */
 public void createImageFile(File file, String format) throws Exception {
   Iterator writers = ImageIO.getImageWritersByFormatName(format);
   ImageWriter writer = (ImageWriter) writers.next();
   ImageOutputStream ios = ImageIO.createImageOutputStream(file);
   writer.setOutput(ios);
   writer.write(new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB));
   ios.close();
 }
Ejemplo n.º 12
0
  /**
   * Test Read on a Paletted Image
   *
   * @throws FileNotFoundException
   * @throws IOException
   */
  @Test
  public void palette() throws FileNotFoundException, IOException {
    if (!isGDALAvailable) {
      return;
    }
    final File outputFile = TestData.temp(this, "writetest.tif", false);
    outputFile.deleteOnExit();
    final File inputFile = TestData.file(this, "paletted.tif");

    ImageReader reader = new GeoTiffImageReaderSpi().createReaderInstance();
    reader.setInput(inputFile);
    final IIOMetadata metadata = reader.getImageMetadata(0);

    final ParameterBlockJAI pbjImageRead = new ParameterBlockJAI("ImageRead");
    pbjImageRead.setParameter("Input", inputFile);
    pbjImageRead.setParameter("reader", reader);

    final ImageLayout l = new ImageLayout();
    l.setTileGridXOffset(0).setTileGridYOffset(0).setTileHeight(256).setTileWidth(256);

    RenderedOp image =
        JAI.create("ImageRead", pbjImageRead, new RenderingHints(JAI.KEY_IMAGE_LAYOUT, l));

    if (TestData.isInteractiveTest()) Viewer.visualizeAllInformation(image, "Paletted image read");

    // ////////////////////////////////////////////////////////////////
    // preparing to write
    // ////////////////////////////////////////////////////////////////
    final ParameterBlockJAI pbjImageWrite = new ParameterBlockJAI("ImageWrite");
    ImageWriter writer = new GeoTiffImageWriterSpi().createWriterInstance();
    pbjImageWrite.setParameter("Output", outputFile);
    pbjImageWrite.setParameter("writer", writer);
    pbjImageWrite.setParameter("ImageMetadata", metadata);
    pbjImageWrite.setParameter("Transcode", false);
    pbjImageWrite.addSource(image);
    final RenderedOp op = JAI.create("ImageWrite", pbjImageWrite);
    final ImageWriter writer2 =
        (ImageWriter) op.getProperty(ImageWriteDescriptor.PROPERTY_NAME_IMAGE_WRITER);
    writer2.dispose();

    // ////////////////////////////////////////////////////////////////
    // preparing to read again
    // ////////////////////////////////////////////////////////////////
    final ParameterBlockJAI pbjImageReRead = new ParameterBlockJAI("ImageRead");
    pbjImageReRead.setParameter("Input", outputFile);
    pbjImageReRead.setParameter("Reader", new GeoTiffImageReaderSpi().createReaderInstance());
    final RenderedOp image2 = JAI.create("ImageRead", pbjImageReRead);
    if (TestData.isInteractiveTest())
      Viewer.visualizeAllInformation(image2, "Paletted image read back after writing");
    else Assert.assertNotNull(image2.getTiles());
    ImageIOUtilities.disposeImage(image2);
    ImageIOUtilities.disposeImage(image);
  }
 private static void write(File f, boolean raw, BufferedImage image) throws IOException {
   Iterator<ImageWriter> writers = ImageIO.getImageWritersBySuffix("ppm");
   assertTrue(writers.hasNext());
   ImageWriter writer = writers.next();
   PNMImageWriteParam params = (PNMImageWriteParam) writer.getDefaultWriteParam();
   params.setRaw(raw);
   ImageOutputStream ios = ImageIO.createImageOutputStream(f);
   writer.setOutput(ios);
   writer.write(null, new IIOImage(image, null, null), params);
   writer.dispose();
   ios.close();
 }
Ejemplo n.º 14
0
  /**
   * 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;
  }
  private static byte[] convertChartToByteArray(
      Chart chartDetails, JFreeChart chart, int width, int height)
      throws IOException, IIOInvalidTreeException {
    BufferedImage buffImg =
        chart.createBufferedImage(
            width, height, BufferedImage.BITMASK | BufferedImage.SCALE_SMOOTH, null);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageWriter writer = ImageIO.getImageWritersByFormatName("png").next();

    ImageWriteParam writeParam = writer.getDefaultWriteParam();
    ImageTypeSpecifier typeSpecifier =
        ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_INT_RGB);
    IIOMetadata metadata = writer.getDefaultImageMetadata(typeSpecifier, writeParam);

    if (chartDetails != null) {
      if (chartDetails.getId() == null) {
        chartDetails.setId("%ID%");
      }
      IIOMetadataNode textEntry = new IIOMetadataNode("tEXtEntry");
      textEntry.setAttribute("keyword", "chart-google-data");
      ByteArrayOutputStream bout = new ByteArrayOutputStream();
      ObjectOutputStream objectOutputStream = new ObjectOutputStream(bout);
      objectOutputStream.writeObject(chartDetails);
      objectOutputStream.flush();
      textEntry.setAttribute(
          "value",
          (String)
              ChartRendererFactory.getRendererForOutput(ChartRendererGoogleTools.TYPE)
                  .renderChart(chartDetails));

      IIOMetadataNode text = new IIOMetadataNode("tEXt");
      text.appendChild(textEntry);

      IIOMetadataNode root = new IIOMetadataNode("javax_imageio_png_1.0");
      root.appendChild(text);

      metadata.mergeTree("javax_imageio_png_1.0", root);
    }
    // setDPI(metadata);

    final ImageOutputStream stream = ImageIO.createImageOutputStream(baos);
    try {
      writer.setOutput(stream);
      writer.write(metadata, new IIOImage(buffImg, null, metadata), writeParam);
    } finally {
      stream.close();
    }

    byte[] bytes = baos.toByteArray(); // ChartUtilities.encodeAsPNG(buffImg, true, 9);
    return bytes;
  }
 /**
  * Save an image
  *
  * @param fileName the name of the file
  * @param img the img
  * @throws FileNotFoundException
  * @throws IOException
  */
 private static void saveImage(String fileName, BufferedImage img)
     throws FileNotFoundException, IOException {
   Iterator iter = ImageIO.getImageWritersByFormatName("jpeg");
   ImageWriter writer = (ImageWriter) iter.next();
   ImageWriteParam iwp = writer.getDefaultWriteParam();
   iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
   iwp.setCompressionQuality(1);
   File outputfile = new File(fileName);
   FileImageOutputStream output = new FileImageOutputStream(outputfile);
   writer.setOutput(output);
   IIOImage outimage = new IIOImage(img, null, null);
   writer.write(null, outimage, iwp);
   writer.dispose();
 }
Ejemplo n.º 17
0
 public static boolean writeImageMetadata(IIOMetadata imageMetadata, File target)
     throws IOException {
   Iterator writers =
       ImageIO.getImageWritersBySuffix(StringHelper.getFileExtension(target.getName()));
   if (!writers.hasNext()) {
     return false;
   } else {
     ImageWriter writer = (ImageWriter) writers.next();
     writer.setOutput(new FileImageOutputStream(target));
     BufferedImage image = ImageIO.read(target);
     writer.write(null, new IIOImage(image, null, imageMetadata), null);
     return true;
   }
 }
Ejemplo n.º 18
0
  private void jButton3ActionPerformed(
      final ActionEvent evt) { // GEN-FIRST:event_jButton3ActionPerformed

    try {
      BufferedImage image = (BufferedImage) guiMap2D.getCanvas().getSnapShot();
      Object output0 = new File("temp0.png");
      Object output1 = new File("temp1.png");

      final Iterator<ImageWriter> writers = ImageIO.getImageWritersByMIMEType("image/png");
      while (writers.hasNext()) {
        final ImageWriter writer = writers.next();
        final ImageWriterSpi spi = writer.getOriginatingProvider();
        if (spi.canEncodeImage(image)) {
          ImageOutputStream stream = null;
          if (!isValidType(spi.getOutputTypes(), output0)) {
            stream = ImageIO.createImageOutputStream(output0);
            output0 = stream;
            stream = ImageIO.createImageOutputStream(output1);
            output1 = stream;
          }

          ImageWriteParam iwp = writer.getDefaultWriteParam();
          iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
          iwp.setCompressionQuality(0);
          IIOImage iimage = new IIOImage(image, null, null);
          writer.setOutput(output0);
          writer.write(null, iimage, iwp);
          writer.dispose();

          iwp = writer.getDefaultWriteParam();
          iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
          iwp.setCompressionQuality(1);
          iimage = new IIOImage(image, null, null);
          writer.setOutput(output1);
          writer.write(null, iimage, iwp);
          writer.dispose();

          if (output0 != null) {
            ((ImageOutputStream) output0).close();
            ((ImageOutputStream) output1).close();
          }

          return;
        }
      }
    } catch (Exception rx) {
      rx.printStackTrace();
    }
  } // GEN-LAST:event_jButton3ActionPerformed
Ejemplo n.º 19
0
 public static void writeJPEG(BufferedImage input, String name) throws IOException {
   Iterator iter = ImageIO.getImageWritersByFormatName("JPG");
   if (iter.hasNext()) {
     ImageWriter writer = (ImageWriter) iter.next();
     ImageWriteParam iwp = writer.getDefaultWriteParam();
     iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
     iwp.setCompressionQuality(0.95f);
     File outFile = new File(name);
     FileImageOutputStream output = new FileImageOutputStream(outFile);
     writer.setOutput(output);
     IIOImage image = new IIOImage(input, null, null);
     writer.write(null, image, iwp);
     output.close();
   }
 }
Ejemplo n.º 20
0
 /**
  * Returns <code>true</code> if the <code>ImageWriter</code> object passed in is an instance of
  * the <code>ImageWriter</code> associated with this service provider.
  *
  * @param writer an <code>ImageWriter</code> instance.
  * @return <code>true</code> if <code>writer</code> is recognized
  * @exception IllegalArgumentException if <code>writer</code> is <code>null</code>.
  */
 public boolean isOwnWriter(ImageWriter writer) {
   if (writer == null) {
     throw new IllegalArgumentException("writer == null!");
   }
   String name = writer.getClass().getName();
   return name.equals(pluginClassName);
 }
Ejemplo n.º 21
0
  /**
   * reduce the quality of an image.
   *
   * @param image the original image
   * @param quality quality
   * @param output data stream of the quality reduced image
   */
  public void reduceImageQuality(BufferedImage image, float quality, OutputStream output) {
    ImageWriter encoder = (ImageWriter) ImageIO.getImageWritersByFormatName("JPEG").next();
    JPEGImageWriteParam param = new JPEGImageWriteParam(null);

    quality = Math.max(0, Math.min(quality, 100));
    param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    param.setCompressionQuality(quality / 100.0f);

    encoder.setOutput(output);

    try {
      encoder.write((IIOMetadata) null, new IIOImage(image, null, null), param);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
Ejemplo n.º 22
0
  private static byte[] toPng(BufferedImage bufferedImage) throws IOException {
    ImageWriter imageWriter = getPngImageWriter();
    try {
      // set quality
      ImageWriteParam imageWriteParam = imageWriter.getDefaultWriteParam();
      ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
      ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(byteArrayOutputStream);

      imageWriter.setOutput(imageOutputStream);
      IIOImage iioImage = new IIOImage(bufferedImage, null, null);
      imageWriter.write(null, iioImage, imageWriteParam);

      return (byteArrayOutputStream.toByteArray());
    } finally {
      imageWriter.dispose();
    }
  }
 /** Cleans this {@link GrassBinaryImageWriter}. */
 public void dispose() {
   try {
     rasterWriter.close();
   } catch (Exception e) {
     e.printStackTrace();
   }
   super.dispose();
 }
Ejemplo n.º 24
0
 public void compressJpegFile(
     File infile, File outfile, float compressionQuality, int widthCanvas, int heightCanvas)
     throws IOException {
   // Retrieve jpg image to be compressed
   BufferedImage rendImage = ImageIO.read(infile);
   widthFile = rendImage.getWidth();
   heightFile = rendImage.getHeight();
   double aspectRatioCanvas = widthCanvas / heightCanvas;
   double aspectRatioFile = widthFile / heightFile;
   widthFile = widthCanvas;
   heightFile = widthCanvas / aspectRatioFile;
   if (heightFile > heightCanvas) {
     heightFile = heightCanvas;
     widthFile = heightCanvas * aspectRatioFile;
   }
   this.width = (int) widthFile;
   this.height = (int) heightFile;
   ImageTypeSpecifier its = ImageTypeSpecifier.createFromRenderedImage(rendImage);
   BufferedImage outImage = its.createBufferedImage(width, height);
   Graphics2D graphics2D = outImage.createGraphics();
   graphics2D.setRenderingHint(
       RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
   //         graphics2D.drawRenderedImage(rendImage, new AffineTransform());
   graphics2D.drawImage(rendImage, 0, 0, width, height, null);
   // Find a jpeg writer
   ImageWriter writer = null;
   Iterator iter = ImageIO.getImageWritersByFormatName("jpg");
   if (iter.hasNext()) {
     writer = (ImageWriter) iter.next();
   }
   // Prepare output file
   ImageOutputStream ios = ImageIO.createImageOutputStream(outfile);
   writer.setOutput(ios);
   // Set the compression quality
   ImageWriteParam iwparam = new JPEGImageWriteParam(Locale.getDefault());
   iwparam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
   iwparam.setCompressionQuality(compressionQuality);
   // Write the image
   writer.write(null, new IIOImage(outImage, null, null), iwparam);
   // infile.delete();
   // Cleanup
   ios.flush();
   writer.dispose();
   ios.close();
   // return
 }
Ejemplo n.º 25
0
 public void setOutput(Object output) {
   super.setOutput(output); // validates output
   if (output != null) {
     if (!(output instanceof ImageOutputStream))
       throw new IllegalArgumentException(I18N.getString("WBMPImageWriter"));
     this.stream = (ImageOutputStream) output;
   } else this.stream = null;
 }
Ejemplo n.º 26
0
 public void initialize() {
   if (log.isTraceEnabled()) {
     String s = "Available JPEG image writers:";
     Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpeg");
     while (writers.hasNext()) {
       ImageWriter w = writers.next();
       s += "\n\t" + w.getClass().getName();
     }
     log.trace(s);
   }
   jpegImageWriter = ImageIO.getImageWritersByFormatName("jpeg").next();
   if (jpegImageWriter == null)
     throw new NullPointerException("Unable to create a JPEG image writer");
   jpegImageWriter.addIIOWriteWarningListener(ImageWriterWarningListener.INSTANCE);
   log.debug("Used JPEG image writer: " + jpegImageWriter.getClass().getName());
   iwp = jpegImageWriter.getDefaultWriteParam();
   iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
   iwp.setCompressionQuality(jpegCompressionLevel);
 }
Ejemplo n.º 27
0
  public void processImage(BufferedImage image, OutputStream out) throws IOException {

    if (image.getColorModel().hasAlpha()) {
      // Javas JPEG writes has a bug when the image has alpha transparency
      // see http://stackoverflow.com/questions/4386446/problem-using-imageio-write-jpg-file

      BufferedImage imageRGB =
          new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB);
      Graphics2D g = imageRGB.createGraphics();
      g.drawImage(image, null, 0, 0);
      g.dispose();
      image = imageRGB;
    }

    ImageOutputStream imageOut = ImageIO.createImageOutputStream(out);
    jpegImageWriter.setOutput(imageOut);
    IIOImage ioImage = new IIOImage(image, null, null);
    jpegImageWriter.write(null, ioImage, iwp);
  }
Ejemplo n.º 28
0
 /**
  * Returns the default write parameters for encoding the image.
  *
  * @param iiowriter The IIO ImageWriter that will be used
  * @param image the image to be encoded
  * @param params the parameters for this writer instance
  * @return the IIO ImageWriteParam instance
  */
 protected ImageWriteParam getDefaultWriteParam(
     javax.imageio.ImageWriter iiowriter, RenderedImage image, ImageWriterParams params) {
   ImageWriteParam param = iiowriter.getDefaultWriteParam();
   System.err.println("Param: " + params);
   if ((params != null) && (params.getCompressionMethod() != null)) {
     param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
     param.setCompressionType(params.getCompressionMethod());
   }
   return param;
 }
Ejemplo n.º 29
0
  public static byte[] getImageBytes(Image image, String type) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    BufferedImage bufImage = convertToBufferedImage(image);
    ImageWriter writer = null;
    Iterator i = ImageIO.getImageWritersByMIMEType(type);
    if (i.hasNext()) {
      writer = (ImageWriter) i.next();
    }
    if (writer != null) {
      ImageOutputStream stream = null;
      stream = ImageIO.createImageOutputStream(baos);
      writer.setOutput(stream);
      writer.write(bufImage);
      stream.close();
      return baos.toByteArray();
    }
    return null;
  }
  public static boolean compressPic(String srcFilePath, String descFilePath) {
    File file = null;
    BufferedImage src = null;
    FileOutputStream out = null;
    ImageWriter imgWrier;
    ImageWriteParam imgWriteParams;

    // 指定写图片的方式为 jpg
    imgWrier = ImageIO.getImageWritersByFormatName("jpg").next();
    imgWriteParams = new javax.imageio.plugins.jpeg.JPEGImageWriteParam(null);
    // 要使用压缩,必须指定压缩方式为MODE_EXPLICIT
    imgWriteParams.setCompressionMode(imgWriteParams.MODE_EXPLICIT);
    // 这里指定压缩的程度,参数qality是取值0~1范围内,
    imgWriteParams.setCompressionQuality((float) 0.1);
    imgWriteParams.setProgressiveMode(imgWriteParams.MODE_DISABLED);
    ColorModel colorModel = ColorModel.getRGBdefault();
    // 指定压缩时使用的色彩模式
    imgWriteParams.setDestinationType(
        new javax.imageio.ImageTypeSpecifier(
            colorModel, colorModel.createCompatibleSampleModel(16, 16)));

    try {
      if (StringUtils.isBlank(srcFilePath)) {
        return false;
      } else {
        file = new File(srcFilePath);
        src = ImageIO.read(file);
        out = new FileOutputStream(descFilePath);

        imgWrier.reset();
        // 必须先指定 out值,才能调用write方法, ImageOutputStream可以通过任何 OutputStream构造
        imgWrier.setOutput(ImageIO.createImageOutputStream(out));
        // 调用write方法,就可以向输入流写图片
        imgWrier.write(null, new IIOImage(src, null, null), imgWriteParams);
        out.flush();
        out.close();
      }
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
    return true;
  }