Ejemplo n.º 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
Ejemplo n.º 2
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);
  }
  @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.º 4
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;
 }
 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;
  }
 /**
  * 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.º 8
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.º 9
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();
    }
  }
Ejemplo n.º 10
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.º 11
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
        }
      }
    }
  }
 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();
   }
 }
Ejemplo n.º 14
0
  /**
   * Write the image to a file in uncompressed tiff format.
   *
   * @param image image to write
   * @param file path and file name (extension will be ignored and changed to tiff.
   */
  public static void writeUncompressedImage(BufferedImage image, String file) throws IOException {
    FileImageOutputStream out = null;
    try {
      final File parentFile = new File(file).getParentFile();
      Iterator<ImageWriter> writers = ImageIO.getImageWritersBySuffix("tiff");
      final ImageWriter next = writers.next();

      final ImageWriteParam param = next.getDefaultWriteParam();
      param.setCompressionMode(ImageWriteParam.MODE_DISABLED);

      final File outputFile = new File(parentFile, Files.getNameWithoutExtension(file) + ".tiff");

      out = new FileImageOutputStream(outputFile);
      next.setOutput(out);
      next.write(image);
    } catch (Throwable e) {
      System.err.println("Error writing the image generated by the test:" + file + "\n\t");
      e.printStackTrace();
    } finally {
      if (out != null) {
        out.close();
      }
    }
  }
Ejemplo n.º 15
0
  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);
      }
    }
  }
Ejemplo n.º 16
0
  /**
   * Encodes a BufferedImage using JAI in <code>format</code> format and sends it to <code>outStream
   * </code>.
   *
   * @param format the MIME type of the output image in which to encode <code>image</code> through
   *     JAI
   * @param image the actual image to be encoded in <code>format</code> format.
   * @param outStream the encoded image destination.
   * @throws IOException if the image writing to <code>outStream</code> fails.
   * @throws IllegalArgumentException if <code>format</code> is not a supported output format for
   *     the installed JAI library.
   */
  public static void encode(String format, BufferedImage image, OutputStream outStream)
      throws IOException {
    if (format.equalsIgnoreCase("jpeg")) {
      format = "image/jpeg";
    }

    Iterator it = ImageIO.getImageWritersByMIMEType(format);

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

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

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

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

      meta = writer.getDefaultStreamMetadata(param);

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

      image = curImage;

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

      return;
    }

    ioutstream = ImageIOExt.createImageOutputStream(image, outStream);
    writer.setOutput(ioutstream);
    writer.write(meta, new IIOImage(image, null, meta), param);
    ioutstream.close();
    writer.dispose();
  }
Ejemplo n.º 17
0
  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();
        }
      }
    }
  }
