/**
   * Return a list of all of the files in this directory. If 'noHiddenFiles' is set to true, then
   * hidden files are omitted.
   *
   * @see java.io.File#list()
   */
  public String[] list(boolean noHiddenFiles) {
    String key = getAbsolutePath() + Boolean.toString(noHiddenFiles);
    String[] result = null;
    if (cacheListings) {
      cleanStaleCacheEntries();
      ListingsResult listingsResult = fileListings.get(key);
      if (listingsResult != null) {
        return listingsResult.listing;
      }
    }
    ArrayList<String> files = new ArrayList<String>();
    if (isURL) {
      try {
        URLConnection c = url.openConnection();
        InputStream is = c.getInputStream();
        boolean foundEnd = false;

        while (!foundEnd) {
          byte[] b = new byte[is.available()];
          is.read(b);
          String s = new String(b, Constants.ENCODING);
          if (s.toLowerCase().indexOf("</html>") != -1) foundEnd = true;

          while (s.indexOf("a href") != -1) {
            int ndx = s.indexOf("a href") + 8;
            int idx = s.indexOf("\"", ndx);
            if (idx < 0) break;
            String f = s.substring(ndx, idx);
            if (files.size() > 0 && f.startsWith("/")) {
              return null;
            }
            s = s.substring(idx + 1);
            if (f.startsWith("?")) continue;
            Location check = new Location(getAbsolutePath(), f);
            if (check.exists() && (!noHiddenFiles || !check.isHidden())) {
              files.add(check.getName());
            }
          }
        }
      } catch (IOException e) {
        LOGGER.trace("Could not retrieve directory listing", e);
        return null;
      }
    } else {
      if (file == null) return null;
      String[] f = file.list();
      if (f == null) return null;
      String path = file.getAbsolutePath();
      for (String name : f) {
        if (!noHiddenFiles || !(name.startsWith(".") || new Location(path, name).isHidden())) {
          files.add(name);
        }
      }
    }
    result = files.toArray(new String[files.size()]);
    if (cacheListings) {
      fileListings.put(key, new ListingsResult(result, System.nanoTime()));
    }
    return result;
  }
  /* @see loci.formats.FormatReader#initFile(String) */
  protected void initFile(String id) throws FormatException, IOException {
    super.initFile(id);
    reader = new ImageReader();

    reader.setMetadataOptions(getMetadataOptions());
    reader.setMetadataFiltered(isMetadataFiltered());
    reader.setOriginalMetadataPopulated(isOriginalMetadataPopulated());
    reader.setNormalized(isNormalized());
    reader.setMetadataStore(getMetadataStore());

    // NB: We need a raw handle on the ZIP data itself, not a ZipHandle.
    IRandomAccess rawHandle = Location.getHandle(id, false, false);
    in = new RandomAccessInputStream(rawHandle, id);

    ZipInputStream zip = new ZipInputStream(in);
    while (true) {
      ZipEntry ze = zip.getNextEntry();
      if (ze == null) break;
      ZipHandle handle = new ZipHandle(id, ze);
      Location.mapFile(ze.getName(), handle);
      mappedFiles.add(ze.getName());
    }

    ZipHandle base = new ZipHandle(id);
    reader.setId(base.getEntryName());

    metadataStore = reader.getMetadataStore();
    core = reader.getCoreMetadata();
    metadata = reader.getGlobalMetadata();

    base.close();
  }
  private void findTIFFs() throws IOException {
    Location baseFile = new Location(currentId).getAbsoluteFile();
    Location parent = baseFile.getParentFile();
    FilePattern pattern = new FilePattern(baseFile);
    String[] tiffs = pattern.getFiles();
    NumericComparator comparator = new NumericComparator();
    Arrays.sort(tiffs, comparator);

    Vector<String> validTIFFs = new Vector<String>();

    for (String tiff : tiffs) {
      if (!new Location(tiff).exists()) {
        String base = tiff.substring(tiff.lastIndexOf(File.separator) + 1);
        base = base.substring(0, base.indexOf("."));
        String suffix = tiff.substring(tiff.lastIndexOf("."));
        while (base.length() < 3) {
          base = "0" + base;
        }
        Location test = new Location(parent, base + suffix);
        if (test.exists()) {
          tiff = test.getAbsolutePath();
        } else continue;
      }
      validTIFFs.add(tiff);
    }

    files = validTIFFs.toArray(new String[validTIFFs.size()]);
  }
 /* @see loci.formats.IFormatReader#isThisType(String, boolean) */
 public boolean isThisType(String name, boolean open) {
   if (!open) return false; // not allowed to touch the file system
   if (name.equals(METADATA)
       || name.endsWith(File.separator + METADATA)
       || name.equals(XML)
       || name.endsWith(File.separator + XML)) {
     final int blockSize = 1048576;
     try {
       RandomAccessInputStream stream = new RandomAccessInputStream(name);
       long length = stream.length();
       String data = stream.readString((int) Math.min(blockSize, length));
       stream.close();
       return length > 0
           && (data.indexOf("Micro-Manager") >= 0 || data.indexOf("micromanager") >= 0);
     } catch (IOException e) {
       return false;
     }
   }
   try {
     Location parent = new Location(name).getAbsoluteFile().getParentFile();
     Location metaFile = new Location(parent, METADATA);
     RandomAccessInputStream s = new RandomAccessInputStream(name);
     boolean validTIFF = isThisType(s);
     s.close();
     return validTIFF && isThisType(metaFile.getAbsolutePath(), open);
   } catch (NullPointerException e) {
   } catch (IOException e) {
   }
   return false;
 }
Exemple #5
0
  private void parseChannelData(Location dir) throws IOException {
    emWave = new int[channelNames.size()];
    exWave = new int[channelNames.size()];
    exposure = new double[channelNames.size()];
    gain = new double[channelNames.size()];
    offset = new double[channelNames.size()];

    for (int c = 0; c < channelNames.size(); c++) {
      Location dyeFile = new Location(dir, channelNames.get(c) + ".dye");
      FileInputStream stream = new FileInputStream(dyeFile.getAbsolutePath());
      IniList dye =
          new IniParser()
              .parseINI(new BufferedReader(new InputStreamReader(stream, Constants.ENCODING)));

      IniTable numerator = dye.getTable("Numerator");
      String em = numerator.get("Emission");
      em = em.substring(0, em.indexOf(" "));
      emWave[c] = Integer.parseInt(em);

      String ex = numerator.get("Excitation");
      ex = ex.substring(0, ex.lastIndexOf(" "));
      if (ex.indexOf(" ") != -1) {
        ex = ex.substring(ex.lastIndexOf(" ") + 1);
      }
      exWave[c] = Integer.parseInt(ex);

      exposure[c] = Double.parseDouble(numerator.get("Exposure"));
      gain[c] = Double.parseDouble(numerator.get("Gain"));
      offset[c] = Double.parseDouble(numerator.get("Offset"));
    }
  }
