Ejemplo n.º 1
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);
  }
Ejemplo n.º 2
0
 public void saveView(String filename) {
   BoundingSphere bs = _ipg.getBoundingSphere(true);
   Vector3 tvec = _view.getTranslate();
   try {
     FileWriter fw = new FileWriter(filename);
     PrintWriter out = new PrintWriter(fw);
     out.println(bs.getRadius());
     Point3 center = bs.getCenter();
     out.printf("%f %f %f \n", center.x, center.y, center.z);
     out.println(_view.getAzimuth());
     out.println(_view.getElevation());
     out.println(_view.getScale());
     out.printf("%f %f %f \n", tvec.x, tvec.y, tvec.z);
     Iterator<ImagePanel> itr = _ipg.getImagePanels();
     while (itr.hasNext()) {
       ImagePanel ip = itr.next();
       AxisAlignedFrame aaf = ip.getFrame();
       Point3 min = aaf.getCornerMin();
       Point3 max = aaf.getCornerMax();
       out.printf("%f %f %f %f %f %f\n", min.x, min.y, min.z, max.x, max.y, max.z);
     }
     out.println(_pmax);
     out.println(_color.getCode());
     out.close();
   } catch (Exception e) {
     System.out.println(e);
   }
 }
Ejemplo n.º 3
0
  /**
   * Gets a list of <code>IIOImage</code> objects for an image file.
   *
   * @param imageFile input image file. It can be any of the supported formats, including TIFF,
   *     JPEG, GIF, PNG, BMP, JPEG, and PDF if GPL Ghostscript is installed
   * @return a list of <code>IIOImage</code> objects
   * @throws Exception
   */
  public static List<IIOImage> getIIOImageList(File imageFile) throws IOException {
    File workingTiffFile = null;

    ImageReader reader = null;
    ImageInputStream iis = null;

    try {
      // convert PDF to TIFF
      if (imageFile.getName().toLowerCase().endsWith(".pdf")) {
        workingTiffFile = PdfUtilities.convertPdf2Tiff(imageFile);
        imageFile = workingTiffFile;
      }

      List<IIOImage> iioImageList = new ArrayList<IIOImage>();

      String imageFileName = imageFile.getName();
      String imageFormat = imageFileName.substring(imageFileName.lastIndexOf('.') + 1);
      if (imageFormat.matches("(pbm|pgm|ppm)")) {
        imageFormat = "pnm";
      } else if (imageFormat.equals("jp2")) {
        imageFormat = "jpeg2000";
      }
      Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(imageFormat);
      reader = readers.next();

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

      iis = ImageIO.createImageInputStream(imageFile);
      reader.setInput(iis);

      int imageTotal = reader.getNumImages(true);

      for (int i = 0; i < imageTotal; i++) {
        //                IIOImage oimage = new IIOImage(reader.read(i), null,
        // reader.getImageMetadata(i));
        IIOImage oimage = reader.readAll(i, reader.getDefaultReadParam());
        iioImageList.add(oimage);
      }

      return iioImageList;
    } finally {
      try {
        if (iis != null) {
          iis.close();
        }
        if (reader != null) {
          reader.dispose();
        }
      } catch (Exception e) {
        // ignore
      }
      if (workingTiffFile != null && workingTiffFile.exists()) {
        workingTiffFile.delete();
      }
    }
  }
Ejemplo n.º 4
0
 public Iterator getAttachments(Iterator iter) {
   while (iter.hasNext()) {
     Object obj = iter.next();
     if (!(obj instanceof AttachmentPart)) {
       return null;
     }
   }
   return iter;
 }
 /** highlight a route (maybe to show it's in use...) */
 public void highlightRoute(String src, String dst) {
   Iterator i = rows.iterator();
   while (i.hasNext()) {
     Map temp = (Map) i.next();
     if (temp.get("Address").equals(dst) && temp.get("Pivot").equals(src)) {
       temp.put("Active", Boolean.TRUE);
     }
   }
 }