Ejemplo n.º 18
0
  /**
   * Takes the Scene and writes an image file according to the constraints defined by the caller.
   * This returns a BufferedImage of the Scene even if the file can not be written.
   *
   * @param visibleAreaOnly Eliminates all zoom features. If true, the exported image will be a
   *     created from the visible area of the scene.
   * @param selectedOnly Create an image including only the objects selected on the scene. Note that
   *     this feature requires that the scene is an instance of an ObjectScene since it is the
   *     implementation that allows for object selection.
   * @param quality And integer value between 0-100. This is for JPG images only. Parameter is not
   *     used if an image type other than jpg is selected.
   * @param width Directly sets the horizontal dimension of the exported image. This is only used
   *     when the zoomType is ZoomType.CUSTOM_SIZE
   * @param height Directly sets the vertical dimension of the exported image. This is only used
   *     when the zoomType is ZoomType.CUSTOM_SIZE.
   * @param createImageMap If true, the necessary steps are taken to setup the sequential call to
   *     getSceneImageMapCoordinates.
   * @return image The raw image that was written to the file.
   * @throws java.io.IOException If for some reason the file cannot be written, an IOExeption will
   *     be thrown.
   */
  public BufferedImage createImage(
      ImageType imageType,
      ZoomType zoomType,
      boolean visibleAreaOnly,
      boolean selectedOnly,
      int quality,
      int width,
      int height,
      boolean createImageMap)
      throws IOException {
    double _scale = scene.getZoomFactor();

    Rectangle sceneRec = scene.getPreferredBounds();
    Rectangle viewRect = scene.getView().getVisibleRect();

    BufferedImage bufferedImage;
    Graphics2D g;
    ArrayList<Widget> hiddenWidgets = new ArrayList<Widget>();

    int _imageWidth = sceneRec.width;
    int _imageHeight = sceneRec.height;

    Set<?> _selectedObjects = null;

    if (selectedOnly) {
      // in order to use getSelectedObject the scene must be an
      // ObjectScene
      if (scene instanceof ObjectScene) {

        ObjectScene gScene = (ObjectScene) scene;
        // hide unselected widget
        HashSet<Object> invisible = new HashSet<Object>();
        invisible.addAll(gScene.getObjects());
        _selectedObjects = gScene.getSelectedObjects();
        invisible.removeAll(_selectedObjects);

        for (Object o : invisible) {
          Widget widget = gScene.findWidget(o);
          if (widget != null && widget.isVisible()) {
            widget.setVisible(false);
            hiddenWidgets.add(widget);
          }
        }
      }
    }

    if (visibleAreaOnly) {
      _imageWidth = viewRect.width;
      _imageHeight = viewRect.height;
    } else {
      switch (zoomType) {
        case CUSTOM_SIZE:
          _imageWidth = width;
          _imageHeight = height;
          _scale =
              Math.min(
                  (double) width / (double) sceneRec.width,
                  (double) height / (double) sceneRec.height);
          break;
        case FIT_IN_WINDOW:
          _scale =
              Math.min(
                  (double) viewRect.width / (double) sceneRec.width,
                  (double) viewRect.height / (double) sceneRec.height);
          _imageWidth = (int) ((double) sceneRec.width * _scale);
          _imageHeight = (int) ((double) sceneRec.height * _scale);
          break;
        case CURRENT_ZOOM_LEVEL:
          _imageWidth = (int) (sceneRec.width * scene.getZoomFactor());
          _imageHeight = (int) (sceneRec.height * scene.getZoomFactor());
          break;
        case ACTUAL_SIZE:
          _imageWidth = sceneRec.width;
          _imageHeight = sceneRec.height;
          _scale = 1.0;
          break;
      }
    }

    // Note that the field variable are being set to method local variable.
    // This
    // is for the call to getSceneImageMapCoordinates that will come since
    // createImageMap is true.
    if (createImageMap) {
      this.selectedObjects = _selectedObjects;
      this.imageHeight = _imageHeight;
      this.imageWidth = _imageWidth;
      this.scale = _scale;
    }

    bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    g = bufferedImage.createGraphics();
    g.translate(0, 0);
    g.scale(_scale, _scale);
    g.setColor(Color.WHITE);
    g.fillRect(0, 0, width, height);
    scene.paint(g);

    // restore widget visibility
    for (Widget w : hiddenWidgets) {
      w.setVisible(true);
    }

    if (file != null) {
      FileImageOutputStream fo = new FileImageOutputStream(file);

      if (imageType == ImageType.JPG) {
        Iterator<?> iter = ImageIO.getImageWritersByFormatName("jpg");
        ImageWriter writer = (ImageWriter) iter.next();

        ImageWriteParam iwp = writer.getDefaultWriteParam();
        iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        if (quality > 100) {
          quality = 100;
        }
        if (quality < 0) {
          quality = 0;
        }
        iwp.setCompressionQuality(quality / 100);
        writer.setOutput(fo);
        IIOImage image = new IIOImage(bufferedImage, null, null);
        writer.write(null, image, iwp);

        writer.dispose();
      } else {
        ImageIO.write(bufferedImage, "" + imageType, fo);
      }

      fo.flush();
      fo.close();
    }

    return bufferedImage;
  }
Ejemplo n.º 19
0
  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();
        }
      }
    }
  }