Exemple #6
0
  private String[][] getTiffs(String dir) {
    Location f = new Location(dir);
    Vector<Vector<String>> files = new Vector<Vector<String>>();

    String[] wells = f.list(true);
    Arrays.sort(wells);

    for (String filename : wells) {
      Location file = new Location(f, filename).getAbsoluteFile();
      if (file.isDirectory() && filename.startsWith("Well ")) {
        String[] list = file.list(true);
        Vector<String> tiffList = new Vector<String>();
        Arrays.sort(list);
        for (String tiff : list) {
          if (tiff.matches(".* - n\\d\\d\\d\\d\\d\\d\\.tif")) {
            tiffList.add(new Location(file, tiff).getAbsolutePath());
          }
        }
        files.add(tiffList);
      }
    }

    String[][] tiffFiles = new String[files.size()][];
    for (int i = 0; i < tiffFiles.length; i++) {
      tiffFiles[i] = files.get(i).toArray(new String[0]);
    }
    return tiffFiles;
  }
 /* @see loci.formats.IFormatReader#close(boolean) */
 public void close(boolean fileOnly) throws IOException {
   super.close(fileOnly);
   if (reader != null) reader.close(fileOnly);
   if (!fileOnly) reader = null;
   for (String name : mappedFiles) {
     IRandomAccess handle = Location.getMappedFile(name);
     Location.mapFile(name, null);
     if (handle != null) {
       handle.close();
     }
   }
   mappedFiles.clear();
 }
 /* @see loci.formats.FormatReader#initFile(String) */
 protected void initFile(String id) throws FormatException, IOException {
   if (!checkSuffix(id, "tif")) {
     Location parent = new Location(id).getAbsoluteFile().getParentFile();
     String[] list = parent.list(true);
     for (String f : list) {
       if (checkSuffix(f, "tif")) {
         String path = new Location(parent, f).getAbsolutePath();
         if (isThisType(path)) {
           id = path;
           break;
         }
       }
     }
   }
   super.initFile(id);
 }
Exemple #9
0
 @DataProvider(name = "wrappers")
 public Object[][] createWrappers() {
   Location.mapId(TEST_FILE, TEST_FILE);
   Object[][] wrappers =
       new Object[][] {
         {new ChannelFiller()},
         {new ChannelMerger()},
         {new ChannelSeparator()},
         {new DimensionSwapper()},
         {new FileStitcher()},
         {new ImageReader()},
         {new MinMaxCalculator()}
       };
   for (int i = 0; i < wrappers.length; i++) {
     IFormatReader reader = (IFormatReader) wrappers[i][0];
     try {
       reader.setId(TEST_FILE);
     } catch (FormatException e) {
       e.printStackTrace();
     } catch (IOException e) {
       e.printStackTrace();
     }
   }
   return wrappers;
 }
Exemple #10
0
  /* @see IFormatHandler#setId(String) */
  public void setId(String id) throws FormatException, IOException {
    try {
      super.setId(id);
    } catch (CMMException e) {
      // strip out all but the first application marker
      // ImageIO isn't too keen on supporting multiple application markers
      // in the same stream, as evidenced by:
      //
      // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6488904

      in = new RandomAccessInputStream(id);
      ByteArrayOutputStream v = new ByteArrayOutputStream();

      byte[] tag = new byte[2];
      in.read(tag);
      v.write(tag);

      in.read(tag);
      int tagValue = DataTools.bytesToShort(tag, false) & 0xffff;
      boolean appNoteFound = false;
      while (tagValue != 0xffdb) {
        if (!appNoteFound || (tagValue < 0xffe0 && tagValue >= 0xfff0)) {
          v.write(tag);

          in.read(tag);
          int len = DataTools.bytesToShort(tag, false) & 0xffff;
          byte[] tagContents = new byte[len - 2];
          in.read(tagContents);
          v.write(tag);
          v.write(tagContents);
        } else {
          in.read(tag);
          int len = DataTools.bytesToShort(tag, false) & 0xffff;
          in.skipBytes(len - 2);
        }

        if (tagValue >= 0xffe0 && tagValue < 0xfff0 && !appNoteFound) {
          appNoteFound = true;
        }
        in.read(tag);
        tagValue = DataTools.bytesToShort(tag, false) & 0xffff;
      }
      v.write(tag);
      byte[] remainder = new byte[(int) (in.length() - in.getFilePointer())];
      in.read(remainder);
      v.write(remainder);

      ByteArrayHandle bytes = new ByteArrayHandle(v.toByteArray());

      Location.mapFile(currentId + ".fixed", bytes);
      super.setId(currentId + ".fixed");
    }
    if (getSizeX() > MAX_SIZE && getSizeY() > MAX_SIZE && !legacyReaderInitialized) {
      close();
      useLegacy = true;
      super.setId(id);
    }
    currentId = id;
  }
 /**
  * Checks that the given id points at a valid data stream.
  *
  * @param id The id string to validate.
  * @throws IOException if the id is not valid.
  */
 public static void checkValidId(String id) throws IOException {
   if (getMappedFile(id) != null) {
     // NB: The id maps directly to an IRandomAccess handle, so is valid. Do
     // not destroy an existing mapped IRandomAccess handle by closing it.
     return;
   }
   // NB: Try to actually open a handle to make sure it is valid. Close it
   // afterward so we don't leave it dangling. The process of doing this will
   // throw IOException if something goes wrong.
   Location.getHandle(id).close();
 }
  private void buildTIFFList(int posIndex) throws FormatException {
    Position p = positions.get(posIndex);
    String parent = new Location(p.metadataFile).getParent();

    LOGGER.info("Finding image file names");

    // find the name of a TIFF file
    p.tiffs = new Vector<String>();

    // build list of TIFF files

    buildTIFFList(posIndex, parent + File.separator + p.baseTiff);

    if (p.tiffs.size() == 0) {
      Vector<String> uniqueZ = new Vector<String>();
      Vector<String> uniqueC = new Vector<String>();
      Vector<String> uniqueT = new Vector<String>();

      Location dir = new Location(p.metadataFile).getAbsoluteFile().getParentFile();
      String[] files = dir.list(true);
      Arrays.sort(files);
      for (String f : files) {
        if (checkSuffix(f, "tif") || checkSuffix(f, "tiff")) {
          String[] blocks = f.split("_");
          if (!uniqueT.contains(blocks[1])) uniqueT.add(blocks[1]);
          if (!uniqueC.contains(blocks[2])) uniqueC.add(blocks[2]);
          if (!uniqueZ.contains(blocks[3])) uniqueZ.add(blocks[3]);

          p.tiffs.add(new Location(dir, f).getAbsolutePath());
        }
      }

      core[posIndex].sizeZ = uniqueZ.size();
      core[posIndex].sizeC = uniqueC.size();
      core[posIndex].sizeT = uniqueT.size();

      if (p.tiffs.size() == 0) {
        throw new FormatException("Could not find TIFF files.");
      }
    }
  }
  /* (non-Javadoc)
   * @see loci.formats.NetCDFService#setFile(java.lang.String)
   */
  public void setFile(String file) throws IOException {
    this.currentFile = file;

    String currentId = Location.getMappedId(currentFile);
    netCDFFile = NetcdfFile.open(currentId);
    root = netCDFFile.getRootGroup();

    attributeList = new Vector<String>();
    variableList = new Vector<String>();
    List<Group> groups = new ArrayList<Group>();
    groups.add(root);
    parseAttributesAndVariables(groups);
  }
  /**
   * Tests whether Bio-Formats is potentially capable of importing the given file IDs. Outputs the
   * IDs it can potentially import, one group per line, with elements of the each group separated by
   * spaces.
   */
  public void testIds(int[] fileIds) throws OmeisException, FormatException, IOException {
    Arrays.sort(fileIds);

    // set up file path mappings
    String[] ids = new String[fileIds.length];
    for (int i = 0; i < fileIds.length; i++) {
      Hashtable fileInfo = getFileInfo(fileIds[i]);
      ids[i] = (String) fileInfo.get("Name");
      String path = getLocalFilePath(fileIds[i]);
      Location.mapId(ids[i], path);
    }

    // check types and groups
    if (http) printHttpResponseHeader();
    boolean[] done = new boolean[fileIds.length];
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < fileIds.length; i++) {
      if (done[i]) continue; // already part of another group
      if (ids[i] == null) continue; // invalid id
      if (!reader.isThisType(ids[i])) continue; // unknown format
      reader.setId(ids[i]);
      String[] files = reader.getUsedFiles();

      if (files == null) continue; // invalid files list
      sb.setLength(0);

      for (int j = files.length - 1; j >= 0; j--) {
        for (int ii = i; ii < fileIds.length; ii++) {
          if (files[j] == null) {
            log("Warning: FileID " + fileIds[ii] + " ('" + ids[ii] + "') has null used file #" + j);
          } else if (files[j].equals(ids[ii])) {
            if (done[ii]) {
              log(
                  "Warning: FileID "
                      + fileIds[ii]
                      + " ('"
                      + ids[ii]
                      + "') already belongs to a group");
            }
            done[ii] = true;
            if (j < files.length - 1) sb.append(" ");
            sb.append(fileIds[ii]);
            break;
          }
        }
      }
      System.out.println(sb.toString());
    }
  }
  /* @see loci.formats.FormatReader#initFile(String) */
  public void initFile(String id) throws FormatException, IOException {
    super.initFile(id);
    tiffReader = new MinimalTiffReader();
    positions = new Vector<Position>();

    LOGGER.info("Reading metadata file");

    // find metadata.txt

    Location file = new Location(currentId).getAbsoluteFile();
    Location parentFile = file.getParentFile();
    String metadataFile = METADATA;
    if (file.exists()) {
      metadataFile = new Location(parentFile, METADATA).getAbsolutePath();

      // look for other positions

      if (parentFile.getName().indexOf("Pos_") >= 0) {
        parentFile = parentFile.getParentFile();
        String[] dirs = parentFile.list(true);
        Arrays.sort(dirs);
        for (String dir : dirs) {
          if (dir.indexOf("Pos_") >= 0) {
            Position pos = new Position();
            Location posDir = new Location(parentFile, dir);
            pos.metadataFile = new Location(posDir, METADATA).getAbsolutePath();
            positions.add(pos);
          }
        }
      } else {
        Position pos = new Position();
        pos.metadataFile = metadataFile;
        positions.add(pos);
      }
    }

    core = new CoreMetadata[positions.size()];

    for (int i = 0; i < positions.size(); i++) {
      core[i] = new CoreMetadata();
      setSeries(i);
      parsePosition(i);
    }
    setSeries(0);

    populateMetadata();
  }