Ejemplo n.º 6
0
  public void loadView(String filename) {
    Point3 point;
    Vector3 tvec;
    double radius;
    double azimuth;
    double elevation;
    double scale;
    double x, y, z;
    double vx, vy, vz;

    try {
      if (_ipg == null) throw new Exception("Must load a cube first!");
      Scanner s = new Scanner(new File(filename));
      radius = s.nextDouble();
      x = s.nextDouble();
      y = s.nextDouble();
      z = s.nextDouble();
      point = new Point3(x, y, z);
      azimuth = s.nextDouble();
      elevation = s.nextDouble();
      scale = s.nextDouble();
      vx = s.nextDouble();
      vy = s.nextDouble();
      vz = s.nextDouble();
      tvec = new Vector3(vx, vy, vz);
      Iterator<ImagePanel> itr = _ipg.getImagePanels();
      while (itr.hasNext()) {
        ImagePanel ip = itr.next();
        AxisAlignedFrame aaf = ip.getFrame();
        double lx = s.nextDouble();
        double ly = s.nextDouble();
        double lz = s.nextDouble();
        double mx = s.nextDouble();
        double my = s.nextDouble();
        double mz = s.nextDouble();

        Point3 min = new Point3(lx, ly, lz);
        Point3 max = new Point3(mx, my, mz);
        aaf.setCorners(min, max);
      }
      _pmax = s.nextFloat();
      int code = s.nextInt();
      _color = ColorList.getMatch(code);
      setColorMap();
      _view.setWorldSphere(new BoundingSphere(point, radius));
      _view.setTranslate(tvec);
      _view.setAzimuth(azimuth);
      _view.setElevation(elevation);
      _view.setScale(scale);
      _ipg.setPercentiles(_pmin, _pmax);

    } catch (Exception e) {
      System.out.println("Failed to load view point!");
      System.out.println(e);
    }
  }
 /** show the meterpreter routes . :) */
 public void setRoutes(Route[] routes) {
   Iterator i = rows.iterator();
   while (i.hasNext()) {
     Map temp = (Map) i.next();
     for (int x = 0; x < routes.length; x++) {
       Route r = routes[x];
       if (r.shouldRoute(temp.get("Address") + "")) temp.put("Pivot", r.getGateway());
     }
   }
 }
  public void tabRemoveHighlight(int tabIndex) {
    Iterator<Integer> highlightedIter = highlightedTabs.iterator();

    while (highlightedIter.hasNext()) {
      if (highlightedIter.next().intValue() == tabIndex) {
        highlightedIter.remove();
        break;
      }
    }
  }
    @Override
    public void actionPerformed(ActionEvent e) {
      if (fc == null) {
        fc = new IDEFileChooser();
        fc.setFileView(new IDEFileView());
        fc.setAcceptAllFileFilterUsed(false);
        fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
        fc.setMultiSelectionEnabled(false);
        fc.setDialogTitle(
            messagesBundle.getString("ImageViewerPanelSaveAction.Choose_filename_to_save_4"));

        //$NON-NLS-1$

        // prepare file filters
        IIORegistry theRegistry = IIORegistry.getDefaultInstance();
        Iterator it = theRegistry.getServiceProviders(ImageWriterSpi.class, false);
        while (it.hasNext()) {
          ImageWriterSpi writer = (ImageWriterSpi) it.next();
          if ((imageType == BufferedImage.TYPE_INT_ARGB
                  || imageType == BufferedImage.TYPE_INT_ARGB_PRE)
              && "JPEG".equals(writer.getFormatNames()[0].toUpperCase())) continue;
          ImageWriterSpiFileFilter ff = new ImageWriterSpiFileFilter(writer);
          fc.addChoosableFileFilter(ff);
        }
      }

      if (fc.showSaveDialog(viewerPanel) == JFileChooser.APPROVE_OPTION) {
        File selectedFile = fc.getSelectedFile();

        if (selectedFile != null) {
          String fileName = selectedFile.getAbsolutePath();
          ImageWriterSpiFileFilter ff = (ImageWriterSpiFileFilter) fc.getFileFilter();
          if (!ff.hasCorrectSuffix(fileName)) fileName = ff.addSuffix(fileName);
          selectedFile = new File(fileName);
          if (selectedFile.exists()) {
            String message =
                MessageFormat.format(
                    messagesBundle.getString("ImageViewerPanelSaveAction.Overwrite_question_5"),
                    //$NON-NLS-1$
                    fileName);
            if (JOptionPane.NO_OPTION
                == JOptionPane.showConfirmDialog(
                    viewerPanel,
                    message,
                    messagesBundle.getString("ImageViewerPanelSaveAction.Warning_6"),
                    //$NON-NLS-1$
                    JOptionPane.YES_NO_OPTION,
                    JOptionPane.WARNING_MESSAGE)) return;
          }
          writeToFile(selectedFile, ff);
        }
      }
    }
Ejemplo n.º 10
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;
  }