Ejemplo n.º 20
0
  public void build_bricks() {

    ImagePlus imp;
    ImagePlus orgimp;
    ImageStack stack;
    FileInfo finfo;

    if (lvImgTitle.isEmpty()) return;
    orgimp = WindowManager.getImage(lvImgTitle.get(0));
    imp = orgimp;

    finfo = imp.getFileInfo();
    if (finfo == null) return;

    int[] dims = imp.getDimensions();
    int imageW = dims[0];
    int imageH = dims[1];
    int nCh = dims[2];
    int imageD = dims[3];
    int nFrame = dims[4];
    int bdepth = imp.getBitDepth();
    double xspc = finfo.pixelWidth;
    double yspc = finfo.pixelHeight;
    double zspc = finfo.pixelDepth;
    double z_aspect = Math.max(xspc, yspc) / zspc;

    int orgW = imageW;
    int orgH = imageH;
    int orgD = imageD;
    double orgxspc = xspc;
    double orgyspc = yspc;
    double orgzspc = zspc;

    lv = lvImgTitle.size();
    if (filetype == "JPEG") {
      for (int l = 0; l < lv; l++) {
        if (WindowManager.getImage(lvImgTitle.get(l)).getBitDepth() != 8) {
          IJ.error("A SOURCE IMAGE MUST BE 8BIT GLAYSCALE");
          return;
        }
      }
    }

    // calculate levels
    /*		int baseXY = 256;
    		int baseZ = 256;

    		if (z_aspect < 0.5) baseZ = 128;
    		if (z_aspect > 2.0) baseXY = 128;
    		if (z_aspect >= 0.5 && z_aspect < 1.0) baseZ = (int)(baseZ*z_aspect);
    		if (z_aspect > 1.0 && z_aspect <= 2.0) baseXY = (int)(baseXY/z_aspect);

    		IJ.log("Z_aspect: " + z_aspect);
    		IJ.log("BaseXY: " + baseXY);
    		IJ.log("BaseZ: " + baseZ);
    */

    int baseXY = 256;
    int baseZ = 128;
    int dbXY = Math.max(orgW, orgH) / baseXY;
    if (Math.max(orgW, orgH) % baseXY > 0) dbXY *= 2;
    int dbZ = orgD / baseZ;
    if (orgD % baseZ > 0) dbZ *= 2;
    lv = Math.max(log2(dbXY), log2(dbZ)) + 1;

    int ww = orgW;
    int hh = orgH;
    int dd = orgD;
    for (int l = 0; l < lv; l++) {
      int bwnum = ww / baseXY;
      if (ww % baseXY > 0) bwnum++;
      int bhnum = hh / baseXY;
      if (hh % baseXY > 0) bhnum++;
      int bdnum = dd / baseZ;
      if (dd % baseZ > 0) bdnum++;

      if (bwnum % 2 == 0) bwnum++;
      if (bhnum % 2 == 0) bhnum++;
      if (bdnum % 2 == 0) bdnum++;

      int bw = (bwnum <= 1) ? ww : ww / bwnum + 1 + (ww % bwnum > 0 ? 1 : 0);
      int bh = (bhnum <= 1) ? hh : hh / bhnum + 1 + (hh % bhnum > 0 ? 1 : 0);
      int bd = (bdnum <= 1) ? dd : dd / bdnum + 1 + (dd % bdnum > 0 ? 1 : 0);

      bwlist.add(bw);
      bhlist.add(bh);
      bdlist.add(bd);

      IJ.log("LEVEL: " + l);
      IJ.log("  width: " + ww);
      IJ.log("  hight: " + hh);
      IJ.log("  depth: " + dd);
      IJ.log("  bw: " + bw);
      IJ.log("  bh: " + bh);
      IJ.log("  bd: " + bd);

      int xyl2 = Math.max(ww, hh) / baseXY;
      if (Math.max(ww, hh) % baseXY > 0) xyl2 *= 2;
      if (lv - 1 - log2(xyl2) <= l) {
        ww /= 2;
        hh /= 2;
      }
      IJ.log("  xyl2: " + (lv - 1 - log2(xyl2)));

      int zl2 = dd / baseZ;
      if (dd % baseZ > 0) zl2 *= 2;
      if (lv - 1 - log2(zl2) <= l) dd /= 2;
      IJ.log("  zl2: " + (lv - 1 - log2(zl2)));

      if (l < lv - 1) {
        lvImgTitle.add(lvImgTitle.get(0) + "_level" + (l + 1));
        IJ.selectWindow(lvImgTitle.get(0));
        IJ.run(
            "Scale...",
            "x=- y=- z=- width="
                + ww
                + " height="
                + hh
                + " depth="
                + dd
                + " interpolation=Bicubic average process create title="
                + lvImgTitle.get(l + 1));
      }
    }

    for (int l = 0; l < lv; l++) {
      IJ.log(lvImgTitle.get(l));
    }

    Document doc = newXMLDocument();
    Element root = doc.createElement("BRK");
    root.setAttribute("version", "1.0");
    root.setAttribute("nLevel", String.valueOf(lv));
    root.setAttribute("nChannel", String.valueOf(nCh));
    root.setAttribute("nFrame", String.valueOf(nFrame));
    doc.appendChild(root);

    for (int l = 0; l < lv; l++) {
      IJ.showProgress(0.0);

      int[] dims2 = imp.getDimensions();
      IJ.log(
          "W: "
              + String.valueOf(dims2[0])
              + " H: "
              + String.valueOf(dims2[1])
              + " C: "
              + String.valueOf(dims2[2])
              + " D: "
              + String.valueOf(dims2[3])
              + " T: "
              + String.valueOf(dims2[4])
              + " b: "
              + String.valueOf(bdepth));

      bw = bwlist.get(l).intValue();
      bh = bhlist.get(l).intValue();
      bd = bdlist.get(l).intValue();

      boolean force_pow2 = false;
      /*			if(IsPowerOf2(bw) && IsPowerOf2(bh) && IsPowerOf2(bd)) force_pow2 = true;

      			if(force_pow2){
      				//force pow2
      				if(Pow2(bw) > bw) bw = Pow2(bw)/2;
      				if(Pow2(bh) > bh) bh = Pow2(bh)/2;
      				if(Pow2(bd) > bd) bd = Pow2(bd)/2;
      			}

      			if(bw > imageW) bw = (Pow2(imageW) == imageW) ? imageW : Pow2(imageW)/2;
      			if(bh > imageH) bh = (Pow2(imageH) == imageH) ? imageH : Pow2(imageH)/2;
      			if(bd > imageD) bd = (Pow2(imageD) == imageD) ? imageD : Pow2(imageD)/2;

      */
      if (bw > imageW) bw = imageW;
      if (bh > imageH) bh = imageH;
      if (bd > imageD) bd = imageD;

      if (bw <= 1 || bh <= 1 || bd <= 1) break;

      if (filetype == "JPEG" && (bw < 8 || bh < 8)) break;

      Element lvnode = doc.createElement("Level");
      lvnode.setAttribute("lv", String.valueOf(l));
      lvnode.setAttribute("imageW", String.valueOf(imageW));
      lvnode.setAttribute("imageH", String.valueOf(imageH));
      lvnode.setAttribute("imageD", String.valueOf(imageD));
      lvnode.setAttribute("xspc", String.valueOf(xspc));
      lvnode.setAttribute("yspc", String.valueOf(yspc));
      lvnode.setAttribute("zspc", String.valueOf(zspc));
      lvnode.setAttribute("bitDepth", String.valueOf(bdepth));
      root.appendChild(lvnode);

      Element brksnode = doc.createElement("Bricks");
      brksnode.setAttribute("brick_baseW", String.valueOf(bw));
      brksnode.setAttribute("brick_baseH", String.valueOf(bh));
      brksnode.setAttribute("brick_baseD", String.valueOf(bd));
      lvnode.appendChild(brksnode);

      ArrayList<Brick> bricks = new ArrayList<Brick>();
      int mw, mh, md, mw2, mh2, md2;
      double tx0, ty0, tz0, tx1, ty1, tz1;
      double bx0, by0, bz0, bx1, by1, bz1;
      for (int k = 0; k < imageD; k += bd) {
        if (k > 0) k--;
        for (int j = 0; j < imageH; j += bh) {
          if (j > 0) j--;
          for (int i = 0; i < imageW; i += bw) {
            if (i > 0) i--;
            mw = Math.min(bw, imageW - i);
            mh = Math.min(bh, imageH - j);
            md = Math.min(bd, imageD - k);

            if (force_pow2) {
              mw2 = Pow2(mw);
              mh2 = Pow2(mh);
              md2 = Pow2(md);
            } else {
              mw2 = mw;
              mh2 = mh;
              md2 = md;
            }

            if (filetype == "JPEG") {
              if (mw2 < 8) mw2 = 8;
              if (mh2 < 8) mh2 = 8;
            }

            tx0 = i == 0 ? 0.0d : ((mw2 - mw + 0.5d) / mw2);
            ty0 = j == 0 ? 0.0d : ((mh2 - mh + 0.5d) / mh2);
            tz0 = k == 0 ? 0.0d : ((md2 - md + 0.5d) / md2);

            tx1 = 1.0d - 0.5d / mw2;
            if (mw < bw) tx1 = 1.0d;
            if (imageW - i == bw) tx1 = 1.0d;

            ty1 = 1.0d - 0.5d / mh2;
            if (mh < bh) ty1 = 1.0d;
            if (imageH - j == bh) ty1 = 1.0d;

            tz1 = 1.0d - 0.5d / md2;
            if (md < bd) tz1 = 1.0d;
            if (imageD - k == bd) tz1 = 1.0d;

            bx0 = i == 0 ? 0.0d : (i + 0.5d) / (double) imageW;
            by0 = j == 0 ? 0.0d : (j + 0.5d) / (double) imageH;
            bz0 = k == 0 ? 0.0d : (k + 0.5d) / (double) imageD;

            bx1 = Math.min((i + bw - 0.5d) / (double) imageW, 1.0d);
            if (imageW - i == bw) bx1 = 1.0d;

            by1 = Math.min((j + bh - 0.5d) / (double) imageH, 1.0d);
            if (imageH - j == bh) by1 = 1.0d;

            bz1 = Math.min((k + bd - 0.5d) / (double) imageD, 1.0d);
            if (imageD - k == bd) bz1 = 1.0d;

            int x, y, z;
            x = i - (mw2 - mw);
            y = j - (mh2 - mh);
            z = k - (md2 - md);
            bricks.add(
                new Brick(
                    x, y, z, mw2, mh2, md2, 0, 0, tx0, ty0, tz0, tx1, ty1, tz1, bx0, by0, bz0, bx1,
                    by1, bz1));
          }
        }
      }

      Element fsnode = doc.createElement("Files");
      lvnode.appendChild(fsnode);

      stack = imp.getStack();

      int totalbricknum = nFrame * nCh * bricks.size();
      int curbricknum = 0;
      for (int f = 0; f < nFrame; f++) {
        for (int ch = 0; ch < nCh; ch++) {
          int sizelimit = bdsizelimit * 1024 * 1024;
          int bytecount = 0;
          int filecount = 0;
          int pd_bufsize = Math.max(sizelimit, bw * bh * bd * bdepth / 8);
          byte[] packed_data = new byte[pd_bufsize];
          String base_dataname =
              basename
                  + "_Lv"
                  + String.valueOf(l)
                  + "_Ch"
                  + String.valueOf(ch)
                  + "_Fr"
                  + String.valueOf(f);
          String current_dataname = base_dataname + "_data" + filecount;

          Brick b_first = bricks.get(0);
          if (b_first.z_ != 0) IJ.log("warning");
          int st_z = b_first.z_;
          int ed_z = b_first.z_ + b_first.d_;
          LinkedList<ImageProcessor> iplist = new LinkedList<ImageProcessor>();
          for (int s = st_z; s < ed_z; s++)
            iplist.add(stack.getProcessor(imp.getStackIndex(ch + 1, s + 1, f + 1)));

          //					ImagePlus test;
          //					ImageStack tsst;
          //					test = NewImage.createByteImage("test", imageW, imageH, imageD,
          // NewImage.FILL_BLACK);
          //					tsst = test.getStack();
          for (int i = 0; i < bricks.size(); i++) {
            Brick b = bricks.get(i);

            if (ed_z > b.z_ || st_z < b.z_ + b.d_) {
              if (b.z_ > st_z) {
                for (int s = 0; s < b.z_ - st_z; s++) iplist.pollFirst();
                st_z = b.z_;
              } else if (b.z_ < st_z) {
                IJ.log("warning");
                for (int s = st_z - 1; s > b.z_; s--)
                  iplist.addFirst(stack.getProcessor(imp.getStackIndex(ch + 1, s + 1, f + 1)));
                st_z = b.z_;
              }

              if (b.z_ + b.d_ > ed_z) {
                for (int s = ed_z; s < b.z_ + b.d_; s++)
                  iplist.add(stack.getProcessor(imp.getStackIndex(ch + 1, s + 1, f + 1)));
                ed_z = b.z_ + b.d_;
              } else if (b.z_ + b.d_ < ed_z) {
                IJ.log("warning");
                for (int s = 0; s < ed_z - (b.z_ + b.d_); s++) iplist.pollLast();
                ed_z = b.z_ + b.d_;
              }
            } else {
              IJ.log("warning");
              iplist.clear();
              st_z = b.z_;
              ed_z = b.z_ + b.d_;
              for (int s = st_z; s < ed_z; s++)
                iplist.add(stack.getProcessor(imp.getStackIndex(ch + 1, s + 1, f + 1)));
            }

            if (iplist.size() != b.d_) {
              IJ.log("Stack Error");
              return;
            }

            //						int zz = st_z;

            int bsize = 0;
            byte[] bdata = new byte[b.w_ * b.h_ * b.d_ * bdepth / 8];
            Iterator<ImageProcessor> ipite = iplist.iterator();
            while (ipite.hasNext()) {

              //							ImageProcessor tsip = tsst.getProcessor(zz+1);

              ImageProcessor ip = ipite.next();
              ip.setRoi(b.x_, b.y_, b.w_, b.h_);
              if (bdepth == 8) {
                byte[] data = (byte[]) ip.crop().getPixels();
                System.arraycopy(data, 0, bdata, bsize, data.length);
                bsize += data.length;
              } else if (bdepth == 16) {
                ByteBuffer buffer = ByteBuffer.allocate(b.w_ * b.h_ * bdepth / 8);
                buffer.order(ByteOrder.LITTLE_ENDIAN);
                short[] data = (short[]) ip.crop().getPixels();
                for (short e : data) buffer.putShort(e);
                System.arraycopy(buffer.array(), 0, bdata, bsize, buffer.array().length);
                bsize += buffer.array().length;
              } else if (bdepth == 32) {
                ByteBuffer buffer = ByteBuffer.allocate(b.w_ * b.h_ * bdepth / 8);
                buffer.order(ByteOrder.LITTLE_ENDIAN);
                float[] data = (float[]) ip.crop().getPixels();
                for (float e : data) buffer.putFloat(e);
                System.arraycopy(buffer.array(), 0, bdata, bsize, buffer.array().length);
                bsize += buffer.array().length;
              }
            }

            String filename =
                basename
                    + "_Lv"
                    + String.valueOf(l)
                    + "_Ch"
                    + String.valueOf(ch)
                    + "_Fr"
                    + String.valueOf(f)
                    + "_ID"
                    + String.valueOf(i);

            int offset = bytecount;
            int datasize = bdata.length;

            if (filetype == "RAW") {
              int dummy = -1;
              // do nothing
            }
            if (filetype == "JPEG" && bdepth == 8) {
              try {
                DataBufferByte db = new DataBufferByte(bdata, datasize);
                Raster raster = Raster.createPackedRaster(db, b.w_, b.h_ * b.d_, 8, null);
                BufferedImage img =
                    new BufferedImage(b.w_, b.h_ * b.d_, BufferedImage.TYPE_BYTE_GRAY);
                img.setData(raster);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ImageOutputStream ios = ImageIO.createImageOutputStream(baos);
                String format = "jpg";
                Iterator<javax.imageio.ImageWriter> iter =
                    ImageIO.getImageWritersByFormatName("jpeg");
                javax.imageio.ImageWriter writer = iter.next();
                ImageWriteParam iwp = writer.getDefaultWriteParam();
                iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
                iwp.setCompressionQuality((float) jpeg_quality * 0.01f);
                writer.setOutput(ios);
                writer.write(null, new IIOImage(img, null, null), iwp);
                // ImageIO.write(img, format, baos);
                bdata = baos.toByteArray();
                datasize = bdata.length;
              } catch (IOException e) {
                e.printStackTrace();
                return;
              }
            }
            if (filetype == "ZLIB") {
              byte[] tmpdata = new byte[b.w_ * b.h_ * b.d_ * bdepth / 8];
              Deflater compresser = new Deflater();
              compresser.setInput(bdata);
              compresser.setLevel(Deflater.DEFAULT_COMPRESSION);
              compresser.setStrategy(Deflater.DEFAULT_STRATEGY);
              compresser.finish();
              datasize = compresser.deflate(tmpdata);
              bdata = tmpdata;
              compresser.end();
            }

            if (bytecount + datasize > sizelimit && bytecount > 0) {
              BufferedOutputStream fis = null;
              try {
                File file = new File(directory + current_dataname);
                fis = new BufferedOutputStream(new FileOutputStream(file));
                fis.write(packed_data, 0, bytecount);
              } catch (IOException e) {
                e.printStackTrace();
                return;
              } finally {
                try {
                  if (fis != null) fis.close();
                } catch (IOException e) {
                  e.printStackTrace();
                  return;
                }
              }
              filecount++;
              current_dataname = base_dataname + "_data" + filecount;
              bytecount = 0;
              offset = 0;
              System.arraycopy(bdata, 0, packed_data, bytecount, datasize);
              bytecount += datasize;
            } else {
              System.arraycopy(bdata, 0, packed_data, bytecount, datasize);
              bytecount += datasize;
            }

            Element filenode = doc.createElement("File");
            filenode.setAttribute("filename", current_dataname);
            filenode.setAttribute("channel", String.valueOf(ch));
            filenode.setAttribute("frame", String.valueOf(f));
            filenode.setAttribute("brickID", String.valueOf(i));
            filenode.setAttribute("offset", String.valueOf(offset));
            filenode.setAttribute("datasize", String.valueOf(datasize));
            filenode.setAttribute("filetype", String.valueOf(filetype));

            fsnode.appendChild(filenode);

            curbricknum++;
            IJ.showProgress((double) (curbricknum) / (double) (totalbricknum));
          }
          if (bytecount > 0) {
            BufferedOutputStream fis = null;
            try {
              File file = new File(directory + current_dataname);
              fis = new BufferedOutputStream(new FileOutputStream(file));
              fis.write(packed_data, 0, bytecount);
            } catch (IOException e) {
              e.printStackTrace();
              return;
            } finally {
              try {
                if (fis != null) fis.close();
              } catch (IOException e) {
                e.printStackTrace();
                return;
              }
            }
          }
        }
      }

      for (int i = 0; i < bricks.size(); i++) {
        Brick b = bricks.get(i);
        Element bricknode = doc.createElement("Brick");
        bricknode.setAttribute("id", String.valueOf(i));
        bricknode.setAttribute("st_x", String.valueOf(b.x_));
        bricknode.setAttribute("st_y", String.valueOf(b.y_));
        bricknode.setAttribute("st_z", String.valueOf(b.z_));
        bricknode.setAttribute("width", String.valueOf(b.w_));
        bricknode.setAttribute("height", String.valueOf(b.h_));
        bricknode.setAttribute("depth", String.valueOf(b.d_));
        brksnode.appendChild(bricknode);

        Element tboxnode = doc.createElement("tbox");
        tboxnode.setAttribute("x0", String.valueOf(b.tx0_));
        tboxnode.setAttribute("y0", String.valueOf(b.ty0_));
        tboxnode.setAttribute("z0", String.valueOf(b.tz0_));
        tboxnode.setAttribute("x1", String.valueOf(b.tx1_));
        tboxnode.setAttribute("y1", String.valueOf(b.ty1_));
        tboxnode.setAttribute("z1", String.valueOf(b.tz1_));
        bricknode.appendChild(tboxnode);

        Element bboxnode = doc.createElement("bbox");
        bboxnode.setAttribute("x0", String.valueOf(b.bx0_));
        bboxnode.setAttribute("y0", String.valueOf(b.by0_));
        bboxnode.setAttribute("z0", String.valueOf(b.bz0_));
        bboxnode.setAttribute("x1", String.valueOf(b.bx1_));
        bboxnode.setAttribute("y1", String.valueOf(b.by1_));
        bboxnode.setAttribute("z1", String.valueOf(b.bz1_));
        bricknode.appendChild(bboxnode);
      }

      if (l < lv - 1) {
        imp = WindowManager.getImage(lvImgTitle.get(l + 1));
        int[] newdims = imp.getDimensions();
        imageW = newdims[0];
        imageH = newdims[1];
        imageD = newdims[3];
        xspc = orgxspc * ((double) orgW / (double) imageW);
        yspc = orgyspc * ((double) orgH / (double) imageH);
        zspc = orgzspc * ((double) orgD / (double) imageD);
        bdepth = imp.getBitDepth();
      }
    }

    File newXMLfile = new File(directory + basename + ".vvd");
    writeXML(newXMLfile, doc);

    for (int l = 1; l < lv; l++) {
      imp = WindowManager.getImage(lvImgTitle.get(l));
      imp.changes = false;
      imp.close();
    }
  }
