Search in sources :

Example 21 with MetadataRetrieve

use of loci.formats.meta.MetadataRetrieve in project bioformats by openmicroscopy.

the class OMEXMLWriter method saveBytes.

// -- IFormatWriter API methods --
/**
 * @see loci.formats.IFormatWriter#saveBytes(int, byte[], int, int, int, int)
 */
@Override
public void saveBytes(int no, byte[] buf, int x, int y, int w, int h) throws FormatException, IOException {
    checkParams(no, buf, x, y, w, h);
    if (!isFullPlane(x, y, w, h)) {
        throw new FormatException("OMEXMLWriter does not yet support saving image tiles.");
    }
    MetadataRetrieve retrieve = getMetadataRetrieve();
    if (no == 0) {
        out.writeBytes(xmlFragments.get(series));
    }
    String type = retrieve.getPixelsType(series).toString();
    int pixelType = FormatTools.pixelTypeFromString(type);
    int bytes = FormatTools.getBytesPerPixel(pixelType);
    int nChannels = getSamplesPerPixel();
    int sizeX = retrieve.getPixelsSizeX(series).getValue().intValue();
    int sizeY = retrieve.getPixelsSizeY(series).getValue().intValue();
    int planeSize = sizeX * sizeY * bytes;
    boolean bigEndian = false;
    if (retrieve.getPixelsBigEndian(series) != null) {
        bigEndian = retrieve.getPixelsBigEndian(series).booleanValue();
    } else if (retrieve.getPixelsBinDataCount(series) == 0) {
        bigEndian = retrieve.getPixelsBinDataBigEndian(series, 0).booleanValue();
    }
    String namespace = "xmlns=\"http://www.openmicroscopy.org/Schemas/OME/" + service.getLatestVersion() + "\"";
    for (int i = 0; i < nChannels; i++) {
        byte[] b = ImageTools.splitChannels(buf, i, nChannels, bytes, false, interleaved);
        byte[] encodedPix = compress(b);
        final StringBuilder plane = new StringBuilder("\n<BinData ");
        plane.append(namespace);
        plane.append(" Length=\"");
        plane.append(planeSize);
        plane.append("\"");
        plane.append(" BigEndian=\"");
        plane.append(bigEndian);
        plane.append("\"");
        if (compression != null && !compression.equals("Uncompressed")) {
            plane.append(" Compression=\"");
            plane.append(compression);
            plane.append("\"");
        }
        plane.append(">");
        plane.append(new String(encodedPix, Constants.ENCODING));
        plane.append("</BinData>");
        out.writeBytes(plane.toString());
    }
}
Also used : MetadataRetrieve(loci.formats.meta.MetadataRetrieve) FormatException(loci.formats.FormatException)

Example 22 with MetadataRetrieve

use of loci.formats.meta.MetadataRetrieve in project bioformats by openmicroscopy.

the class AVIWriter method setId.

