Search in sources :

Example 26 with ImageReader

use of loci.formats.ImageReader in project bioformats by openmicroscopy.

the class WritePrecompressedPlanes method main.

public static void main(String[] args) throws FormatException, IOException {
    // print usage if no args specified
    if (args.length == 0) {
        System.out.println("Usage: java WritePrecompressedPlanes " + "[input file 1] ... [input file n] [output file]");
        System.exit(0);
    }
    // first n - 1 args are the input files
    String[] inputFiles = new String[args.length - 1];
    System.arraycopy(args, 0, inputFiles, 0, inputFiles.length);
    // last arg is the output file
    String outputFile = args[args.length - 1];
    // open up one of the input files so that we can read the metadata
    // this assumes that the dimensions of the input files are the same
    ImageReader reader = new ImageReader();
    reader.setId(inputFiles[0]);
    int pixelType = reader.getPixelType();
    // write the pixel data to the output file
    RandomAccessOutputStream out = new RandomAccessOutputStream(outputFile);
    TiffSaver saver = new TiffSaver(out, outputFile);
    saver.setWritingSequentially(true);
    saver.setLittleEndian(reader.isLittleEndian());
    saver.setBigTiff(false);
    saver.writeHeader();
    for (int i = 0; i < inputFiles.length; i++) {
        RandomAccessInputStream in = new RandomAccessInputStream(inputFiles[i]);
        byte[] buf = new byte[(int) in.length()];
        in.readFully(buf);
        in.close();
        IFD ifd = new IFD();
        ifd.put(IFD.IMAGE_WIDTH, reader.getSizeX());
        ifd.put(IFD.IMAGE_LENGTH, reader.getSizeY());
        ifd.put(IFD.LITTLE_ENDIAN, reader.isLittleEndian());
        ifd.put(IFD.SAMPLE_FORMAT, FormatTools.isSigned(pixelType) ? 2 : FormatTools.isFloatingPoint(pixelType) ? 3 : 1);
        ifd.put(IFD.PLANAR_CONFIGURATION, 1);
        ifd.put(IFD.REUSE, out.length());
        out.seek(out.length());
        // this is very important
        // the data is already compressed in a single chunk, so setting the
        // number of rows per strip to something smaller than the full height
        // will require us to re-compress the data
        ifd.put(IFD.ROWS_PER_STRIP, reader.getSizeY());
        saver.writeImage(buf, ifd, i, pixelType, 0, 0, reader.getSizeX(), reader.getSizeY(), i == inputFiles.length - 1, reader.getRGBChannelCount(), true);
    }
    reader.close();
    out.close();
    // reset the TIFF file's compression flag
    // you cannot do this before the pixel data is written, otherwise
    // the pixels will be re-compressed
    saver = new TiffSaver(outputFile);
    for (int i = 0; i < inputFiles.length; i++) {
        RandomAccessInputStream in = new RandomAccessInputStream(outputFile);
        saver.overwriteLastIFDOffset(in);
        saver.overwriteIFDValue(in, i, IFD.COMPRESSION, TiffCompression.JPEG.getCode());
        in.close();
    }
    saver.getStream().close();
}
Also used : IFD(loci.formats.tiff.IFD) RandomAccessOutputStream(loci.common.RandomAccessOutputStream) TiffSaver(loci.formats.tiff.TiffSaver) RandomAccessInputStream(loci.common.RandomAccessInputStream) ImageReader(loci.formats.ImageReader)

Example 27 with ImageReader

use of loci.formats.ImageReader in project bioformats by openmicroscopy.

the class SimpleTiledWriter method initialize.

/**
 * Set up the file reader and writer, ensuring that the input file is
 * associated with the reader and the output file is associated with the
 * writer.
 *
 * @return true if the reader and writer were successfully set up, or false
 *   if an error occurred
 * @throws DependencyException thrown if failed to create an OMEXMLService
 * @throws IOException thrown if unable to setup input or output stream for reader or writer
 * @throws FormatException thrown if invalid ID set for reader or writer or invalid tile size set
 * @throws ServiceException thrown if unable to create OME-XML meta data
 */