Ejemplo n.º 21
0
  private void writeImages(File outputDir, Array<Page> pages, String packFileName) {
    String imageName = packFileName;
    int dotIndex = imageName.lastIndexOf('.');
    if (dotIndex != -1) imageName = imageName.substring(0, dotIndex);

    int fileIndex = 0;
    for (Page page : pages) {
      int width = page.width, height = page.height;
      int paddingX = settings.paddingX;
      int paddingY = settings.paddingY;
      if (settings.duplicatePadding) {
        paddingX /= 2;
        paddingY /= 2;
      }
      width -= settings.paddingX;
      height -= settings.paddingY;
      if (settings.edgePadding) {
        page.x = paddingX;
        page.y = paddingY;
        width += paddingX * 2;
        height += paddingY * 2;
      }
      if (settings.pot) {
        width = MathUtils.nextPowerOfTwo(width);
        height = MathUtils.nextPowerOfTwo(height);
      }
      width = Math.max(settings.minWidth, width);
      height = Math.max(settings.minHeight, height);

      if (settings.forceSquareOutput) {
        if (width > height) {
          height = width;
        } else {
          width = height;
        }
      }

      File outputFile;
      while (true) {
        outputFile =
            new File(
                outputDir,
                imageName + (fileIndex++ == 0 ? "" : fileIndex) + "." + settings.outputFormat);
        if (!outputFile.exists()) break;
      }
      page.imageName = outputFile.getName();

      BufferedImage canvas =
          new BufferedImage(width, height, getBufferedImageType(settings.format));
      Graphics2D g = (Graphics2D) canvas.getGraphics();

      System.out.println(
          "Writing " + canvas.getWidth() + "x" + canvas.getHeight() + ": " + outputFile);

      for (Rect rect : page.outputRects) {
        BufferedImage image = rect.image;
        int iw = image.getWidth();
        int ih = image.getHeight();
        int rectX = page.x + rect.x, rectY = page.y + page.height - rect.y - rect.height;
        if (settings.duplicatePadding) {
          int amountX = settings.paddingX / 2;
          int amountY = settings.paddingY / 2;
          if (rect.rotated) {
            // Copy corner pixels to fill corners of the padding.
            for (int i = 1; i <= amountX; i++) {
              for (int j = 1; j <= amountY; j++) {
                plot(canvas, rectX - j, rectY + iw - 1 + i, image.getRGB(0, 0));
                plot(canvas, rectX + ih - 1 + j, rectY + iw - 1 + i, image.getRGB(0, ih - 1));
                plot(canvas, rectX - j, rectY - i, image.getRGB(iw - 1, 0));
                plot(canvas, rectX + ih - 1 + j, rectY - i, image.getRGB(iw - 1, ih - 1));
              }
            }
            // Copy edge pixels into padding.
            for (int i = 1; i <= amountY; i++) {
              for (int j = 0; j < iw; j++) {
                plot(canvas, rectX - i, rectY + iw - 1 - j, image.getRGB(j, 0));
                plot(canvas, rectX + ih - 1 + i, rectY + iw - 1 - j, image.getRGB(j, ih - 1));
              }
            }
            for (int i = 1; i <= amountX; i++) {
              for (int j = 0; j < ih; j++) {
                plot(canvas, rectX + j, rectY - i, image.getRGB(iw - 1, j));
                plot(canvas, rectX + j, rectY + iw - 1 + i, image.getRGB(0, j));
              }
            }
          } else {
            // Copy corner pixels to fill corners of the padding.
            for (int i = 1; i <= amountX; i++) {
              for (int j = 1; j <= amountY; j++) {
                canvas.setRGB(rectX - i, rectY - j, image.getRGB(0, 0));
                canvas.setRGB(rectX - i, rectY + ih - 1 + j, image.getRGB(0, ih - 1));
                canvas.setRGB(rectX + iw - 1 + i, rectY - j, image.getRGB(iw - 1, 0));
                canvas.setRGB(rectX + iw - 1 + i, rectY + ih - 1 + j, image.getRGB(iw - 1, ih - 1));
              }
            }
            // Copy edge pixels into padding.
            for (int i = 1; i <= amountY; i++) {
              copy(image, 0, 0, iw, 1, canvas, rectX, rectY - i, rect.rotated);
              copy(image, 0, ih - 1, iw, 1, canvas, rectX, rectY + ih - 1 + i, rect.rotated);
            }
            for (int i = 1; i <= amountX; i++) {
              copy(image, 0, 0, 1, ih, canvas, rectX - i, rectY, rect.rotated);
              copy(image, iw - 1, 0, 1, ih, canvas, rectX + iw - 1 + i, rectY, rect.rotated);
            }
          }
        }
        copy(image, 0, 0, iw, ih, canvas, rectX, rectY, rect.rotated);
        if (settings.debug) {
          g.setColor(Color.magenta);
          g.drawRect(
              rectX,
              rectY,
              rect.width - settings.paddingX - 1,
              rect.height - settings.paddingY - 1);
        }
      }

      if (settings.debug) {
        g.setColor(Color.magenta);
        g.drawRect(0, 0, width - 1, height - 1);
      }

      ImageOutputStream ios = null;
      try {
        if (settings.outputFormat.equalsIgnoreCase("jpg")) {
          BufferedImage newImage =
              new BufferedImage(
                  canvas.getWidth(), canvas.getHeight(), BufferedImage.TYPE_3BYTE_BGR);
          newImage.getGraphics().drawImage(canvas, 0, 0, null);
          canvas = newImage;

          Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpg");
          ImageWriter writer = writers.next();
          ImageWriteParam param = writer.getDefaultWriteParam();
          param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
          param.setCompressionQuality(settings.jpegQuality);
          ios = ImageIO.createImageOutputStream(outputFile);
          writer.setOutput(ios);
          writer.write(null, new IIOImage(canvas, null, null), param);
        } else {
          if (settings.premultiplyAlpha)
            canvas.getColorModel().coerceData(canvas.getRaster(), true);
          ImageIO.write(canvas, "png", outputFile);
        }
      } catch (IOException ex) {
        throw new RuntimeException("Error writing file: " + outputFile, ex);
      } finally {
        if (ios != null) {
          try {
            ios.close();
          } catch (Exception ignored) {
          }
        }
      }
    }
  }