Exemple #16
0
 /* Locate the experiment file given any file in set */
 private String locateExperimentFile(String id) throws FormatException, IOException {
   if (!checkSuffix(id, "exp")) {
     Location parent = new Location(id).getAbsoluteFile().getParentFile();
     if (checkSuffix(id, "tif")) parent = parent.getParentFile();
     Location expFile = new Location(parent, EXPERIMENT_FILE);
     if (expFile.exists()) {
       return expFile.getAbsolutePath();
     }
     throw new FormatException(
         "Could not find " + EXPERIMENT_FILE + " in " + parent.getAbsolutePath());
   }
   return id;
 }
  public String uploadFile(
      final ImportProcessPrx proc,
      final String[] srcFiles,
      final int index,
      final ChecksumProviderFactory cpf,
      TimeEstimator estimator,
      final byte[] buf)
      throws ServerError, IOException {

    final ChecksumProvider cp =
        cpf.getProvider(
            ChecksumAlgorithmMapper.getChecksumType(proc.getImportSettings().checksumAlgorithm));

    final File file = new File(Location.getMappedId(srcFiles[index]));

    try {
      return transfer.transfer(
          new TransferState(file, index, srcFiles.length, proc, this, estimator, cp, buf));
    } catch (Exception e) {
      // Required to bump the error count
      notifyObservers(
          new ErrorHandler.FILE_EXCEPTION(file.getAbsolutePath(), e, srcFiles, "unknown"));
      // The state that we're entering, i.e. exiting upload via error
      notifyObservers(
          new ImportEvent.FILE_UPLOAD_ERROR(
              file.getAbsolutePath(), index, srcFiles.length, null, null, e));
      if (e instanceof RuntimeException) {
        throw (RuntimeException) e;
      } else if (e instanceof ServerError) {
        throw (ServerError) e;
      } else if (e instanceof IOException) {
        throw (IOException) e;
      } else {
        String msg = "Unexpected exception thrown!";
        log.error(msg, e);
        throw new RuntimeException(msg, e);
      }
    }
  }
  /* @see loci.formats.IFormatReader#isThisType(String, boolean) */
  public boolean isThisType(String name, boolean open) {
    if (super.isThisType(name, open)) return true;

    if (!checkSuffix(name, "tif") && open) {
      Location current = new Location(name).getAbsoluteFile();
      Location parent = current.getParentFile();

      String tiff = current.getName();
      int index = tiff.lastIndexOf(".");
      if (index >= 0) {
        tiff = tiff.substring(0, index);
      }
      tiff += ".tif";

      Location tiffFile = new Location(parent, tiff);
      return tiffFile.exists() && isThisType(tiffFile.getAbsolutePath(), open);
    }
    return false;
  }
  /* @see loci.formats.in.BaseTiffReader#initStandardMetadata() */
  protected void initStandardMetadata() throws FormatException, IOException {
    super.initStandardMetadata();

    ifds = tiffParser.getIFDs();
    for (IFD ifd : ifds) {
      tiffParser.fillInIFD(ifd);
    }

    String comment = ifds.get(0).getComment();
    String[] values = comment.split(";");
    for (String v : values) {
      int eq = v.indexOf("=");
      if (eq < 0) continue;
      String key = v.substring(0, eq).trim();
      String value = v.substring(eq + 1).trim();
      addGlobalMeta(key, value);

      if (key.equals("OverlapsXY")) {
        String[] overlapValues = value.split(" ");
        overlaps = new int[ifds.size() * 2];
        for (int i = 0; i < overlapValues.length; i++) {
          overlaps[i] = Integer.parseInt(overlapValues[i]);
        }
      }
    }

    core = new CoreMetadata[ifds.size()];

    for (int i = 0; i < core.length; i++) {
      setSeries(i);
      core[i] = new CoreMetadata();

      if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {}
    }
    setSeries(0);

    // repopulate core metadata

    for (int s = 0; s < core.length; s++) {
      IFD ifd = ifds.get(s);
      PhotoInterp p = ifd.getPhotometricInterpretation();
      int samples = ifd.getSamplesPerPixel();
      core[s].rgb = samples > 1 || p == PhotoInterp.RGB;

      long numTileRows = ifd.getTilesPerColumn() - 1;
      long numTileCols = ifd.getTilesPerRow() - 1;

      int overlapX = overlaps[s * 2];
      int overlapY = overlaps[s * 2 + 1];

      core[s].sizeX = (int) (ifd.getImageWidth() - (numTileCols * overlapX));
      core[s].sizeY = (int) (ifd.getImageLength() - (numTileRows * overlapY));
      core[s].sizeZ = 1;
      core[s].sizeT = 1;
      core[s].sizeC = core[s].rgb ? samples : 1;
      core[s].littleEndian = ifd.isLittleEndian();
      core[s].indexed =
          p == PhotoInterp.RGB_PALETTE
              && (get8BitLookupTable() != null || get16BitLookupTable() != null);
      core[s].imageCount = 1;
      core[s].pixelType = ifd.getPixelType();
      core[s].metadataComplete = true;
      core[s].interleaved = false;
      core[s].falseColor = false;
      core[s].dimensionOrder = "XYCZT";
      core[s].thumbnail = s > 0;
    }

    // look for all of the other associated metadata files

    files = new ArrayList<String>();

    Location baseFile = new Location(currentId).getAbsoluteFile();
    Location parent = baseFile.getParentFile();
    String name = baseFile.getName();
    if (name.indexOf(".") >= 0) {
      name = name.substring(0, name.indexOf(".") + 1);
    }

    roiFile = new Location(parent, name + "ROI").getAbsolutePath();
    roiDrawFile = new Location(parent, name + "ROI-draw").getAbsolutePath();

    String[] list = parent.list(true);
    for (String f : list) {
      if (!f.equals(baseFile.getName())) {
        files.add(new Location(parent, f).getAbsolutePath());
      }
    }
  }
  private byte[] decodeTile(int no, int row, int col) throws FormatException, IOException {
    if (tileMap[getCoreIndex()] == null) {
      return new byte[getTileSize()];
    }

    int[] zct = getZCTCoords(no);
    TileCoordinate t = new TileCoordinate(nDimensions[getCoreIndex()]);
    t.coordinate[0] = col;
    t.coordinate[1] = row;

    for (String dim : dimensionOrdering.keySet()) {
      int index = dimensionOrdering.get(dim) + 2;

      if (dim.equals("Z")) {
        t.coordinate[index] = zct[0];
      } else if (dim.equals("C")) {
        t.coordinate[index] = zct[1];
      } else if (dim.equals("T")) {
        t.coordinate[index] = zct[2];
      }
    }

    Integer index = (Integer) tileMap[getCoreIndex()].get(t);
    if (index == null) {
      return new byte[getTileSize()];
    }

    Long offset = tileOffsets[getCoreIndex()][index];
    RandomAccessInputStream ets = new RandomAccessInputStream(usedFiles[getCoreIndex()]);
    ets.seek(offset);

    CodecOptions options = new CodecOptions();
    options.interleaved = isInterleaved();
    options.littleEndian = isLittleEndian();
    int tileSize = getTileSize();
    if (tileSize == 0) {
      tileSize = tileX[getCoreIndex()] * tileY[getCoreIndex()] * 10;
    }
    options.maxBytes = (int) (offset + tileSize);

    byte[] buf = null;
    long end =
        index < tileOffsets[getCoreIndex()].length - 1
            ? tileOffsets[getCoreIndex()][index + 1]
            : ets.length();

    IFormatReader reader = null;
    String file = null;

    switch (compressionType[getCoreIndex()]) {
      case RAW:
        buf = new byte[tileSize];
        ets.read(buf);
        break;
      case JPEG:
        Codec codec = new JPEGCodec();
        buf = codec.decompress(ets, options);
        break;
      case JPEG_2000:
        codec = new JPEG2000Codec();
        buf = codec.decompress(ets, options);
        break;
      case PNG:
        file = "tile.png";
        reader = new APNGReader();
      case BMP:
        if (reader == null) {
          file = "tile.bmp";
          reader = new BMPReader();
        }

        byte[] b = new byte[(int) (end - offset)];
        ets.read(b);
        Location.mapFile(file, new ByteArrayHandle(b));
        reader.setId(file);
        buf = reader.openBytes(0);
        Location.mapFile(file, null);
        break;
    }

    if (reader != null) {
      reader.close();
    }

    ets.close();
    return buf;
  }
  /* @see loci.formats.FormatReader#initFile(String) */
  protected void initFile(String id) throws FormatException, IOException {
    super.initFile(id);

    if (!checkSuffix(id, "vsi")) {
      Location current = new Location(id).getAbsoluteFile();
      Location parent = current.getParentFile();
      parent = parent.getParentFile();
      Location grandparent = parent.getParentFile();
      String vsi = parent.getName();
      vsi = vsi.substring(1, vsi.length() - 1) + ".vsi";

      Location vsiFile = new Location(grandparent, vsi);
      if (!vsiFile.exists()) {
        throw new FormatException("Could not find .vsi file.");
      } else {
        id = vsiFile.getAbsolutePath();
      }
    }

    parser = new TiffParser(id);
    ifds = parser.getIFDs();

    RandomAccessInputStream vsi = new RandomAccessInputStream(id);
    vsi.order(parser.getStream().isLittleEndian());
    vsi.seek(8);
    readTags(vsi);
    vsi.seek(parser.getStream().getFilePointer());

    vsi.skipBytes(273);

    ArrayList<String> files = new ArrayList<String>();
    Location file = new Location(id).getAbsoluteFile();

    Location dir = file.getParentFile();

    String name = file.getName();
    name = name.substring(0, name.lastIndexOf("."));

    Location pixelsDir = new Location(dir, "_" + name + "_");
    String[] stackDirs = pixelsDir.list(true);
    if (stackDirs != null) {
      for (String f : stackDirs) {
        Location stackDir = new Location(pixelsDir, f);
        String[] pixelsFiles = stackDir.list(true);
        if (pixelsFiles != null) {
          for (String pixelsFile : pixelsFiles) {
            if (checkSuffix(pixelsFile, "ets")) {
              files.add(new Location(stackDir, pixelsFile).getAbsolutePath());
            }
          }
        }
      }
    }
    files.add(file.getAbsolutePath());
    usedFiles = files.toArray(new String[files.size()]);

    core = new CoreMetadata[files.size() - 1 + ifds.size()];

    tileOffsets = new Long[files.size() - 1][];
    rows = new int[files.size() - 1];
    cols = new int[files.size() - 1];
    nDimensions = new int[core.length];

    IFDList exifs = parser.getExifIFDs();

    compressionType = new int[core.length];
    tileX = new int[core.length];
    tileY = new int[core.length];
    tileMap = new HashMap[core.length];

    for (int s = 0; s < core.length; s++) {
      core[s] = new CoreMetadata();
    }

    for (int s = 0; s < core.length; s++) {
      tileMap[s] = new HashMap<TileCoordinate, Integer>();

      if (s == 0 && !hasFlattenedResolutions()) {
        core[s].resolutionCount = ifds.size() + (files.size() == 1 ? 0 : 1);
      }

      if (s < files.size() - 1) {
        setSeries(s);
        parseETSFile(files.get(s), s);

        core[s].littleEndian = compressionType[s] == RAW;
        core[s].interleaved = core[s].rgb;

        if (s == 0 && exifs.size() > 0) {
          IFD exif = exifs.get(0);

          int newX = exif.getIFDIntValue(IFD.PIXEL_X_DIMENSION);
          int newY = exif.getIFDIntValue(IFD.PIXEL_Y_DIMENSION);

          if (getSizeX() > newX || getSizeY() > newY) {
            core[s].sizeX = newX;
            core[s].sizeY = newY;
          }
        }

        setSeries(0);
      } else {
        IFD ifd = ifds.get(s - files.size() + 1);
        PhotoInterp p = ifd.getPhotometricInterpretation();
        int samples = ifd.getSamplesPerPixel();
        core[s].rgb = samples > 1 || p == PhotoInterp.RGB;
        core[s].sizeX = (int) ifd.getImageWidth();
        core[s].sizeY = (int) ifd.getImageLength();
        core[s].sizeZ = 1;
        core[s].sizeT = 1;
        core[s].sizeC = core[s].rgb ? samples : 1;
        core[s].littleEndian = ifd.isLittleEndian();
        core[s].indexed =
            p == PhotoInterp.RGB_PALETTE
                && (get8BitLookupTable() != null || get16BitLookupTable() != null);
        core[s].imageCount = 1;
        core[s].pixelType = ifd.getPixelType();
        core[s].interleaved = false;
        core[s].falseColor = false;
        core[s].thumbnail = s != 0;
      }
      core[s].metadataComplete = true;
      core[s].dimensionOrder = "XYCZT";
    }
    vsi.close();

    MetadataStore store = makeFilterMetadata();
    MetadataTools.populatePixels(store, this);
  }
  /**
   * Attempts to import the given file IDs using Bio-Formats, as a single group. Pixels are saved to
   * the pixels file designated by OMEIS, and an OME-XML metadata block describing the successfully
   * imported data is dumped to standard output.
   */
  public void importIds(int[] fileIds) throws OmeisException, FormatException, IOException {
    boolean doLittle = isLittleEndian();

    Arrays.sort(fileIds);

    // set up file path mappings
    String[] ids = new String[fileIds.length];
    for (int i = 0; i < fileIds.length; i++) {
      Hashtable fileInfo = getFileInfo(fileIds[i]);
      ids[i] = (String) fileInfo.get("Name");
      String path = getLocalFilePath(fileIds[i]);
      Location.mapId(ids[i], path);
    }

    // read file group
    String id = ids[0];
    String path = Location.getMappedId(id);
    if (DEBUG) log("Reading file '" + id + "' --> " + path);

    // verify that all given file IDs were grouped by the reader
    reader.setId(id);
    String[] used = reader.getUsedFiles();
    if (used == null) {
      throw new FormatException("Invalid file list for " + path);
    }
    if (used.length != ids.length) {
      throw new FormatException(
          "File list length mismatch for " + path + ": used=" + a2s(used) + "; ids=" + a2s(ids));
    }

    boolean[] done = new boolean[ids.length];
    int numLeft = ids.length;
    for (int i = 0; i < used.length; i++) {
      for (int j = 0; j < ids.length; j++) {
        if (done[j]) continue;
        if (used[i].equals(ids[j])) {
          done[j] = true;
          numLeft--;
          break;
        }
      }
    }
    if (numLeft > 0) {
      throw new FormatException("File list does not correspond to ID list for " + path);
    }

    int seriesCount = reader.getSeriesCount();

    // get DOM and Pixels elements for the file's OME-XML metadata
    OMENode ome = (OMENode) omexmlMeta.getRoot();
    Document omeDoc = ome.getDOMElement().getOwnerDocument();
    Vector pix = DOMUtil.findElementList("Pixels", omeDoc);
    if (pix.size() != seriesCount) {
      throw new FormatException(
          "Pixels element count ("
              + pix.size()
              + ") does not match series count ("
              + seriesCount
              + ") for '"
              + id
              + "'");
    }
    if (DEBUG) log(seriesCount + " series detected.");

    for (int s = 0; s < seriesCount; s++) {
      reader.setSeries(s);

      // gather pixels information for this series
      int sizeX = reader.getSizeX();
      int sizeY = reader.getSizeY();
      int sizeZ = reader.getSizeZ();
      int sizeC = reader.getSizeC();
      int sizeT = reader.getSizeT();
      int pixelType = reader.getPixelType();
      int bytesPerPixel;
      boolean isSigned, isFloat;
      switch (pixelType) {
        case FormatTools.INT8:
          bytesPerPixel = 1;
          isSigned = true;
          isFloat = false;
          break;
        case FormatTools.UINT8:
          bytesPerPixel = 1;
          isSigned = false;
          isFloat = false;
          break;
        case FormatTools.INT16:
          bytesPerPixel = 2;
          isSigned = true;
          isFloat = false;
          break;
        case FormatTools.UINT16:
          bytesPerPixel = 2;
          isSigned = false;
          isFloat = false;
          break;
        case FormatTools.INT32:
          bytesPerPixel = 4;
          isSigned = true;
          isFloat = false;
          break;
        case FormatTools.UINT32:
          bytesPerPixel = 4;
          isSigned = false;
          isFloat = false;
          break;
        case FormatTools.FLOAT:
          bytesPerPixel = 4;
          isSigned = true;
          isFloat = true;
          break;
        case FormatTools.DOUBLE:
          bytesPerPixel = 8;
          isSigned = true;
          isFloat = true;
          break;
        default:
          throw new FormatException(
              "Unknown pixel type for '" + id + "' series #" + s + ": " + pixelType);
      }
      boolean little = reader.isLittleEndian();
      boolean swap = doLittle != little && bytesPerPixel > 1 && !isFloat;

      // ask OMEIS to allocate new pixels file
      int pixelsId = newPixels(sizeX, sizeY, sizeZ, sizeC, sizeT, bytesPerPixel, isSigned, isFloat);
      String pixelsPath = getLocalPixelsPath(pixelsId);
      if (DEBUG) {
        log("Series #" + s + ": id=" + pixelsId + ", path=" + pixelsPath);
      }

      // write pixels to file
      FileOutputStream out = new FileOutputStream(pixelsPath);
      int imageCount = reader.getImageCount();
      if (DEBUG) {
        log(
            "Processing "
                + imageCount
                + " planes (sizeZ="
                + sizeZ
                + ", sizeC="
                + sizeC
                + ", sizeT="
                + sizeT
                + "): ");
      }
      // OMEIS expects XYZCT order --
      // interleaved RGB files will be handled a bit more slowly due to this
      // ordering (ChannelSeparator must read each plane three times), but
      // caching performed by the OS helps some
      for (int t = 0; t < sizeT; t++) {
        for (int c = 0; c < sizeC; c++) {
          for (int z = 0; z < sizeZ; z++) {
            int ndx = reader.getIndex(z, c, t);
            if (DEBUG) {
              log("Reading plane #" + ndx + ": z=" + z + ", c=" + c + ", t=" + t);
            }
            byte[] plane = reader.openBytes(ndx);
            if (swap) { // swap endianness
              for (int b = 0; b < plane.length; b += bytesPerPixel) {
                for (int k = 0; k < bytesPerPixel / 2; k++) {
                  int i1 = b + k;
                  int i2 = b + bytesPerPixel - k - 1;
                  byte b1 = plane[i1];
                  byte b2 = plane[i2];
                  plane[i1] = b2;
                  plane[i2] = b1;
                }
              }
            }
            out.write(plane);
          }
        }
      }
      out.close();
      if (DEBUG) log("[done]");

      // tell OMEIS we're done
      pixelsId = finishPixels(pixelsId);
      if (DEBUG) log("finishPixels called (new id=" + pixelsId + ")");

      // get SHA1 hash for finished pixels
      String sha1 = getPixelsSHA1(pixelsId);
      if (DEBUG) log("SHA1=" + sha1);

      // inject important extra attributes into proper Pixels element
      Element pixels = (Element) pix.elementAt(s);
      pixels.setAttribute("FileSHA1", sha1);
      pixels.setAttribute("ImageServerID", "" + pixelsId);
      pixels.setAttribute("DimensionOrder", "XYZCT"); // ignored anyway
      String pType = pixels.getAttribute("PixelType");
      if (pType.startsWith("u")) {
        pixels.setAttribute("PixelType", pType.replace('u', 'U'));
      }
      if (DEBUG) log("Pixel attributes injected.");
    }

    reader.close();

    // accumulate XML into buffer
    ByteArrayOutputStream xml = new ByteArrayOutputStream();
    try {
      DOMUtil.writeXML(xml, omeDoc);
    } catch (javax.xml.transform.TransformerException exc) {
      throw new FormatException(exc);
    }

    // output OME-XML to standard output
    xml.close();
    String xmlString = new String(xml.toByteArray());
    if (DEBUG) log(xmlString);
    if (http) printHttpResponseHeader();
    System.out.println(xmlString);
  }
