コード例 #1
0
ファイル: JMap2DFrame.java プロジェクト: Geomatys/geotoolkit
  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
コード例 #2
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);
  }
コード例 #3
0
  @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);
    }
  }
コード例 #4
0
ファイル: ImageIOHelper.java プロジェクト: AxellH/docs
  /**
   * 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);
  }
コード例 #5
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;
  }
コード例 #6
0
ファイル: graphPanel.java プロジェクト: TUDelftNAS/graphGEAR
 /**
  * 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;
 }
コード例 #7
0
ファイル: ImageUtils.java プロジェクト: dgkim11/examples
  /**
   * 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
  @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());
  }
コード例 #9
0
ファイル: GeoTiffTest.java プロジェクト: bradh/imageio-ext
  /**
   * 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());
  }
コード例 #10
0
 /** Cleans this {@link GrassBinaryImageWriter}. */
 public void dispose() {
   try {
     rasterWriter.close();
   } catch (Exception e) {
     e.printStackTrace();
   }
   super.dispose();
 }
コード例 #11
0
ファイル: GeoTiffTest.java プロジェクト: bradh/imageio-ext
  /**
   * 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);
  }
コード例 #12
0
 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();
 }
コード例 #13
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;
  }
コード例 #14
0
 /**
  * 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();
 }
コード例 #15
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();
      }
    }
  }
コード例 #16
0
ファイル: miniatura.java プロジェクト: ReneFGJr/URFGS-CEDAP
 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
 }
コード例 #17
0
ファイル: QrCodeUtils.java プロジェクト: scoophealth/oscar
  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();
    }
  }
コード例 #18
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;
  }
コード例 #19
0
ファイル: DownloadPictures.java プロジェクト: Blinke/mage
    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();
    }
コード例 #20
0
  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
        }
      }
    }
  }
コード例 #21
0
ファイル: ImageIOHelper.java プロジェクト: KeithZhang/zk
  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;
  }
コード例 #22
0
 private void writeToFile(File selectedFile, ImageWriterSpiFileFilter ff) {
   try {
     ImageOutputStream ios = ImageIO.createImageOutputStream(selectedFile);
     ImageWriter iw = ff.getImageWriterSpi().createWriterInstance();
     iw.setOutput(ios);
     ImageWriteParam iwp = iw.getDefaultWriteParam();
     if (iwp.canWriteCompressed()) {
       iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
       // set maximum image quality
       iwp.setCompressionQuality(1.f);
     }
     Image image = viewerPanel.getImage();
     BufferedImage bufferedImage;
     if (viewerPanel.getImage() instanceof BufferedImage)
       bufferedImage = (BufferedImage) viewerPanel.getImage();
     else {
       bufferedImage =
           new BufferedImage(
               image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB);
       bufferedImage.createGraphics().drawImage(image, 0, 0, null);
     }
     iw.write(null, new IIOImage(bufferedImage, null, null), iwp);
     iw.dispose();
     ios.close();
   } catch (IOException ioe) {
     JOptionPane.showMessageDialog(
         viewerPanel,
         messagesBundle.getString(
             "ImageViewerPanelSaveAction." + "Error_during_image_saving_message_7"),
         //$NON-NLS-1$
         messagesBundle.getString("ImageViewerPanelSaveAction." + "Error_dialog_title_8"),
         //$NON-NLS-1$
         JOptionPane.ERROR_MESSAGE);
     ioe.printStackTrace();
   }
 }
コード例 #23
0
  /**
   * This static method writes the indicated renderedImage (BufferedImage) to the indicated file.
   *
   * @param writeFile The File that shall receive the jpg data
   * @param renderedImage The RenderedImage (BufferedImage) to be written
   * @param jpgQuality The quality with which to compress to jpg
   */
  public static void writeJpg(File writeFile, RenderedImage renderedImage, float jpgQuality) {
    Iterator writers = ImageIO.getImageWritersByFormatName("jpg");
    ImageWriter writer = (ImageWriter) writers.next();
    JPEGImageWriteParam params = new JPEGImageWriteParam(null);
    params.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    params.setCompressionQuality(jpgQuality);
    params.setProgressiveMode(ImageWriteParam.MODE_DISABLED);
    params.setDestinationType(
        new ImageTypeSpecifier(
            java.awt.image.IndexColorModel.getRGBdefault(),
            IndexColorModel.getRGBdefault().createCompatibleSampleModel(16, 16)));

    try (ImageOutputStream ios = ImageIO.createImageOutputStream(new FileOutputStream(writeFile))) {
      writer.setOutput(ios);
      writer.write(null, new IIOImage(renderedImage, null, null), params);
      ios.close();
    } catch (IOException e) {
      // Tools.log("ScalablePicture.writeJpg caught IOException: " +  e.getMessage() + "\nwhile
      // writing " + writeFile.toString());
      e.printStackTrace();
    }
    // writer = null;
    writer.dispose(); // 1.4.1 documentation says to do this.
  }