/* @see loci.formats.FormatWriter#setId(String) */
@Override
public void setId(String id) throws FormatException, IOException {
    super.setId(id);
    savedbLength = new ArrayList<Long>();
    if (out.length() > 0) {
        RandomAccessInputStream in = new RandomAccessInputStream(currentId);
        in.order(true);
        in.seek(FRAME_OFFSET);
        planesWritten = in.readInt();
        in.seek(SAVE_FILE_SIZE);
        endPos = in.readInt() + SAVE_FILE_SIZE + 4;
        in.seek(SAVE_LIST2_SIZE);
        idx1Pos = in.readInt() + SAVE_LIST2_SIZE + 4;
        saveidx1Length = idx1Pos + 4;
        if (planesWritten > 0)
            in.seek(saveidx1Length + 4);
        for (int z = 0; z < planesWritten; z++) {
            in.skipBytes(8);
            savedbLength.add(in.readInt() + 4 + SAVE_MOVI);
            in.skipBytes(4);
        }
        in.close();
        out.seek(idx1Pos);
    } else {
        planesWritten = 0;
    }
    out.order(true);
    MetadataRetrieve meta = getMetadataRetrieve();
    tDim = meta.getPixelsSizeZ(series).getValue().intValue();
    zDim = meta.getPixelsSizeT(series).getValue().intValue();
    yDim = meta.getPixelsSizeY(series).getValue().intValue();
    xDim = meta.getPixelsSizeX(series).getValue().intValue();
    String type = meta.getPixelsType(series).toString();
    int pixelType = FormatTools.pixelTypeFromString(type);
    bytesPerPixel = FormatTools.getBytesPerPixel(pixelType);
    bytesPerPixel *= getSamplesPerPixel();
    xPad = 0;
    int xMod = xDim % 4;
    if (xMod != 0) {
        xPad = 4 - xMod;
        xDim += xPad;
    }
    byte[][] lut = null;
    if (getColorModel() instanceof IndexColorModel) {
        lut = new byte[4][256];
        IndexColorModel model = (IndexColorModel) getColorModel();
        model.getReds(lut[0]);
        model.getGreens(lut[1]);
        model.getBlues(lut[2]);
        model.getAlphas(lut[3]);
    }
    if (out.length() == 0) {
        // signature
        out.writeBytes("RIFF");
        // Bytes 4 thru 7 contain the length of the file. This length does
        // not include bytes 0 thru 7.
        // for now write 0 for size
        out.writeInt(0);
        // RIFF type
        out.writeBytes("AVI ");
        // Write the first LIST chunk, which contains
        // information on data decoding
        // CHUNK signature
        out.writeBytes("LIST");
        // Write the length of the LIST CHUNK not including the first 8 bytes
        // with LIST and size. Note that the end of the LIST CHUNK is followed
        // by JUNK.
        out.writeInt((bytesPerPixel == 1) ? 1240 : 216);
        // CHUNK type
        out.writeBytes("hdrl");
        // Write the avih sub-CHUNK
        out.writeBytes("avih");
        // Write the length of the avih sub-CHUNK (38H) not including the
        // the first 8 bytes for avihSignature and the length
        out.writeInt(0x38);
        // dwMicroSecPerFrame - Write the microseconds per frame
        microSecPerFrame = (int) (1.0 / fps * 1.0e6);
        out.writeInt(microSecPerFrame);
        // Write the maximum data rate of the file in bytes per second
        // dwMaxBytesPerSec
        out.writeInt(0);
        // dwReserved1 - set to 0
        out.writeInt(0);
        // dwFlags - just set the bit for AVIF_HASINDEX
        out.writeInt(0x10);
        // 10H AVIF_HASINDEX: The AVI file has an idx1 chunk containing
        // an index at the end of the file. For good performance, all
        // AVI files should contain an index.
        // 20H AVIF_MUSTUSEINDEX: Index CHUNK, rather than the physical
        // ordering of the chunks in the file, must be used to determine the
        // order of the frames.
        // 100H AVIF_ISINTERLEAVED: Indicates that the AVI file is interleaved.
        // This is used to read data from a CD-ROM more efficiently.
        // 800H AVIF_TRUSTCKTYPE: USE CKType to find key frames
        // 10000H AVIF_WASCAPTUREFILE: The AVI file is used for capturing
        // real-time video. Applications should warn the user before
        // writing over a file with this fla set because the user
        // probably defragmented this file.
        // 20000H AVIF_COPYRIGHTED: The AVI file contains copyrighted data
        // and software. When, this flag is used, software should not
        // permit the data to be duplicated.
        // dwTotalFrames - total frame number
        out.writeInt(0);
        // dwInitialFrames -Initial frame for interleaved files.
        // Noninterleaved files should specify 0.
        out.writeInt(0);
        // dwStreams - number of streams in the file - here 1 video and
        // zero audio.
        out.writeInt(1);
        // dwSuggestedBufferSize - Suggested buffer size for reading the file.
        // Generally, this size should be large enough to contain the largest
        // chunk in the file.
        out.writeInt(0);
        // dwWidth - image width in pixels
        out.writeInt(xDim - xPad);
        // dwHeight - height in pixels
        out.writeInt(yDim);
        // dwReserved[4] - Microsoft says to set the following 4 values to 0.
        out.writeInt(0);
        out.writeInt(0);
        out.writeInt(0);
        out.writeInt(0);
        // Write the Stream line header CHUNK
        out.writeBytes("LIST");
        // Write the size of the first LIST subCHUNK not including the first 8
        // bytes with LIST and size. Note that saveLIST1subSize = saveLIST1Size
        // + 76, and that the length written to saveLIST1subSize is 76 less than
        // the length written to saveLIST1Size. The end of the first LIST
        // subCHUNK is followed by JUNK.
        out.writeInt((bytesPerPixel == 1) ? 1164 : 140);
        // Write the chunk type
        out.writeBytes("strl");
        // Write the strh sub-CHUNK
        out.writeBytes("strh");
        // Write length of strh sub-CHUNK
        out.writeInt(56);
        // fccType - Write the type of data stream - here vids for video stream
        out.writeBytes("vids");
        // Write DIB for Microsoft Device Independent Bitmap.
        // Note: Unfortunately, at least 3 other four character codes are
        // sometimes used for uncompressed AVI videos: 'RGB ', 'RAW ',
        // 0x00000000
        out.writeBytes("DIB ");
        // dwFlags
        out.writeInt(0);
        // 0x00000001 AVISF_DISABLED The stram data should be rendered only when
        // explicitly enabled.
        // 0x00010000 AVISF_VIDEO_PALCHANGES Indicates that a palette change is
        // included in the AVI file. This flag warns the playback software that
        // it will need to animate the palette.
        // dwPriority - priority of a stream type. For example, in a file with
        // multiple audio streams, the one with the highest priority might be
        // the default one.
        out.writeInt(0);
        // dwInitialFrames - Specifies how far audio data is skewed ahead of
        // video frames in interleaved files. Typically, this is about 0.75
        // seconds. In interleaved files specify the number of frames in the
        // file prior to the initial frame of the AVI sequence.
        // Noninterleaved files should use zero.
        out.writeInt(0);
        // rate/scale = samples/second
        // dwScale
        out.writeInt(1);
        // dwRate - frame rate for video streams
        out.writeInt(fps);
        // dwStart - this field is usually set to zero
        out.writeInt(0);
        // dwLength - playing time of AVI file as defined by scale and rate
        // Set equal to the number of frames
        out.writeInt(tDim * zDim);
        // dwSuggestedBufferSize - Suggested buffer size for reading the stream.
        // Typically, this contains a value corresponding to the largest chunk
        // in a stream.
        out.writeInt(0);
        // dwQuality - encoding quality given by an integer between 0 and
        // 10,000. If set to -1, drivers use the default quality value.
        out.writeInt(-1);
        // dwSampleSize #
        // 0 if the video frames may or may not vary in size
        // If 0, each sample of data(such as a video frame) must be in a
        // separate chunk. If nonzero, then multiple samples of data can be
        // grouped into a single chunk within the file.
        out.writeInt(0);
        // rcFrame - Specifies the destination rectangle for a text or video
        // stream within the movie rectangle specified by the dwWidth and
        // dwHeight members of the AVI main header structure. The rcFrame member
        // is typically used in support of multiple video streams. Set this
        // rectangle to the coordinates corresponding to the movie rectangle to
        // update the whole movie rectangle. Units for this member are pixels.
        // The upper-left corner of the destination rectangle is relative to the
        // upper-left corner of the movie rectangle.
        // left
        out.writeShort((short) 0);
        // top
        out.writeShort((short) 0);
        // right
        out.writeShort((short) 0);
        // bottom
        out.writeShort((short) 0);
        // Write the size of the stream format CHUNK not including the first 8
        // bytes for strf and the size. Note that the end of the stream format
        // CHUNK is followed by strn.
        // Write the stream format chunk
        out.writeBytes("strf");
        // write the strf CHUNK size
        out.writeInt((bytesPerPixel == 1) ? 1068 : 44);
        // Applications should use this size to determine which BITMAPINFO
        // header structure is being used. This size includes this biSize field.
        // biSize- Write header size of BITMAPINFO header structure
        out.writeInt(40);
        // biWidth - image width in pixels
        out.writeInt(xDim);
        // biHeight - image height in pixels. If height is positive, the bitmap
        // is a bottom up DIB and its origin is in the lower left corner. If
        // height is negative, the bitmap is a top-down DIB and its origin is
        // the upper left corner. This negative sign feature is supported by the
        // Windows Media Player, but it is not supported by PowerPoint.
        out.writeInt(yDim);
        // biPlanes - number of color planes in which the data is stored
        // This must be set to 1.
        out.writeShort(1);
        int bitsPerPixel = (bytesPerPixel == 3) ? 24 : 8;
        // biBitCount - number of bits per pixel #
        // 0L for BI_RGB, uncompressed data as bitmap
        out.writeShort((short) bitsPerPixel);
        // biSizeImage #
        out.writeInt(0);
        // biCompression - compression type
        out.writeInt(0);
        // biXPelsPerMeter - horizontal resolution in pixels
        out.writeInt(0);
        // biYPelsPerMeter - vertical resolution in pixels per meter
        out.writeInt(0);
        int nColors = 256;
        out.writeInt(nColors);
        // biClrImportant - specifies that the first x colors of the color table
        // are important to the DIB. If the rest of the colors are not
        // available, the image still retains its meaning in an acceptable
        // manner. When this field is set to zero, all the colors are important,
        // or, rather, their relative importance has not been computed.
        out.writeInt(0);
        // written: blue byte, green byte, red byte, 0 byte
        if (bytesPerPixel == 1) {
            if (lut != null) {
                for (int i = 0; i < 256; i++) {
                    out.write(lut[2][i]);
                    out.write(lut[1][i]);
                    out.write(lut[0][i]);
                    out.write(lut[3][i]);
                }
            } else {
                byte[] lutWrite = new byte[4 * 256];
                for (int i = 0; i < 256; i++) {
                    // blue
                    lutWrite[4 * i] = (byte) i;
                    // green
                    lutWrite[4 * i + 1] = (byte) i;
                    // red
                    lutWrite[4 * i + 2] = (byte) i;
                    lutWrite[4 * i + 3] = 0;
                }
                out.write(lutWrite);
            }
        }
        out.seek(SAVE_STRF_SIZE);
        out.writeInt((int) (SAVE_STRN_POS - (SAVE_STRF_SIZE + 4)));
        out.seek(SAVE_STRN_POS);
        // Use strn to provide zero terminated text string describing the stream
        out.writeBytes("strn");
        // Write length of strn sub-CHUNK
        out.writeInt(16);
        out.writeBytes("FileAVI write  ");
        out.seek(SAVE_LIST1_SIZE);
        out.writeInt((int) (SAVE_JUNK_SIG - (SAVE_LIST1_SIZE + 4)));
        out.seek(SAVE_LIST1_SUBSIZE);
        out.writeInt((int) (SAVE_JUNK_SIG - (SAVE_LIST1_SUBSIZE + 4)));
        out.seek(SAVE_JUNK_SIG);
        // write a JUNK CHUNK for padding
        out.writeBytes("JUNK");
        out.writeInt((int) PADDING_BYTES);
        for (int i = 0; i < PADDING_BYTES / 2; i++) {
            out.writeShort((short) 0);
        }
        // Write the second LIST chunk, which contains the actual data
        out.writeBytes("LIST");
        // For now write 0
        out.writeInt(4);
        // Write CHUNK type 'movi'
        out.writeBytes("movi");
        idx1Pos = out.getFilePointer();
    }
}
Also used : RandomAccessInputStream(loci.common.RandomAccessInputStream) MetadataRetrieve(loci.formats.meta.MetadataRetrieve) IndexColorModel(java.awt.image.IndexColorModel)