Ejemplo n.º 22
0
  /**
   * Takes the Scene and writes an image file according to the constraints defined by the caller.
   * This returns a BufferedImage of the {@link Scene} even if the file can not be written. This
   * function creates the image for the entire {@link Scene}.
   *
   * @param visibleAreaOnly Eliminates all zoom features. If true, the exported image will be a
   *     created from the visible area of the scene.
   * @param selectedOnly Create an image including only the objects selected on the scene. Note that
   *     this feature requires that the scene is an instance of an ObjectScene since it is the
   *     implementation that allows for object selection.
   * @param quality And integer value between 0-100. This is for JPG images only. Parameter is not
   *     used if an image type other than jpg is selected.
   * @param canvas The {@link WorkareaCanvas} that is to exported.
   * @param createImageMap If true, the necessary steps are taken to setup the sequential call to
   *     getSceneImageMapCoordinates.
   * @return image The raw image that was written to the file.
   * @throws java.io.IOException If for some reason the file cannot be written, an IOExeption will
   *     be thrown.
   */
  public BufferedImage createImage(
      ImageType imageType,
      ZoomType zoomType,
      boolean visibleAreaOnly,
      boolean selectedOnly,
      int quality,
      WorkareaCanvas canvas,
      boolean createImageMap)
      throws IOException {
    // Creates a rectangle with the starting point and the dimensions of the
    // scene seleceted for export
    Rectangle rectangle = canvas.getScene().getClientArea();

    double _scale = scene.getZoomFactor();

    Rectangle sceneRec = scene.getPreferredBounds();
    Rectangle viewRect = scene.getView().getVisibleRect();

    BufferedImage bufferedImage;
    Graphics2D g;
    ArrayList<Widget> hiddenWidgets = new ArrayList<Widget>();

    int _imageWidth = sceneRec.width;
    int _imageHeight = sceneRec.height;

    Set<?> _selectedObjects = null;

    if (selectedOnly) {
      // in order to use getSelectedObject the scene must be an
      // ObjectScene
      if (scene instanceof ObjectScene) {

        ObjectScene gScene = (ObjectScene) scene;
        // hide unselected widget
        HashSet<Object> invisible = new HashSet<Object>();
        invisible.addAll(gScene.getObjects());
        _selectedObjects = gScene.getSelectedObjects();
        invisible.removeAll(_selectedObjects);

        for (Object o : invisible) {
          Widget widget = gScene.findWidget(o);
          if (widget != null && widget.isVisible()) {
            widget.setVisible(false);
            hiddenWidgets.add(widget);
          }
        }
      }
    }

    if (visibleAreaOnly) {
      _imageWidth = viewRect.width;
      _imageHeight = viewRect.height;
    } else {
      switch (zoomType) {
        case CUSTOM_SIZE:
          _imageWidth = rectangle.width;
          _imageHeight = rectangle.height;
          _scale =
              Math.min(
                  (double) rectangle.width / (double) sceneRec.width,
                  (double) rectangle.height / (double) sceneRec.height);
          break;
        case FIT_IN_WINDOW:
          _scale =
              Math.min(
                  (double) viewRect.width / (double) sceneRec.width,
                  (double) viewRect.height / (double) sceneRec.height);
          _imageWidth = (int) ((double) sceneRec.width * _scale);
          _imageHeight = (int) ((double) sceneRec.height * _scale);
          break;
        case CURRENT_ZOOM_LEVEL:
          _imageWidth = (int) (sceneRec.width * scene.getZoomFactor());
          _imageHeight = (int) (sceneRec.height * scene.getZoomFactor());
          break;
        case ACTUAL_SIZE:
          _imageWidth = sceneRec.width;
          _imageHeight = sceneRec.height;
          _scale = 1.0;
          break;
      }
    }

    // Note that the field variable are being set to method local variable.
    // This
    // is for the call to getSceneImageMapCoordinates that will come since
    // createImageMap is true.
    if (createImageMap) {
      this.selectedObjects = _selectedObjects;
      this.imageHeight = _imageHeight;
      this.imageWidth = _imageWidth;
      this.scale = _scale;
    }

    bufferedImage =
        new BufferedImage(rectangle.width, rectangle.height, BufferedImage.TYPE_INT_RGB);
    g = bufferedImage.createGraphics();
    g.setRenderingHint(
        RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    g.scale(_scale, _scale);
    g.setColor(Color.WHITE);
    g.fillRect(rectangle.x, rectangle.y, rectangle.width, rectangle.height);
    scene.paint(g);

    // restore widget visibility
    for (Widget w : hiddenWidgets) {
      w.setVisible(true);
    }

    if (file != null) {
      boolean save = true;

      if (file.exists()) {
        int answer =
            JOptionPane.showConfirmDialog(
                null,
                "This file exists. Do you wish to overwrite the file?",
                "Confirm",
                JOptionPane.YES_NO_OPTION);

        // The user has not pressed YES
        if (answer != 0) {
          save = false;
        }
      }

      if (save) {
        FileImageOutputStream fo = new FileImageOutputStream(file);

        if (imageType == ImageType.JPG) {
          Iterator<?> iter = ImageIO.getImageWritersByFormatName("jpg");
          ImageWriter writer = (ImageWriter) iter.next();

          ImageWriteParam iwp = writer.getDefaultWriteParam();
          iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
          if (quality > 100) {
            quality = 100;
          }
          if (quality < 0) {
            quality = 0;
          }
          iwp.setCompressionQuality(quality / 100);
          writer.setOutput(fo);
          IIOImage image = new IIOImage(bufferedImage, null, null);
          writer.write(null, image, iwp);

          writer.dispose();
        } else {
          ImageIO.write(bufferedImage, "" + imageType, fo);
        }

        fo.flush();
        fo.close();
      }
    }

    return bufferedImage;
  }