예제 #1
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
  /**
   * 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();
    }
  }
예제 #3
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);
  }
예제 #4
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;
  }
예제 #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;
 }
  @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());
  }
예제 #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);
    }
  }
예제 #8
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);
    }
  }
예제 #10
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);
  }
예제 #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();
 }
예제 #12
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;
 }
예제 #13
0
 public void setOutput(Object output) {
   super.setOutput(output);
   if (output != null) {
     if (!(output instanceof ImageOutputStream)) {
       throw new IllegalArgumentException("output is not an ImageOutputStream");
     }
     this.stream = (ImageOutputStream) output;
     this.stream.setByteOrder(ByteOrder.LITTLE_ENDIAN);
   } else {
     this.stream = null;
   }
 }
 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();
 }
  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;
  }
예제 #16
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;
  }
예제 #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;
   }
 }
예제 #18
0
  /**
   * @see ImageWriter#writeImage(java.awt.image.RenderedImage, java.io.OutputStream,
   *     ImageWriterParams)
   */
  public void writeImage(RenderedImage image, OutputStream out, ImageWriterParams params)
      throws IOException {
    Iterator iter;
    iter = ImageIO.getImageWritersByMIMEType(getMIMEType());
    javax.imageio.ImageWriter iiowriter = null;
    try {
      iiowriter = (javax.imageio.ImageWriter) iter.next();
      if (iiowriter != null) {
        iiowriter.addIIOWriteWarningListener(this);

        ImageOutputStream imgout = null;
        try {
          imgout = ImageIO.createImageOutputStream(out);
          ImageWriteParam iwParam = getDefaultWriteParam(iiowriter, image, params);

          ImageTypeSpecifier type;
          if (iwParam.getDestinationType() != null) {
            type = iwParam.getDestinationType();
          } else {
            type = ImageTypeSpecifier.createFromRenderedImage(image);
          }

          // Handle metadata
          IIOMetadata meta = iiowriter.getDefaultImageMetadata(type, iwParam);
          // meta might be null for some JAI codecs as they don't support metadata
          if (params != null && meta != null) {
            meta = updateMetadata(meta, params);
          }

          // Write image
          iiowriter.setOutput(imgout);
          IIOImage iioimg = new IIOImage(image, null, meta);
          iiowriter.write(null, iioimg, iwParam);
        } finally {
          if (imgout != null) {
            System.err.println("closing");
            imgout.close();
          }
        }
      } else {
        throw new UnsupportedOperationException(
            "No ImageIO codec for writing " + getMIMEType() + " is available!");
      }
    } finally {
      if (iiowriter != null) {
        System.err.println("disposing");
        iiowriter.dispose();
      }
    }
  }
 /**
  * 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();
 }
예제 #20
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();
   }
 }
예제 #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);
    }
  }
예제 #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();
    }
  }
예제 #23
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
 }
예제 #24
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);
  }
예제 #25
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;
  }
예제 #27
0
  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;
  }
예제 #28
0
    private void writeImageToFile(BufferedImage image, TFile file) throws IOException {
      Iterator iter = ImageIO.getImageWritersByFormatName("jpg");

      ImageWriter writer = (ImageWriter) iter.next();
      ImageWriteParam iwp = writer.getDefaultWriteParam();
      iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
      iwp.setCompressionQuality(0.96f);

      File tempFile =
          new File(Constants.IO.imageBaseDir + File.separator + image.hashCode() + file.getName());
      FileImageOutputStream output = new FileImageOutputStream(tempFile);
      writer.setOutput(output);
      IIOImage image2 = new IIOImage(image, null, null);
      writer.write(null, image2, iwp);
      writer.dispose();
      output.close();

      new TFile(tempFile).cp_rp(file);
      tempFile.delete();
    }
  private void writeInternal(
      BufferedImage image, MediaType contentType, HttpHeaders headers, OutputStream body)
      throws IOException, HttpMessageNotWritableException {

    if (contentType == null || contentType.isWildcardType() || contentType.isWildcardSubtype()) {
      contentType = getDefaultContentType();
    }
    Assert.notNull(
        contentType,
        "Count not determine Content-Type, set one using the 'defaultContentType' property");
    headers.setContentType(contentType);
    ImageOutputStream imageOutputStream = null;
    ImageWriter imageWriter = null;
    try {
      Iterator<ImageWriter> imageWriters =
          ImageIO.getImageWritersByMIMEType(contentType.toString());
      if (imageWriters.hasNext()) {
        imageWriter = imageWriters.next();
        ImageWriteParam iwp = imageWriter.getDefaultWriteParam();
        process(iwp);
        imageOutputStream = createImageOutputStream(body);
        imageWriter.setOutput(imageOutputStream);
        imageWriter.write(null, new IIOImage(image, null, null), iwp);
      } else {
        throw new HttpMessageNotWritableException(
            "Could not find javax.imageio.ImageWriter for Content-Type [" + contentType + "]");
      }
    } finally {
      if (imageWriter != null) {
        imageWriter.dispose();
      }
      if (imageOutputStream != null) {
        try {
          imageOutputStream.close();
        } catch (IOException ex) {
          // ignore
        }
      }
    }
  }
예제 #30
0
  public static File createImage(BufferedImage bi) {

    File tempFile = null;

    try {
      tempFile = File.createTempFile("tempImageFile", ".tif");
      tempFile.deleteOnExit();
      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");

      ImageWriter writer = writers.next();

      IIOImage image = new IIOImage(bi, null, null);

      tempFile = tempImageFile(tempFile);

      ImageOutputStream ios = ImageIO.createImageOutputStream(tempFile);

      writer.setOutput(ios);

      writer.write(null, image, tiffWriteParam);

      ios.close();

      writer.dispose();

    } catch (Exception exc) {

      exc.printStackTrace();
    }

    return tempFile;
  }