private void initialize() throws DependencyException, FormatException, IOException, ServiceException {
    // construct the object that stores OME-XML metadata
    ServiceFactory factory = new ServiceFactory();
    OMEXMLService service = factory.getInstance(OMEXMLService.class);
    IMetadata omexml = service.createOMEXMLMetadata();
    // set up the reader and associate it with the input file
    reader = new ImageReader();
    reader.setMetadataStore(omexml);
    reader.setId(inputFile);
    /* initialize-tiling-writer-example-start */
    // set up the writer and associate it with the output file
    writer = new OMETiffWriter();
    writer.setMetadataRetrieve(omexml);
    writer.setInterleaved(reader.isInterleaved());
    // set the tile size height and width for writing
    this.tileSizeX = writer.setTileSizeX(tileSizeX);
    this.tileSizeY = writer.setTileSizeY(tileSizeY);
    writer.setId(outputFile);
/* initialize-tiling-writer-example-end */
}
Also used : OMETiffWriter(loci.formats.out.OMETiffWriter) IMetadata(loci.formats.meta.IMetadata) ServiceFactory(loci.common.services.ServiceFactory) ImageReader(loci.formats.ImageReader) OMEXMLService(loci.formats.services.OMEXMLService)

Example 28 with ImageReader

use of loci.formats.ImageReader in project bioformats by openmicroscopy.

the class NRRDReader method initFile.

// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
@Override
protected void initFile(String id) throws FormatException, IOException {
    // make sure we actually have the .nrrd/.nhdr file
    if (!checkSuffix(id, "nhdr") && !checkSuffix(id, "nrrd")) {
        id += ".nhdr";
        if (!new Location(id).exists()) {
            id = id.substring(0, id.lastIndexOf("."));
            id = id.substring(0, id.lastIndexOf("."));
            id += ".nhdr";
        }
        id = new Location(id).getAbsolutePath();
    }
    super.initFile(id);
    in = new RandomAccessInputStream(id);
    ClassList<IFormatReader> classes = ImageReader.getDefaultReaderClasses();
    Class<? extends IFormatReader>[] classArray = classes.getClasses();
    ClassList<IFormatReader> newClasses = new ClassList<IFormatReader>(IFormatReader.class);
    for (Class<? extends IFormatReader> c : classArray) {
        if (!c.equals(NRRDReader.class)) {
            newClasses.addClass(c);
        }
    }
    helper = new ImageReader(newClasses);
    helper.setMetadataOptions(new DefaultMetadataOptions(MetadataLevel.MINIMUM));
    String key, v;
    String[] pixelSizeUnits = null;
    int numDimensions = 0;
    CoreMetadata m = core.get(0);
    m.sizeX = 1;
    m.sizeY = 1;
    m.sizeZ = 1;
    m.sizeC = 1;
    m.sizeT = 1;
    m.dimensionOrder = "XYCZT";
    String line = in.readLine();
    while (line != null && line.length() > 0) {
        if (!line.startsWith("#") && !line.startsWith("NRRD")) {
            // parse key/value pair
            key = line.substring(0, line.indexOf(':')).trim();
            v = line.substring(line.indexOf(':') + 1).trim();
            addGlobalMeta(key, v);
            if (key.equals("type")) {
                if (v.indexOf("char") != -1 || v.indexOf('8') != -1) {
                    m.pixelType = FormatTools.UINT8;
                } else if (v.indexOf("short") != -1 || v.indexOf("16") != -1) {
                    m.pixelType = FormatTools.UINT16;
                } else if (v.equals("int") || v.equals("signed int") || v.equals("int32") || v.equals("int32_t") || v.equals("uint") || v.equals("unsigned int") || v.equals("uint32") || v.equals("uint32_t")) {
                    m.pixelType = FormatTools.UINT32;
                } else if (v.equals("float"))
                    m.pixelType = FormatTools.FLOAT;
                else if (v.equals("double"))
                    m.pixelType = FormatTools.DOUBLE;
                else
                    throw new FormatException("Unsupported data type: " + v);
            } else if (key.equals("dimension")) {
                numDimensions = Integer.parseInt(v);
            } else if (key.equals("sizes")) {
                String[] tokens = v.split(" ");
                for (int i = 0; i < numDimensions; i++) {
                    int size = Integer.parseInt(tokens[i]);
                    if (numDimensions >= 3 && i == 0 && size > 1 && size <= 16) {
                        m.sizeC = size;
                    } else if (i == 0 || (getSizeC() > 1 && i == 1)) {
                        m.sizeX = size;
                    } else if (i == 1 || (getSizeC() > 1 && i == 2)) {
                        m.sizeY = size;
                    } else if (i == 2 || (getSizeC() > 1 && i == 3)) {
                        m.sizeZ = size;
                    } else if (i == 3 || (getSizeC() > 1 && i == 4)) {
                        m.sizeT = size;
                    }
                }
            } else if (key.equals("data file") || key.equals("datafile")) {
                dataFile = v;
            } else if (key.equals("encoding"))
                encoding = v;
            else if (key.equals("endian")) {
                m.littleEndian = v.equals("little");
            } else if (key.equals("spacings") || key.equals("space directions")) {
                pixelSizes = v.split(" ");
            } else if (key.equals("space units")) {
                pixelSizeUnits = v.split(" ");
            } else if (key.equals("byte skip")) {
                offset = Long.parseLong(v);
            }
        }
        line = in.readLine();
        if (line != null)
            line = line.trim();
    }
    if (dataFile == null)
        offset = in.getFilePointer();
    else {
        Location f = new Location(currentId).getAbsoluteFile();
        Location parent = f.getParentFile();
        if (f.exists() && parent != null) {
            dataFile = dataFile.substring(dataFile.indexOf(File.separator) + 1);
            dataFile = new Location(parent, dataFile).getAbsolutePath();
        }
        initializeHelper = !encoding.equals("raw");
    }
    m.rgb = getSizeC() > 1;
    m.interleaved = true;
    m.imageCount = getSizeZ() * getSizeT();
    m.indexed = false;
    m.falseColor = false;
    m.metadataComplete = true;
    MetadataStore store = makeFilterMetadata();
    MetadataTools.populatePixels(store, this);
    if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
        if (pixelSizes != null) {
            for (int i = 0; i < pixelSizes.length; i++) {
                if (pixelSizes[i] == null)
                    continue;
                try {
                    Double d = parsePixelSize(i);
                    String unit = pixelSizeUnits == null || i >= pixelSizeUnits.length ? null : pixelSizeUnits[i].replaceAll("\"", "");
                    if (i == 0) {
                        Length x = FormatTools.getPhysicalSizeX(d, unit);
                        if (x != null) {
                            store.setPixelsPhysicalSizeX(x, 0);
                        }
                    } else if (i == 1) {
                        Length y = FormatTools.getPhysicalSizeY(d, unit);
                        if (y != null) {
                            store.setPixelsPhysicalSizeY(y, 0);
                        }
                    } else if (i == 2) {
                        Length z = FormatTools.getPhysicalSizeZ(d, unit);
                        if (z != null) {
                            store.setPixelsPhysicalSizeZ(z, 0);
                        }
                    }
                } catch (NumberFormatException e) {
                }
            }
        }
    }
}
Also used : IFormatReader(loci.formats.IFormatReader) ClassList(loci.formats.ClassList) CoreMetadata(loci.formats.CoreMetadata) FormatException(loci.formats.FormatException) MetadataStore(loci.formats.meta.MetadataStore) Length(ome.units.quantity.Length) RandomAccessInputStream(loci.common.RandomAccessInputStream) ImageReader(loci.formats.ImageReader) Location(loci.common.Location)