Exemple #23
0
  /* @see loci.formats.FormatReader#initFile(String) */
  protected void initFile(String id) throws FormatException, IOException {
    // make sure we have the experiment file
    id = locateExperimentFile(id);
    super.initFile(id);
    Location dir = new Location(id).getAbsoluteFile().getParentFile();

    for (String file : dir.list(true)) {
      Location f = new Location(dir, file);
      if (!f.isDirectory()) {
        if (checkSuffix(file, META_EXT)) {
          metadataFiles.add(f.getAbsolutePath());
        }
      }
    }

    // parse Experiment metadata
    IniList experiment = readMetaData(id);

    if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
      objective = experiment.getTable("Geometry").get("Name");
      IniTable camera = experiment.getTable("Camera");
      binning = camera.get("BinX") + "x" + camera.get("BinY");

      parseChannelData(dir);

      addGlobalMeta("Objective", objective);
      addGlobalMeta("Camera binning", binning);
    }

    Vector<String> uniqueRows = new Vector<String>();
    Vector<String> uniqueColumns = new Vector<String>();

    for (String well : wellLabels) {
      String row = well.substring(0, 1).trim();
      String column = well.substring(1).trim();

      if (!uniqueRows.contains(row) && row.length() > 0) uniqueRows.add(row);
      if (!uniqueColumns.contains(column) && column.length() > 0) {
        uniqueColumns.add(column);
      }
    }

    int nSlices = getSizeZ() == 0 ? 1 : getSizeZ();
    int nTimepoints = getSizeT();
    int nWells = wellLabels.size();
    int nChannels = getSizeC() == 0 ? channelNames.size() : getSizeC();
    if (nChannels == 0) nChannels = 1;

    tiffs = getTiffs(dir.getAbsolutePath());

    reader = new MinimalTiffReader();
    reader.setId(tiffs[0][0]);

    int sizeX = reader.getSizeX();
    int sizeY = reader.getSizeY();
    int pixelType = reader.getPixelType();
    boolean rgb = reader.isRGB();
    boolean interleaved = reader.isInterleaved();
    boolean indexed = reader.isIndexed();
    boolean littleEndian = reader.isLittleEndian();

    if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
      IniParser parser = new IniParser();
      for (String metadataFile : metadataFiles) {
        String filename = new Location(metadataFile).getName();
        if (!checkSuffix(metadataFile, "txt")) {
          String data = DataTools.readFile(metadataFile);
          IniList ini = parser.parseINI(new BufferedReader(new StringReader(data)));
          HashMap<String, String> h = ini.flattenIntoHashMap();
          for (String key : h.keySet()) {
            addGlobalMeta(filename + " " + key, h.get(key));
          }
        }
      }
    }

    for (int i = 0; i < getSeriesCount(); i++) {
      core[i] = new CoreMetadata();
      core[i].sizeC = nChannels;
      core[i].sizeZ = nSlices;
      core[i].sizeT = nTimepoints;
      core[i].sizeX = sizeX / fieldCols;
      core[i].sizeY = sizeY / fieldRows;
      core[i].pixelType = pixelType;
      core[i].rgb = rgb;
      core[i].interleaved = interleaved;
      core[i].indexed = indexed;
      core[i].littleEndian = littleEndian;
      core[i].dimensionOrder = "XYZTC";
      core[i].imageCount = nSlices * nTimepoints * nChannels;
    }

    MetadataStore store = makeFilterMetadata();
    boolean populatePlanes = getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM;
    MetadataTools.populatePixels(store, this, populatePlanes);

    String plateAcqID = MetadataTools.createLSID("PlateAcquisition", 0, 0);
    store.setPlateAcquisitionID(plateAcqID, 0, 0);
    if (fieldRows * fieldCols > 0) {
      store.setPlateAcquisitionMaximumFieldCount(new PositiveInteger(fieldRows * fieldCols), 0, 0);
    } else {
      LOGGER.warn("Expected positive value for MaximumFieldCount; got {}", fieldRows * fieldCols);
    }

    for (int row = 0; row < wellRows; row++) {
      for (int col = 0; col < wellCols; col++) {
        int index = row * wellCols + col;

        store.setWellID(MetadataTools.createLSID("Well", 0, index), 0, index);
        store.setWellRow(new NonNegativeInteger(row), 0, index);
        store.setWellColumn(new NonNegativeInteger(col), 0, index);
      }
    }

    for (int i = 0; i < getSeriesCount(); i++) {
      int well = i / (fieldRows * fieldCols);
      int field = i % (fieldRows * fieldCols);

      MetadataTools.setDefaultCreationDate(store, tiffs[well][0], i);

      String name = wellLabels.get(well);
      String row = name.substring(0, 1);
      Integer col = Integer.parseInt(name.substring(1));

      int index = (row.charAt(0) - 'A') * wellCols + col - 1;

      String wellSampleID = MetadataTools.createLSID("WellSample", 0, index, field);
      store.setWellSampleID(wellSampleID, 0, index, field);
      store.setWellSampleIndex(new NonNegativeInteger(i), 0, index, field);

      String imageID = MetadataTools.createLSID("Image", i);
      store.setWellSampleImageRef(imageID, 0, index, field);
      store.setImageID(imageID, i);
      store.setImageName(name + " Field #" + (field + 1), i);

      store.setPlateAcquisitionWellSampleRef(wellSampleID, 0, 0, i);
    }

    MetadataLevel level = getMetadataOptions().getMetadataLevel();
    if (level != MetadataLevel.MINIMUM) {
      String instrumentID = MetadataTools.createLSID("Instrument", 0);
      store.setInstrumentID(instrumentID, 0);

      String objectiveID = MetadataTools.createLSID("Objective", 0, 0);
      store.setObjectiveID(objectiveID, 0, 0);
      if (objective != null) {
        String[] tokens = objective.split(" ");
        String mag = tokens[0].replaceAll("[xX]", "");
        String na = null;
        int naIndex = 0;
        for (int i = 0; i < tokens.length; i++) {
          if (tokens[i].equals("NA")) {
            naIndex = i + 1;
            na = tokens[naIndex];
            break;
          }
        }

        Integer magnification = new Integer(mag);
        if (magnification > 0) {
          store.setObjectiveNominalMagnification(new PositiveInteger(magnification), 0, 0);
        } else {
          LOGGER.warn("Expected positive value for NominalMagnification; got {}", magnification);
        }
        if (na != null) {
          na = na.substring(0, 1) + "." + na.substring(1);
          store.setObjectiveLensNA(new Double(na), 0, 0);
        }
        if (naIndex + 1 < tokens.length) {
          store.setObjectiveManufacturer(tokens[naIndex + 1], 0, 0);
        }
      }

      // populate LogicalChannel data
      for (int i = 0; i < getSeriesCount(); i++) {
        store.setImageInstrumentRef(instrumentID, i);
        store.setObjectiveSettingsID(objectiveID, i);

        for (int c = 0; c < getSizeC(); c++) {
          store.setChannelName(channelNames.get(c), i, c);
          if (emWave[c] > 0) {
            store.setChannelEmissionWavelength(new PositiveInteger(emWave[c]), i, c);
          } else {
            LOGGER.warn("Expected positive value for EmissionWavelength; got {}", emWave[c]);
          }
          if (exWave[c] > 0) {
            store.setChannelExcitationWavelength(new PositiveInteger(exWave[c]), i, c);
          } else {
            LOGGER.warn("Expected positive value for ExcitationWavelength; got {}", exWave[c]);
          }

          String detectorID = MetadataTools.createLSID("Detector", 0, c);
          store.setDetectorID(detectorID, 0, c);
          store.setDetectorSettingsID(detectorID, i, c);
          store.setDetectorSettingsGain(gain[c], i, c);
          store.setDetectorSettingsOffset(offset[c], i, c);
          store.setDetectorSettingsBinning(getBinning(binning), i, c);
        }

        long firstPlane = 0;
        for (int p = 0; p < getImageCount(); p++) {
          int[] zct = getZCTCoords(p);
          store.setPlaneExposureTime(exposure[zct[1]], i, p);
          String file = getFilename(i, p);
          if (file != null) {
            long plane = getTimestamp(file);
            if (p == 0) {
              firstPlane = plane;
            }
            double timestamp = (plane - firstPlane) / 1000.0;
            store.setPlaneDeltaT(timestamp, i, p);
          }
        }
      }

      store.setPlateID(MetadataTools.createLSID("Plate", 0), 0);
      store.setPlateRowNamingConvention(getNamingConvention("Letter"), 0);
      store.setPlateColumnNamingConvention(getNamingConvention("Number"), 0);
      store.setPlateName(plateName, 0);
      store.setPlateDescription(plateDescription, 0);

      if (level != MetadataLevel.NO_OVERLAYS) {
        parseROIs(store);
      }
    }
  }
 private static IRandomAccess getHandle(String file) throws IOException {
   return Location.getHandle(file, false, false);
 }