Example 23 with MetadataRetrieve

use of loci.formats.meta.MetadataRetrieve in project bioformats by openmicroscopy.

the class ICSWriter method setId.

// -- IFormatHandler API methods --
/* @see loci.formats.FormatWriter#setId(String) */
@Override
public void setId(String id) throws FormatException, IOException {
    super.setId(id);
    if (!uniqueFiles.contains(id)) {
        uniqueFiles.add(id);
    }
    if (checkSuffix(currentId, "ids")) {
        String metadataFile = currentId.substring(0, currentId.lastIndexOf("."));
        metadataFile += ".ics";
        out.close();
        out = new RandomAccessOutputStream(metadataFile);
    }
    if (out.length() == 0) {
        out.writeBytes("\t\n");
        if (checkSuffix(id, "ids")) {
            out.writeBytes("ics_version\t1.0\n");
        } else {
            out.writeBytes("ics_version\t2.0\n");
        }
        out.writeBytes("filename\t" + currentId + "\n");
        out.writeBytes("layout\tparameters\t6\n");
        MetadataRetrieve meta = getMetadataRetrieve();
        MetadataTools.verifyMinimumPopulated(meta, series);
        int pixelType = FormatTools.pixelTypeFromString(meta.getPixelsType(series).toString());
        dimensionOffset = out.getFilePointer();
        int[] sizes = overwriteDimensions(meta);
        dimensionLength = (int) (out.getFilePointer() - dimensionOffset);
        if (validBits != 0) {
            out.writeBytes("layout\tsignificant_bits\t" + validBits + "\n");
        }
        boolean signed = FormatTools.isSigned(pixelType);
        boolean littleEndian = false;
        if (meta.getPixelsBigEndian(series) != null) {
            littleEndian = !meta.getPixelsBigEndian(series).booleanValue();
        } else if (meta.getPixelsBinDataCount(series) == 0) {
            littleEndian = !meta.getPixelsBinDataBigEndian(series, 0).booleanValue();
        }
        out.writeBytes("representation\tformat\t" + (pixelType == FormatTools.FLOAT ? "real\n" : "integer\n"));
        out.writeBytes("representation\tsign\t" + (signed ? "signed\n" : "unsigned\n"));
        out.writeBytes("representation\tcompression\tuncompressed\n");
        out.writeBytes("representation\tbyte_order\t");
        for (int i = 0; i < sizes[0] / 8; i++) {
            if ((littleEndian && (sizes[0] < 32 || pixelType == FormatTools.FLOAT)) || (!littleEndian && sizes[0] >= 32 && pixelType != FormatTools.FLOAT)) {
                out.writeBytes((i + 1) + "\t");
            } else {
                out.writeBytes(((sizes[0] / 8) - i) + "\t");
            }
        }
        out.writeBytes("\nparameter\tscale\t1.000000\t");
        final StringBuilder units = new StringBuilder();
        for (int i = 0; i < outputOrder.length(); i++) {
            char dim = outputOrder.charAt(i);
            Number value = 1.0;
            if (dim == 'X') {
                if (meta.getPixelsPhysicalSizeX(0) != null) {
                    value = meta.getPixelsPhysicalSizeX(0).value(UNITS.MICROMETER).doubleValue();
                }
                units.append("micrometers\t");
            } else if (dim == 'Y') {
                if (meta.getPixelsPhysicalSizeY(0) != null) {
                    value = meta.getPixelsPhysicalSizeY(0).value(UNITS.MICROMETER).doubleValue();
                }
                units.append("micrometers\t");
            } else if (dim == 'Z') {
                if (meta.getPixelsPhysicalSizeZ(0) != null) {
                    value = meta.getPixelsPhysicalSizeZ(0).value(UNITS.MICROMETER).doubleValue();
                }
                units.append("micrometers\t");
            } else if (dim == 'T') {
                Time valueTime = meta.getPixelsTimeIncrement(0);
                if (valueTime != null) {
                    value = valueTime.value(UNITS.SECOND);
                    units.append("seconds\t");
                }
            }
            out.writeBytes(value + "\t");
        }
        out.writeBytes("\nparameter\tunits\tbits\t" + units.toString() + "\n");
        out.writeBytes("\nend\n");
        pixelOffset = out.getFilePointer();
    } else if (checkSuffix(currentId, "ics")) {
        RandomAccessInputStream in = new RandomAccessInputStream(currentId);
        in.findString("\nend\n");
        pixelOffset = in.getFilePointer();
        in.close();
    }
    if (checkSuffix(currentId, "ids")) {
        pixelOffset = 0;
    }
}
Also used : RandomAccessOutputStream(loci.common.RandomAccessOutputStream) Time(ome.units.quantity.Time) RandomAccessInputStream(loci.common.RandomAccessInputStream) MetadataRetrieve(loci.formats.meta.MetadataRetrieve)