Example 29 with ImageReader

use of loci.formats.ImageReader in project bioformats by openmicroscopy.

the class ZipReader method initFile.

// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
@Override
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());
    String innerFile = id;
    if (checkSuffix(id, "zip")) {
        innerFile = id.substring(0, id.length() - 4);
    }
    int sep = innerFile.lastIndexOf(File.separator);
    if (sep < 0) {
        sep = innerFile.lastIndexOf("/");
    }
    if (sep >= 0) {
        innerFile = innerFile.substring(sep + 1);
    }
    // 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);
    ZipEntry ze = null;
    entryName = null;
    boolean matchFound = false;
    while (true) {
        ze = zip.getNextEntry();
        if (ze == null)
            break;
        if (entryName == null) {
            entryName = ze.getName();
        }
        if (!matchFound && ze.getName().startsWith(innerFile)) {
            entryName = ze.getName();
            matchFound = true;
        }
        ZipHandle handle = new ZipHandle(id, ze);
        Location.mapFile(ze.getName(), handle);
        mappedFiles.add(ze.getName());
    }
    if (entryName == null) {
        throw new FormatException("Zip file does not contain any valid files");
    }
    reader.setId(entryName);
    metadataStore = reader.getMetadataStore();
    core = new ArrayList<CoreMetadata>(reader.getCoreMetadataList());
    metadata = reader.getGlobalMetadata();
}
Also used : ZipInputStream(java.util.zip.ZipInputStream) ZipHandle(loci.common.ZipHandle) ZipEntry(java.util.zip.ZipEntry) IRandomAccess(loci.common.IRandomAccess) RandomAccessInputStream(loci.common.RandomAccessInputStream) ImageReader(loci.formats.ImageReader) CoreMetadata(loci.formats.CoreMetadata) FormatException(loci.formats.FormatException)

Example 30 with ImageReader

use of loci.formats.ImageReader in project bioformats by openmicroscopy.

the class BioFormatsExtensionPrinter method main.

public static void main(String[] args) throws IOException {
    System.out.println("Generating list of Bio-Formats supported suffixes...");
    try (IFormatReader reader = new ImageReader()) {
        String[] suffixes = reader.getSuffixes();
        PrintWriter fo = null;
        fo = new PrintWriter(new File("BioFormatsSuffixes.txt"), Constants.ENCODING);
        for (String s : suffixes) fo.println("*." + s);
        fo.close();
        System.out.println(suffixes.length + " suffixes discovered.");
    }
}
Also used : IFormatReader(loci.formats.IFormatReader) ImageReader(loci.formats.ImageReader) File(java.io.File) PrintWriter(java.io.PrintWriter)

Aggregations

ImageReader (loci.formats.ImageReader)71 ServiceFactory (loci.common.services.ServiceFactory)23 OMEXMLService (loci.formats.services.OMEXMLService)23 FormatException (loci.formats.FormatException)20 IFormatReader (loci.formats.IFormatReader)20 IMetadata (loci.formats.meta.IMetadata)19 Test (org.testng.annotations.Test)15 IOException (java.io.IOException)11 ChannelFiller (loci.formats.ChannelFiller)11 DependencyException (loci.common.services.DependencyException)10 ServiceException (loci.common.services.ServiceException)10 ChannelSeparator (loci.formats.ChannelSeparator)10 MinMaxCalculator (loci.formats.MinMaxCalculator)10 BufferedImageReader (loci.formats.gui.BufferedImageReader)8 ImageWriter (loci.formats.ImageWriter)7 File (java.io.File)6 FileStitcher (loci.formats.FileStitcher)6 OMETiffWriter (loci.formats.out.OMETiffWriter)6 Location (loci.common.Location)5 DimensionSwapper (loci.formats.DimensionSwapper)5