Exemple #25
0
  private IniList readMetaData(String id) throws IOException {
    IniParser parser = new IniParser();
    IniList exp =
        parser.parseINI(
            new BufferedReader(new InputStreamReader(new FileInputStream(id), Constants.ENCODING)));
    IniList plate = null;
    // Read Plate File
    for (String filename : metadataFiles) {
      if (checkSuffix(filename, "plt")) {
        plate =
            parser.parseINI(
                new BufferedReader(
                    new InputStreamReader(new FileInputStream(filename), Constants.ENCODING)));
      } else if (filename.endsWith("RoiSummary.txt")) {
        roiFile = filename;
        if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
          RandomAccessInputStream s = new RandomAccessInputStream(filename);
          String line = s.readLine().trim();
          while (!line.endsWith(".adf\"")) {
            line = s.readLine().trim();
          }
          plateName = line.substring(line.indexOf(":")).trim();
          plateName = plateName.replace('/', File.separatorChar);
          plateName = plateName.replace('\\', File.separatorChar);
          for (int i = 0; i < 3; i++) {
            plateName = plateName.substring(0, plateName.lastIndexOf(File.separator));
          }
          plateName = plateName.substring(plateName.lastIndexOf(File.separator) + 1);

          s.close();
        }
      }
    }
    if (plate == null) throw new IOException("No Plate File");

    IniTable plateType = plate.getTable("PlateType");

    if (plateName == null) {
      plateName = plateType.get("Brand");
    }
    plateDescription = plateType.get("Brand") + " " + plateType.get("Description");

    int nWells = Integer.parseInt(plateType.get("Wells"));
    if (nWells == 96) {
      wellRows = 8;
      wellCols = 12;
    } else if (nWells == 384) {
      wellRows = 16;
      wellCols = 24;
    }

    Location dir = new Location(id).getAbsoluteFile().getParentFile();
    String[] wellList = dir.list();
    Arrays.sort(wellList);
    for (String filename : wellList) {
      if (filename.startsWith("Well ")) {
        wellLabels.add(filename.split("\\s|\\.")[1]);
      }
    }

    IniTable imageTable = exp.getTable("Image");
    boolean montage = imageTable.get("Montaged").equals("1");
    if (montage) {
      fieldRows = Integer.parseInt(imageTable.get("TilesY"));
      fieldCols = Integer.parseInt(imageTable.get("TilesX"));
    } else {
      fieldRows = 1;
      fieldCols = 1;
    }

    core = new CoreMetadata[wellLabels.size() * fieldRows * fieldCols];

    core[0] = new CoreMetadata();

    // Hack for current testing/development purposes
    // Not all channels have the same Z!!! How to handle???
    // FIXME FIXME FIXME
    core[0].sizeZ = 1;
    // FIXME FIXME FIXME
    // END OF HACK

    core[0].sizeC = Integer.parseInt(exp.getTable("General").get("Dyes"));
    core[0].bitsPerPixel = Integer.parseInt(exp.getTable("Camera").get("BitdepthUsed"));

    IniTable dyeTable = exp.getTable("Dyes");
    for (int i = 1; i <= getSizeC(); i++) {
      channelNames.add(dyeTable.get(Integer.toString(i)));
    }

    // Count Images
    core[0].sizeT = 0;
    Location well = new Location(dir.getAbsolutePath(), "Well " + wellLabels.get(1));
    for (String channelName : channelNames) {
      int timepoints = 0;
      for (String filename : well.list()) {
        if (filename.startsWith(channelName) && filename.endsWith(".tif")) {
          timepoints++;
        }
      }
      if (timepoints > getSizeT()) {
        core[0].sizeT = timepoints;
      }
    }

    return exp;
  }
  private void populateMetadata() throws FormatException, IOException {
    MetadataStore store = makeFilterMetadata();
    MetadataTools.populatePixels(store, this, true);

    String instrumentID = MetadataTools.createLSID("Instrument", 0);
    store.setInstrumentID(instrumentID, 0);

    for (int i = 0; i < positions.size(); i++) {
      Position p = positions.get(i);
      if (p.time != null) {
        String date = DateTools.formatDate(p.time, DATE_FORMAT);
        if (date != null) {
          store.setImageAcquisitionDate(new Timestamp(date), i);
        }
      }

      if (positions.size() > 1) {
        Location parent = new Location(p.metadataFile).getParentFile();
        store.setImageName(parent.getName(), i);
      }

      if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
        store.setImageDescription(p.comment, i);

        // link Instrument and Image
        store.setImageInstrumentRef(instrumentID, i);

        for (int c = 0; c < p.channels.length; c++) {
          store.setChannelName(p.channels[c], i, c);
        }

        if (p.pixelSize != null && p.pixelSize > 0) {
          store.setPixelsPhysicalSizeX(new PositiveFloat(p.pixelSize), i);
          store.setPixelsPhysicalSizeY(new PositiveFloat(p.pixelSize), i);
        } else {
          LOGGER.warn("Expected positive value for PhysicalSizeX; got {}", p.pixelSize);
        }
        if (p.sliceThickness != null && p.sliceThickness > 0) {
          store.setPixelsPhysicalSizeZ(new PositiveFloat(p.sliceThickness), i);
        } else {
          LOGGER.warn("Expected positive value for PhysicalSizeZ; got {}", p.sliceThickness);
        }

        int nextStamp = 0;
        for (int q = 0; q < getImageCount(); q++) {
          store.setPlaneExposureTime(p.exposureTime, i, q);
          String tiff = positions.get(getSeries()).getFile(q);
          if (tiff != null && new Location(tiff).exists() && nextStamp < p.timestamps.length) {
            store.setPlaneDeltaT(p.timestamps[nextStamp++], i, q);
          }
        }

        String serialNumber = p.detectorID;
        p.detectorID = MetadataTools.createLSID("Detector", 0, i);

        for (int c = 0; c < p.channels.length; c++) {
          store.setDetectorSettingsBinning(getBinning(p.binning), i, c);
          store.setDetectorSettingsGain(new Double(p.gain), i, c);
          if (c < p.voltage.size()) {
            store.setDetectorSettingsVoltage(p.voltage.get(c), i, c);
          }
          store.setDetectorSettingsID(p.detectorID, i, c);
        }

        store.setDetectorID(p.detectorID, 0, i);
        if (p.detectorModel != null) {
          store.setDetectorModel(p.detectorModel, 0, i);
        }

        if (serialNumber != null) {
          store.setDetectorSerialNumber(serialNumber, 0, i);
        }

        if (p.detectorManufacturer != null) {
          store.setDetectorManufacturer(p.detectorManufacturer, 0, i);
        }

        if (p.cameraMode == null) p.cameraMode = "Other";
        store.setDetectorType(getDetectorType(p.cameraMode), 0, i);
        store.setImagingEnvironmentTemperature(p.temperature, i);
      }
    }
  }
 public Location(Location parent, String child) {
   this(parent.getAbsolutePath(), child);
 }
  public static void main(String[] args)
      throws DependencyException, FormatException, IOException, ServiceException {
    if (args.length < 1) {
      System.out.println("Please specify a (small) image file.");
      System.exit(1);
    }
    String path = args[0];

    // read in entire file
    System.out.println("Reading file into memory from disk...");
    File inputFile = new File(path);
    int fileSize = (int) inputFile.length();
    DataInputStream in = new DataInputStream(new FileInputStream(inputFile));
    byte[] inBytes = new byte[fileSize];
    in.readFully(inBytes);
    System.out.println(fileSize + " bytes read.");

    // determine input file suffix
    String fileName = inputFile.getName();
    int dot = fileName.lastIndexOf(".");
    String suffix = dot < 0 ? "" : fileName.substring(dot);

    // map input id string to input byte array
    String inId = "inBytes" + suffix;
    Location.mapFile(inId, new ByteArrayHandle(inBytes));

    // read data from byte array using ImageReader
    System.out.println();
    System.out.println("Reading image data from memory...");

    ServiceFactory factory = new ServiceFactory();
    OMEXMLService service = factory.getInstance(OMEXMLService.class);
    IMetadata omeMeta = service.createOMEXMLMetadata();

    ImageReader reader = new ImageReader();
    reader.setMetadataStore(omeMeta);
    reader.setId(inId);
    int seriesCount = reader.getSeriesCount();
    int imageCount = reader.getImageCount();
    int sizeX = reader.getSizeX();
    int sizeY = reader.getSizeY();
    int sizeZ = reader.getSizeZ();
    int sizeC = reader.getSizeC();
    int sizeT = reader.getSizeT();

    // output some details
    System.out.println("Series count: " + seriesCount);
    System.out.println("First series:");
    System.out.println("\tImage count = " + imageCount);
    System.out.println("\tSizeX = " + sizeX);
    System.out.println("\tSizeY = " + sizeY);
    System.out.println("\tSizeZ = " + sizeZ);
    System.out.println("\tSizeC = " + sizeC);
    System.out.println("\tSizeT = " + sizeT);

    // map output id string to output byte array
    String outId = fileName + ".ome.tif";
    ByteArrayHandle outputFile = new ByteArrayHandle();
    Location.mapFile(outId, outputFile);

    // write data to byte array using ImageWriter
    System.out.println();
    System.out.print("Writing planes to destination in memory: ");
    ImageWriter writer = new ImageWriter();
    writer.setMetadataRetrieve(omeMeta);
    writer.setId(outId);

    byte[] plane = null;
    for (int i = 0; i < imageCount; i++) {
      if (plane == null) {
        // allow reader to allocate a new byte array
        plane = reader.openBytes(i);
      } else {
        // reuse previously allocated byte array
        reader.openBytes(i, plane);
      }
      writer.saveBytes(i, plane);
      System.out.print(".");
    }
    reader.close();
    writer.close();
    System.out.println();

    byte[] outBytes = outputFile.getBytes();
    outputFile.close();

    // flush output byte array to disk
    System.out.println();
    System.out.println("Flushing image data to disk...");
    File outFile = new File(fileName + ".ome.tif");
    DataOutputStream out = new DataOutputStream(new FileOutputStream(outFile));
    out.write(outBytes);
    out.close();
  }
Exemple #29
0
 /* @see IFormatReader#close(boolean) */
 public void close(boolean fileOnly) throws IOException {
   super.close(fileOnly);
   Location.mapId(currentId, null);
 }