Ejemplo n.º 11
0
  /** Print it! */
  public String printClusters(Cluster clustering, float threshold, HTMLFile f) {
    int maxSize = 0;

    ArrayList<Cluster> clusters = getClusters(clustering, threshold);

    for (Iterator<Cluster> i = clusters.iterator(); i.hasNext(); ) {
      Cluster cluster = i.next();
      if (cluster.size() > maxSize) maxSize = cluster.size();
    }

    TreeSet<Cluster> sorted = new TreeSet<Cluster>(clusters);
    clusters = null;

    // Now print them:
    return outputClustering(f, sorted, maxSize);
  }
Ejemplo n.º 12
0
 public AttachmentPart getAttachment(java.net.URI ref, Iterator iter) {
   if (iter == null || ref == null) {
     System.err.println("getAttachment: null Iterator for AttachmentPart");
     return null;
   }
   while (iter.hasNext()) {
     AttachmentPart tempAttachment = (AttachmentPart) iter.next();
     if (ref.isOpaque() && ref.getScheme().equals("cid")) {
       String refId = ref.getSchemeSpecificPart();
       String cId = tempAttachment.getContentId();
       if (cId.equals("<" + refId + ">") || cId.equals(refId)) {
         return tempAttachment;
       }
     }
   }
   return null;
 }
Ejemplo n.º 13
0
  public static byte[] getImageBytes(Image image, String type) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    BufferedImage bufImage = convertToBufferedImage(image);
    ImageWriter writer = null;
    Iterator i = ImageIO.getImageWritersByMIMEType(type);
    if (i.hasNext()) {
      writer = (ImageWriter) i.next();
    }
    if (writer != null) {
      ImageOutputStream stream = null;
      stream = ImageIO.createImageOutputStream(baos);
      writer.setOutput(stream);
      writer.write(bufImage);
      stream.close();
      return baos.toByteArray();
    }
    return null;
  }
Ejemplo n.º 14
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;
  }
  public void end() {
    final int[] selected = table.getSelectedRows();

    model.clear(rows.size());
    Iterator i = rows.iterator();
    while (i.hasNext()) {
      model.addEntry((Map) i.next());
    }
    rows.clear();

    if (SwingUtilities.isEventDispatchThread()) {
      SwingUtilities.invokeLater(
          new Runnable() {
            public void run() {
              model.fireListeners();
              fixSelection(selected);
            }
          });
    } else {
      model.fireListeners();
      fixSelection(selected);
    }
  }
Ejemplo n.º 16
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();
  }
Ejemplo n.º 17
0
  public boolean compareImages(Image image1, Image image2, Rectangle rect, String attach) {
    if (image1 == null || image2 == null) return false;

    boolean matched = false;

    Iterator iter1 = handlePixels(image1, rect);
    Iterator iter2 = handlePixels(image2, rect);

    while (iter1.hasNext() && iter2.hasNext()) {
      Pixel pixel = (Pixel) iter1.next();
      if (pixel.equals((Pixel) iter2.next())) {
        matched = true;
      } else {
        matched = false;
      }
    }
    if (matched) return true;
    return false;
  }
Ejemplo n.º 18
0
  private void load_snap_from_xml(Element snap, StructureCollection structs, LinkedList tempList)
      throws VisualizerLoadException {
    Iterator iterator = snap.getChildren().iterator();

    if (!iterator.hasNext()) throw new VisualizerLoadException("Ran out of elements");

    structs.loadTitle((Element) (iterator.next()), tempList, this);
    structs.calcDimsAndStartPts(tempList, this);

    if (!iterator.hasNext()) return;
    Element child = (Element) iterator.next();

    if (child.getName().compareTo("doc_url") == 0) {
      // load the doc_url
      add_a_documentation_URL(child.getText().trim());
      if (!iterator.hasNext()) return;
      child = (Element) iterator.next();
    }

    if (child.getName().compareTo("pseudocode_url") == 0) {
      // load the psuedocode_url
      add_a_pseudocode_URL(child.getText().trim());
      if (!iterator.hasNext()) return;
      child = (Element) iterator.next();
    }

    if (child.getName().compareTo("audio_text") == 0) {
      // load the psuedocode_url
      add_audio_text(child.getText().trim());
      if (!iterator.hasNext()) return;
      child = (Element) iterator.next();
    }

    // create & load the individual structures, hooking them into the StructureCollection.
    // linespernode : calculate it at end of loadStructure call
    while (child.getName().compareTo("question_ref") != 0) {
      StructureType child_struct = assignStructureType(child);
      child_struct.loadStructure(child, tempList, this);
      structs.addChild(child_struct);

      if (!iterator.hasNext()) return;
      child = (Element) iterator.next();
    }

    if (child.getName().compareTo("question_ref") == 0) {
      // set up question ref
      add_a_question_xml(child.getAttributeValue("ref"));
    } else
      // should never happen
      throw new VisualizerLoadException(
          "Expected question_ref element, but found " + child.getName());

    if (iterator.hasNext()) {
      child = (Element) iterator.next();
      throw new VisualizerLoadException(
          "Found " + child.getName() + " when expecting end of snap.");
    }
  } // load_snap_from_xml