Example 24 with MetadataRetrieve

use of loci.formats.meta.MetadataRetrieve in project bioformats by openmicroscopy.

the class OMETiffWriter method setId.

// -- FormatWriter API methods --
/* @see FormatWriter#setId(String) */
@Override
public void setId(String id) throws FormatException, IOException {
    if (id.equals(currentId))
        return;
    super.setId(id);
    if (imageLocations == null) {
        MetadataRetrieve r = getMetadataRetrieve();
        imageLocations = new String[r.getImageCount()][];
        for (int i = 0; i < imageLocations.length; i++) {
            setSeries(i);
            imageLocations[i] = new String[planeCount()];
        }
        setSeries(0);
    }
}
Also used : MetadataRetrieve(loci.formats.meta.MetadataRetrieve)

Example 25 with MetadataRetrieve

use of loci.formats.meta.MetadataRetrieve in project bioformats by openmicroscopy.

the class OMETiffWriter method planeCount.

private int planeCount() {
    MetadataRetrieve r = getMetadataRetrieve();
    int z = r.getPixelsSizeZ(series).getValue().intValue();
    int t = r.getPixelsSizeT(series).getValue().intValue();
    int c = r.getChannelCount(series);
    String pixelType = r.getPixelsType(series).getValue();
    int bytes = FormatTools.getBytesPerPixel(pixelType);
    if (bytes > 1 && c == 1) {
        c = r.getChannelSamplesPerPixel(series, 0).getValue();
    }
    return z * c * t;
}
Also used : MetadataRetrieve(loci.formats.meta.MetadataRetrieve)

Aggregations

MetadataRetrieve (loci.formats.meta.MetadataRetrieve)64 FormatException (loci.formats.FormatException)11 MetadataStore (loci.formats.meta.MetadataStore)11 Length (ome.units.quantity.Length)10 ServiceFactory (loci.common.services.ServiceFactory)8 DependencyException (loci.common.services.DependencyException)7 OMEXMLService (loci.formats.services.OMEXMLService)6 RandomAccessInputStream (loci.common.RandomAccessInputStream)5 Time (ome.units.quantity.Time)5 PositiveInteger (ome.xml.model.primitives.PositiveInteger)5 ServiceException (loci.common.services.ServiceException)4 MissingLibraryException (loci.formats.MissingLibraryException)4 Test (org.testng.annotations.Test)4 IndexColorModel (java.awt.image.IndexColorModel)3 Location (loci.common.Location)3 RandomAccessOutputStream (loci.common.RandomAccessOutputStream)3 ImageReader (loci.formats.ImageReader)3 BufferedImage (java.awt.image.BufferedImage)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 File (java.io.File)2