コード例 #24
0
  /**
   * 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();
  }
コード例 #25
0
ファイル: ImageUtils.java プロジェクト: treejames/shop-2
  public static void addWatermark(File srcFile, File destFile, File watermarkFile, int alpha) {
    Assert.notNull(srcFile);
    Assert.notNull(destFile);
    Assert.state(alpha >= 0);
    Assert.state(alpha <= 100);
    if (watermarkFile == null || !watermarkFile.exists()) {
      try {
        FileUtils.copyFile(srcFile, destFile);
      } catch (IOException e) {
        e.printStackTrace();
      }
      return;
    }
    if (type == Type.jdk) {
      Graphics2D graphics2D = null;
      ImageOutputStream imageOutputStream = null;
      ImageWriter imageWriter = null;
      try {
        BufferedImage srcBufferedImage = ImageIO.read(srcFile);
        int srcWidth = srcBufferedImage.getWidth();
        int srcHeight = srcBufferedImage.getHeight();
        BufferedImage destBufferedImage =
            new BufferedImage(srcWidth, srcHeight, BufferedImage.TYPE_INT_RGB);
        graphics2D = destBufferedImage.createGraphics();
        graphics2D.setBackground(BACKGROUND_COLOR);
        graphics2D.clearRect(0, 0, srcWidth, srcHeight);
        graphics2D.drawImage(srcBufferedImage, 0, 0, null);
        graphics2D.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha / 100F));

        BufferedImage watermarkBufferedImage = ImageIO.read(watermarkFile);
        int watermarkImageWidth = watermarkBufferedImage.getWidth();
        int watermarkImageHeight = watermarkBufferedImage.getHeight();
        int x = srcWidth - watermarkImageWidth;
        int y = srcHeight - watermarkImageHeight;

        graphics2D.drawImage(
            watermarkBufferedImage, x, y, watermarkImageWidth, watermarkImageHeight, null);

        imageOutputStream = ImageIO.createImageOutputStream(destFile);
        imageWriter =
            ImageIO.getImageWritersByFormatName(FilenameUtils.getExtension(destFile.getName()))
                .next();
        imageWriter.setOutput(imageOutputStream);
        ImageWriteParam imageWriteParam = imageWriter.getDefaultWriteParam();
        imageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        imageWriteParam.setCompressionQuality(DEST_QUALITY / 100F);
        imageWriter.write(null, new IIOImage(destBufferedImage, null, null), imageWriteParam);
        imageOutputStream.flush();
      } catch (IOException e) {
        e.printStackTrace();
      } finally {
        if (graphics2D != null) {
          graphics2D.dispose();
        }
        if (imageWriter != null) {
          imageWriter.dispose();
        }
        if (imageOutputStream != null) {
          try {
            imageOutputStream.close();
          } catch (IOException e) {
          }
        }
      }
    } else {
      IMOperation operation = new IMOperation();
      operation.dissolve(alpha);
      operation.quality((double) DEST_QUALITY);
      operation.addImage(watermarkFile.getPath());
      operation.addImage(srcFile.getPath());
      operation.addImage(destFile.getPath());
      if (type == Type.graphicsMagick) {
        CompositeCmd compositeCmd = new CompositeCmd(true);
        if (graphicsMagickPath != null) {
          compositeCmd.setSearchPath(graphicsMagickPath);
        }
        try {
          compositeCmd.run(operation);
        } catch (IOException e) {
          e.printStackTrace();
        } catch (InterruptedException e) {
          e.printStackTrace();
        } catch (IM4JavaException e) {
          e.printStackTrace();
        }
      } else {
        CompositeCmd compositeCmd = new CompositeCmd(false);
        if (imageMagickPath != null) {
          compositeCmd.setSearchPath(imageMagickPath);
        }
        try {
          compositeCmd.run(operation);
        } catch (IOException e) {
          e.printStackTrace();
        } catch (InterruptedException e) {
          e.printStackTrace();
        } catch (IM4JavaException e) {
          e.printStackTrace();
        }
      }
    }
  }
コード例 #26
0
ファイル: ImageUtils.java プロジェクト: treejames/shop-2
  public static void zoom(File srcFile, File destFile, int destWidth, int destHeight) {
    Assert.notNull(srcFile);
    Assert.notNull(destFile);
    Assert.state(destWidth > 0);
    Assert.state(destHeight > 0);
    if (type == Type.jdk) {
      Graphics2D graphics2D = null;
      ImageOutputStream imageOutputStream = null;
      ImageWriter imageWriter = null;
      try {
        BufferedImage srcBufferedImage = ImageIO.read(srcFile);
        int srcWidth = srcBufferedImage.getWidth();
        int srcHeight = srcBufferedImage.getHeight();
        int width = destWidth;
        int height = destHeight;
        if (srcHeight >= srcWidth) {
          width = (int) Math.round(((destHeight * 1.0 / srcHeight) * srcWidth));
        } else {
          height = (int) Math.round(((destWidth * 1.0 / srcWidth) * srcHeight));
        }
        BufferedImage destBufferedImage =
            new BufferedImage(destWidth, destHeight, BufferedImage.TYPE_INT_RGB);
        graphics2D = destBufferedImage.createGraphics();
        graphics2D.setBackground(BACKGROUND_COLOR);
        graphics2D.clearRect(0, 0, destWidth, destHeight);
        graphics2D.drawImage(
            srcBufferedImage.getScaledInstance(width, height, Image.SCALE_SMOOTH),
            (destWidth / 2) - (width / 2),
            (destHeight / 2) - (height / 2),
            null);

        imageOutputStream = ImageIO.createImageOutputStream(destFile);
        imageWriter =
            ImageIO.getImageWritersByFormatName(FilenameUtils.getExtension(destFile.getName()))
                .next();
        imageWriter.setOutput(imageOutputStream);
        ImageWriteParam imageWriteParam = imageWriter.getDefaultWriteParam();
        imageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        imageWriteParam.setCompressionQuality((float) (DEST_QUALITY / 100.0));
        imageWriter.write(null, new IIOImage(destBufferedImage, null, null), imageWriteParam);
        imageOutputStream.flush();
      } catch (IOException e) {
        e.printStackTrace();
      } finally {
        if (graphics2D != null) {
          graphics2D.dispose();
        }
        if (imageWriter != null) {
          imageWriter.dispose();
        }
        if (imageOutputStream != null) {
          try {
            imageOutputStream.close();
          } catch (IOException e) {
          }
        }
      }
    } else {
      IMOperation operation = new IMOperation();
      operation.thumbnail(destWidth, destHeight);
      operation.gravity("center");
      operation.background(toHexEncoding(BACKGROUND_COLOR));
      operation.extent(destWidth, destHeight);
      operation.quality((double) DEST_QUALITY);
      operation.addImage(srcFile.getPath());
      operation.addImage(destFile.getPath());
      if (type == Type.graphicsMagick) {
        ConvertCmd convertCmd = new ConvertCmd(true);
        if (graphicsMagickPath != null) {
          convertCmd.setSearchPath(graphicsMagickPath);
        }
        try {
          convertCmd.run(operation);
        } catch (IOException e) {
          e.printStackTrace();
        } catch (InterruptedException e) {
          e.printStackTrace();
        } catch (IM4JavaException e) {
          e.printStackTrace();
        }
      } else {
        ConvertCmd convertCmd = new ConvertCmd(false);
        if (imageMagickPath != null) {
          convertCmd.setSearchPath(imageMagickPath);
        }
        try {
          convertCmd.run(operation);
        } catch (IOException e) {
          e.printStackTrace();
        } catch (InterruptedException e) {
          e.printStackTrace();
        } catch (IM4JavaException e) {
          e.printStackTrace();
        }
      }
    }
  }
コード例 #27
0
 public void dispose() {
   jpegImageWriter.dispose();
   jpegImageWriter = null;
 }
コード例 #28
0
ファイル: PdfGraphics2D.java プロジェクト: RealEnder/jsignpdf
  private boolean drawImage(
      Image img, Image mask, AffineTransform xform, Color bgColor, ImageObserver obs) {
    if (xform == null) xform = new AffineTransform();
    else xform = new AffineTransform(xform);
    xform.translate(0, img.getHeight(obs));
    xform.scale(img.getWidth(obs), img.getHeight(obs));

    AffineTransform inverse = this.normalizeMatrix();
    AffineTransform flipper = AffineTransform.getScaleInstance(1, -1);
    inverse.concatenate(xform);
    inverse.concatenate(flipper);

    double[] mx = new double[6];
    inverse.getMatrix(mx);
    if (currentFillGState != 255) {
      PdfGState gs = fillGState[255];
      if (gs == null) {
        gs = new PdfGState();
        gs.setFillOpacity(1);
        fillGState[255] = gs;
      }
      cb.setGState(gs);
    }

    try {
      com.lowagie.text.Image image = null;
      if (!convertImagesToJPEG) {
        image = com.lowagie.text.Image.getInstance(img, bgColor);
      } else {
        BufferedImage scaled =
            new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB);
        Graphics2D g3 = scaled.createGraphics();
        g3.drawImage(img, 0, 0, img.getWidth(null), img.getHeight(null), null);
        g3.dispose();

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageWriteParam iwparam = new JPEGImageWriteParam(Locale.getDefault());
        iwparam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        iwparam.setCompressionQuality(jpegQuality); // Set here your compression rate
        ImageWriter iw = (ImageWriter) ImageIO.getImageWritersByFormatName("jpg").next();
        ImageOutputStream ios = ImageIO.createImageOutputStream(baos);
        iw.setOutput(ios);
        iw.write(null, new IIOImage(scaled, null, null), iwparam);
        iw.dispose();
        ios.close();

        scaled.flush();
        scaled = null;
        image = com.lowagie.text.Image.getInstance(baos.toByteArray());
      }
      if (mask != null) {
        com.lowagie.text.Image msk = com.lowagie.text.Image.getInstance(mask, null, true);
        msk.makeMask();
        msk.setInverted(true);
        image.setImageMask(msk);
      }
      cb.addImage(
          image,
          (float) mx[0],
          (float) mx[1],
          (float) mx[2],
          (float) mx[3],
          (float) mx[4],
          (float) mx[5]);
      Object url = getRenderingHint(HyperLinkKey.KEY_INSTANCE);
      if (url != null && !url.equals(HyperLinkKey.VALUE_HYPERLINKKEY_OFF)) {
        PdfAction action = new PdfAction(url.toString());
        cb.setAction(
            action, (float) mx[4], (float) mx[5], (float) (mx[0] + mx[4]), (float) (mx[3] + mx[5]));
      }
    } catch (Exception ex) {
      throw new IllegalArgumentException();
    }
    if (currentFillGState != 255) {
      PdfGState gs = fillGState[currentFillGState];
      cb.setGState(gs);
    }
    return true;
  }
コード例 #29
0
ファイル: JAISupport.java プロジェクト: gollon/geoserver
  /**
   * 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();
  }
コード例 #30
0
ファイル: Movie.java プロジェクト: sansibar/JAVMovieScraper
  public void writeToFile(
      File nfofile,
      File posterFile,
      File fanartFile,
      File currentlySelectedFolderJpgFile,
      MoviescraperPreferences preferences)
      throws IOException {
    // Output the movie to XML using XStream and a proxy class to
    // translate things to a format that xbmc expects

    String xml = new XbmcXmlMovieBean(this).toXML();
    // add the xml header since xstream doesn't do this
    xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\" ?>" + "\n" + xml;
    System.out.println("Xml I am writing to file: \n" + xml);

    FileUtils.writeStringToFile(nfofile, xml, org.apache.commons.lang3.CharEncoding.UTF_8);

    Thumb posterToSaveToDisk = posters[0];

    boolean writePoster = preferences.getWriteFanartAndPostersPreference();
    boolean writeFanart = preferences.getWriteFanartAndPostersPreference();
    boolean writePosterIfAlreadyExists = preferences.getOverWriteFanartAndPostersPreference();
    boolean writeFanartIfAlreadyExists = preferences.getOverWriteFanartAndPostersPreference();
    boolean createFolderJpgEnabledPreference = preferences.getCreateFolderJpgEnabledPreference();

    // save the first poster out
    // maybe we did some clipping, so we're going to have to reencode it
    if (this.getPosters().length > 0
        && (writePoster || createFolderJpgEnabledPreference)
        && ((posterFile.exists() == writePosterIfAlreadyExists)
            || (!posterFile.exists() || (createFolderJpgEnabledPreference)))) {
      if (posterToSaveToDisk.isModified()
          || createFolderJpgEnabledPreference
          || !posterFile.exists()) {
        // reencode the jpg since we probably did a resize
        Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("jpeg");
        ImageWriter writer = (ImageWriter) iter.next();
        // instantiate an ImageWriteParam object with default compression options
        ImageWriteParam iwp = writer.getDefaultWriteParam();
        iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        iwp.setCompressionQuality(1); // an float between 0 and 1
        // 1 specifies minimum compression and maximum quality
        IIOImage image =
            new IIOImage((RenderedImage) posterToSaveToDisk.getThumbImage(), null, null);

        if (writePoster && posterFile != null && posterToSaveToDisk.isModified()) {
          System.out.println("Writing poster to " + posterFile);
          FileImageOutputStream posterFileOutput = new FileImageOutputStream(posterFile);
          writer.setOutput(posterFileOutput);
          writer.write(null, image, iwp);
          posterFileOutput.close();
        }
        // write out the poster file without reencoding it and resizing it
        else if ((!posterFile.exists() || writePosterIfAlreadyExists)
            && posterToSaveToDisk != null
            && posterToSaveToDisk.getThumbURL() != null
            && !posterToSaveToDisk.isLoadedFromDisk()) {
          System.out.println("Writing poster file with no changes to " + posterFile);
          FileUtils.copyURLToFile(
              posterToSaveToDisk.getThumbURL(), posterFile, connectionTimeout, readTimeout);
        }
        if (createFolderJpgEnabledPreference && currentlySelectedFolderJpgFile != null) {
          if (!posterToSaveToDisk.isModified()) {
            System.out.println(
                "Writing folder.jpg (no changes) to " + currentlySelectedFolderJpgFile);
            FileUtils.copyURLToFile(
                posterToSaveToDisk.getThumbURL(),
                currentlySelectedFolderJpgFile,
                connectionTimeout,
                readTimeout);
          } else {
            System.out.println("Writing folder to " + currentlySelectedFolderJpgFile);
            FileImageOutputStream folderFileOutput =
                new FileImageOutputStream(currentlySelectedFolderJpgFile);
            writer.setOutput(folderFileOutput);
            writer.write(null, image, iwp);
            folderFileOutput.close();
          }
        }
        writer.dispose();
      }
      // else
      // {
      // System.out.println("In Else");
      // if(writePoster)
      // FileUtils.copyURLToFile(posterToSaveToDisk.getThumbURL(), fanartFile, connectionTimeout,
      // readTimeout);
      // if(createFolderJpgEnabledPreference)
      // FileUtils.copyURLToFile(posterToSaveToDisk.getThumbURL(), currentlySelectedFolderJpgFile,
      // connectionTimeout, readTimeout);
      // }
    }

    // save the first fanart out
    // we didn't modify it so we can write it directly from the URL
    if (this.getFanart().length > 0
        && writeFanart
        && ((fanartFile.exists() == writeFanartIfAlreadyExists) || !fanartFile.exists())) {
      if (fanart != null && fanart.length > 0) {
        Thumb fanartToSaveToDisk;
        if (preferredFanartToWriteToDisk != null) fanartToSaveToDisk = preferredFanartToWriteToDisk;
        else fanartToSaveToDisk = fanart[0];
        System.out.println("saving out first fanart to " + fanartFile);
        FileUtils.copyURLToFile(
            fanartToSaveToDisk.getThumbURL(), fanartFile, connectionTimeout, readTimeout);
      }
    }
  }