Ejemplo n.º 19
0
  /** This method returns the distribution HTML code as a string */
  private String outputClustering(HTMLFile f, Collection<Cluster> allClusters, int maxSize) {
    int[] distribution = new int[maxSize + 1];
    int max = 0;
    for (int i = 0; i <= maxSize; i++) distribution[i] = 0;

    // Now output the clustering:
    f.println("<TABLE CELLPADDING=2 CELLSPACING=2>");

    f.println(
        "<TR><TH ALIGN=center BGCOLOR=#8080ff>"
            + msg.getString("Clusters.Cluster_number")
            + "<TH ALIGN=center BGCOLOR=#8080ff>"
            + msg.getString("Clusters.Size")
            + "<TH ALIGN=center BGCOLOR=#8080ff>"
            + msg.getString("Clusters.Threshold")
            + "<TH ALIGN=center BGCOLOR=#8080ff>"
            + msg.getString("Clusters.Cluster_members")
            + "<TH ALIGN=center BGCOLOR=#8080ff>"
            + msg.getString("Clusters.Most_frequent_words")
            + "</TR>");
    Iterator<Cluster> clusterI = allClusters.iterator();
    for (int i = 1; clusterI.hasNext(); i++) {
      Cluster cluster = clusterI.next();
      if (max < ++distribution[cluster.size()]) max = distribution[cluster.size()];

      // no singleton clusters
      if (cluster.size() == 1) continue;

      f.print(
          "<TR><TD ALIGN=center BGCOLOR=#8080ff>"
              + i
              + "<TD ALIGN=center BGCOLOR=#c0c0ff>"
              + cluster.size()
              + "<TD ALIGN=center BGCOLOR=#c0c0ff>"
              + cluster.getSimilarity()
              + "<TD ALIGN=left BGCOLOR=#c0c0ff>");

      // sort names
      TreeSet<Submission> sortedSubmissions = new TreeSet<Submission>();
      for (int x = 0; x < cluster.size(); x++) {
        sortedSubmissions.add(submissions.elementAt(cluster.getSubmissionAt(x)));
      }

      for (Iterator<Submission> iter = sortedSubmissions.iterator(); iter.hasNext(); ) {
        Submission sub = iter.next();
        int index = submissions.indexOf(sub);
        f.print("<A HREF=\"submission" + index + ".html\">" + sub.name + "</A>");
        if (iter.hasNext()) f.print(", ");
        neededSubmissions.add(sub); // write files for these.
      }

      if (this.program.get_language() instanceof jplag.text.Language) {
        f.println(
            "<TD ALIGN=left BGCOLOR=#c0c0ff>"
                + ThemeGenerator.generateThemes(
                    sortedSubmissions, this.program.get_themewords(), true, this.program));
      } else {
        f.println("<TD ALIGN=left BGCOLOR=#c0c0ff>-");
      }

      f.println("</TR>");
    }
    f.println("</TABLE>\n<P>\n");

    f.println("<H5>" + msg.getString("Clusters.Distribution_of_cluster_size") + ":</H5>");

    String text;
    text = "<TABLE CELLPADDING=1 CELLSPACING=1>\n";
    text +=
        "<TR><TH ALIGN=center BGCOLOR=#8080ff>"
            + msg.getString("Clusters.Cluster_size")
            + "<TH ALIGN=center BGCOLOR=#8080ff>"
            + msg.getString("Clusters.Number_of_clusters")
            + "<TH ALIGN=center BGCOLOR=#8080ff>.</TR>\n";
    for (int i = 0; i <= maxSize; i++) {
      if (distribution[i] == 0) continue;
      text +=
          "<TR><TD ALIGN=center BGCOLOR=#c0c0ff>"
              + i
              + "<TD ALIGN=right BGCOLOR=#c0c0ff>"
              + distribution[i]
              + "<TD BGCOLOR=#c0c0ff>\n";
      for (int j = (distribution[i] * barLength / max); j > 0; j--) text += ("#");
      if (distribution[i] * barLength / max == 0) {
        if (distribution[i] == 0) text += (".");
        else text += ("#");
      }
      text += ("</TR>\n");
    }
    text += ("</TABLE>\n");

    f.print(text);
    return text;
  }
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();
    }
  }