CSJ2K.j2k.fileformat.reader.FileFormatReader.readFileFormat C# (CSharp) Method

readFileFormat() public method

This method checks whether the given RandomAccessIO is a valid JP2 file and if so finds the first codestream in the file. Currently, the information in the codestream is not used
If an I/O error ocurred. /// /// If end of file is reached /// ///
public readFileFormat ( ) : void
return void
        public virtual void readFileFormat()
        {
            //int foundCodeStreamBoxes = 0;
            int box;
            int length;
            long longLength = 0;
            int pos;
            short marker;
            bool jp2HeaderBoxFound = false;
            bool lastBoxFound = false;

            try
            {

                // Go through the randomaccessio and find the first contiguous
                // codestream box. Check also that the File Format is correct

                // Make sure that the first 12 bytes is the JP2_SIGNATURE_BOX or
                // if not that the first 2 bytes is the SOC marker
                if (in_Renamed.readInt() != 0x0000000c || in_Renamed.readInt() != CSJ2K.j2k.fileformat.FileFormatBoxes.JP2_SIGNATURE_BOX || in_Renamed.readInt() != 0x0d0a870a)
                {
                    // Not a JP2 file
                    in_Renamed.seek(0);

                    marker = (short) in_Renamed.readShort();
                    if (marker != CSJ2K.j2k.codestream.Markers.SOC)
                    //Standard syntax marker found
                        throw new System.InvalidOperationException("File is neither valid JP2 file nor " + "valid JPEG 2000 codestream");
                    JP2FFUsed = false;
                    in_Renamed.seek(0);
                    return ;
                }

                // The JP2 File format is being used
                JP2FFUsed = true;

                // Read File Type box
                if (!readFileTypeBox())
                {
                    // Not a valid JP2 file or codestream
                    throw new System.InvalidOperationException("Invalid JP2 file: File Type box missing");
                }

                // Read all remaining boxes
                while (!lastBoxFound)
                {
                    pos = in_Renamed.Pos;
                    length = in_Renamed.readInt();
                    if ((pos + length) == in_Renamed.length())
                        lastBoxFound = true;

                    box = in_Renamed.readInt();
                    if (length == 0)
                    {
                        lastBoxFound = true;
                        length = in_Renamed.length() - in_Renamed.Pos;
                    }
                    else if (length == 1)
                    {
                        longLength = in_Renamed.readLong();
                        throw new System.IO.IOException("File too long.");
                    }
                    else
                        longLength = (long) 0;

                    switch (box)
                    {

                        case CSJ2K.j2k.fileformat.FileFormatBoxes.CONTIGUOUS_CODESTREAM_BOX:
                            if (!jp2HeaderBoxFound)
                            {
                                throw new System.InvalidOperationException("Invalid JP2 file: JP2Header box not " + "found before Contiguous codestream " + "box ");
                            }
                            readContiguousCodeStreamBox(pos, length, longLength);
                            break;

                        case CSJ2K.j2k.fileformat.FileFormatBoxes.JP2_HEADER_BOX:
                            if (jp2HeaderBoxFound)
                                throw new System.InvalidOperationException("Invalid JP2 file: Multiple " + "JP2Header boxes found");
                            readJP2HeaderBox(pos, length, longLength);
                            jp2HeaderBoxFound = true;
                            break;

                        case CSJ2K.j2k.fileformat.FileFormatBoxes.INTELLECTUAL_PROPERTY_BOX:
                            readIntPropertyBox(length);
                            break;

                        case CSJ2K.j2k.fileformat.FileFormatBoxes.XML_BOX:
                            readXMLBox(length);
                            break;

                        case CSJ2K.j2k.fileformat.FileFormatBoxes.UUID_BOX:
                            readUUIDBox(length);
                            break;

                        case CSJ2K.j2k.fileformat.FileFormatBoxes.UUID_INFO_BOX:
                            readUUIDInfoBox(length);
                            break;

                        case CSJ2K.j2k.fileformat.FileFormatBoxes.READER_REQUIREMENTS_BOX:
                            readReaderRequirementsBox(length);
                            break;

                        default:
                            FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.WARNING, "Unknown box-type: 0x" + System.Convert.ToString(box, 16));
                            break;

                    }
                    if (!lastBoxFound)
                        in_Renamed.seek(pos + length);
                }
            }
            catch (System.IO.EndOfStreamException e)
            {
                throw new System.InvalidOperationException("EOF reached before finding Contiguous " + "Codestream Box");
            }

            if (codeStreamPos.Count == 0)
            {
                // Not a valid JP2 file or codestream
                throw new System.InvalidOperationException("Invalid JP2 file: Contiguous codestream box " + "missing");
            }

            return ;
        }

Usage Example

Example #1
0
        public static Image FromStream(Stream stream)
        {
            RandomAccessIO in_stream = new ISRandomAccessIO(stream);

            // Initialize default parameters
            ParameterList defpl = GetDefaultParameterList(decoder_pinfo);

            // Create parameter list using defaults
            ParameterList pl = new ParameterList(defpl);

            // **** File Format ****
            // If the codestream is wrapped in the jp2 fileformat, Read the
            // file format wrapper
            FileFormatReader ff = new FileFormatReader(in_stream);
            ff.readFileFormat();
            if (ff.JP2FFUsed)
            {
                in_stream.seek(ff.FirstCodeStreamPos);
            }

            // +----------------------------+
            // | Instantiate decoding chain |
            // +----------------------------+

            // **** Header decoder ****
            // Instantiate header decoder and read main header 
            HeaderInfo hi = new HeaderInfo();
            HeaderDecoder hd;
            try
            {
                hd = new HeaderDecoder(in_stream, pl, hi);
            }
            catch (EndOfStreamException e)
            {
                throw new ApplicationException("Codestream too short or bad header, unable to decode.", e);
            }

            int nCompCod = hd.NumComps;
            int nTiles = hi.sizValue.NumTiles;
            DecoderSpecs decSpec = hd.DecoderSpecs;

            // Get demixed bitdepths
            int[] depth = new int[nCompCod];
            for (int i = 0; i < nCompCod; i++)
            {
                depth[i] = hd.getOriginalBitDepth(i);
            }

            // **** Bit stream reader ****
            BitstreamReaderAgent breader;
            try
            {
                breader = BitstreamReaderAgent.
                    createInstance(in_stream, hd, pl, decSpec,
                                   false, hi);
            }
            catch (IOException e)
            {
                throw new ApplicationException("Error while reading bit stream header or parsing packets.", e);
            }
            catch (ArgumentException e)
            {
                throw new ApplicationException("Cannot instantiate bit stream reader.", e);
            }

            // **** Entropy decoder ****
            EntropyDecoder entdec;
            try
            {
                entdec = hd.createEntropyDecoder(breader, pl);
            }
            catch (ArgumentException e)
            {
                throw new ApplicationException("Cannot instantiate entropy decoder.", e);
            }

            // **** ROI de-scaler ****
            ROIDeScaler roids;
            try
            {
                roids = hd.createROIDeScaler(entdec, pl, decSpec);
            }
            catch (ArgumentException e)
            {
                throw new ApplicationException("Cannot instantiate roi de-scaler.", e);
            }

            // **** Dequantizer ****
            Dequantizer deq;
            try
            {
                deq = hd.createDequantizer(roids, depth, decSpec);
            }
            catch (ArgumentException e)
            {
                throw new ApplicationException("Cannot instantiate dequantizer.", e);
            }

            // **** Inverse wavelet transform ***
            InverseWT invWT;
            try
            {
                // full page inverse wavelet transform
                invWT = InverseWT.createInstance(deq, decSpec);
            }
            catch (ArgumentException e)
            {
                throw new ApplicationException("Cannot instantiate inverse wavelet transform.", e);
            }

            int res = breader.ImgRes;
            invWT.ImgResLevel = res;

            // **** Data converter **** (after inverse transform module)
            ImgDataConverter converter = new ImgDataConverter(invWT, 0);

            // **** Inverse component transformation **** 
            InvCompTransf ictransf = new InvCompTransf(converter, decSpec, depth, pl);

            // **** Color space mapping ****
            BlkImgDataSrc color;
            if (ff.JP2FFUsed && pl.getParameter("nocolorspace").Equals("off"))
            {
                try
                {
                    ColorSpace csMap = new ColorSpace(in_stream, hd, pl);
                    BlkImgDataSrc channels = hd.createChannelDefinitionMapper(ictransf, csMap);
                    BlkImgDataSrc resampled = hd.createResampler(channels, csMap);
                    BlkImgDataSrc palettized = hd.createPalettizedColorSpaceMapper(resampled, csMap);
                    color = hd.createColorSpaceMapper(palettized, csMap);
                }
                catch (ArgumentException e)
                {
                    throw new ApplicationException("Could not instantiate ICC profiler.", e);
                }
                catch (ColorSpaceException e)
                {
                    throw new ApplicationException("Error processing ColorSpace information.", e);
                }
            }
            else
            { // Skip colorspace mapping
                color = ictransf;
            }

            // This is the last image in the decoding chain and should be
            // assigned by the last transformation:
            BlkImgDataSrc decodedImage = color;
            if (color == null)
            {
                decodedImage = ictransf;
            }
            int numComps = decodedImage.NumComps;

            int bytesPerPixel = (numComps == 4 ? 4 : 3);

            // **** Copy to Bitmap ****
            PixelFormat pixelFormat;
            switch (numComps)
            {
                case 1:
                    pixelFormat = PixelFormat.Format24bppRgb; break;
                case 3:
                    pixelFormat = PixelFormat.Format24bppRgb; break;
                case 4:
                    pixelFormat = PixelFormat.Format32bppArgb; break;
                default:
                    throw new ApplicationException("Unsupported PixelFormat.  " + numComps + " components.");
            }

            Bitmap dst = new Bitmap(decodedImage.ImgWidth, decodedImage.ImgHeight, pixelFormat);

            Coord numTiles = decodedImage.getNumTiles(null);

            int tIdx = 0;

            for (int y = 0; y < numTiles.y; y++)
            {
                // Loop on horizontal tiles
                for (int x = 0; x < numTiles.x; x++, tIdx++)
                {
                    decodedImage.setTile(x, y);

                    int height = decodedImage.getTileCompHeight(tIdx, 0);
                    int width = decodedImage.getTileCompWidth(tIdx, 0);

                    int tOffx = decodedImage.getCompULX(0) -
                        (int)Math.Ceiling(decodedImage.ImgULX /
                           (double)decodedImage.getCompSubsX(0));

                    int tOffy = decodedImage.getCompULY(0) -
                        (int)Math.Ceiling(decodedImage.ImgULY /
                            (double)decodedImage.getCompSubsY(0));

                    DataBlkInt[] db = new DataBlkInt[numComps];
                    int[] ls = new int[numComps];
                    int[] mv = new int[numComps];
                    int[] fb = new int[numComps];
                    for (int i = 0; i < numComps; i++)
                    {
                        db[i] = new DataBlkInt();
                        ls[i] = 1 << (decodedImage.getNomRangeBits(0) - 1);
                        mv[i] = (1 << decodedImage.getNomRangeBits(0)) - 1;
                        fb[i] = decodedImage.getFixedPoint(0);
                    }
                    for (int l = 0; l < height; l++)
                    {
                        for (int i = numComps - 1; i >= 0; i--)
                        {
                            db[i].ulx = 0;
                            db[i].uly = l;
                            db[i].w = width;
                            db[i].h = 1;
                            decodedImage.getInternCompData(db[i], i);
                        }
                        int[] k = new int[numComps];
                        for (int i = numComps - 1; i >= 0; i--) k[i] = db[i].offset + width - 1;

                        byte[] rowvalues = new byte[width * bytesPerPixel];

                        for (int i = width - 1; i >= 0; i--)
                        {
                            int[] tmp = new int[numComps];
                            for (int j = numComps - 1; j >= 0; j--)
                            {
                                tmp[j] = (db[j].data_array[k[j]--] >> fb[j]) + ls[j];
                                tmp[j] = (tmp[j] < 0) ? 0 : ((tmp[j] > mv[j]) ? mv[j] : tmp[j]);

                                if (decodedImage.getNomRangeBits(j) != 8)
                                    tmp[j] = (int)Math.Round(((double)tmp[j] / Math.Pow(2D, (double)decodedImage.getNomRangeBits(j))) * 255D);

                            }
                            int offset = i * bytesPerPixel;
                            switch (numComps)
                            {
                                case 1:
                                    rowvalues[offset + 0] = (byte)tmp[0];
                                    rowvalues[offset + 1] = (byte)tmp[0];
                                    rowvalues[offset + 2] = (byte)tmp[0];
                                    break;
                                case 3:
                                    rowvalues[offset + 0] = (byte)tmp[2];
                                    rowvalues[offset + 1] = (byte)tmp[1];
                                    rowvalues[offset + 2] = (byte)tmp[0];
                                    break;
                                case 4:
                                    rowvalues[offset + 0] = (byte)tmp[3];
                                    rowvalues[offset + 1] = (byte)tmp[2];
                                    rowvalues[offset + 2] = (byte)tmp[1];
                                    rowvalues[offset + 3] = (byte)tmp[0];
                                    break;
                            }
                        }

                        BitmapData dstdata = dst.LockBits(
                            new System.Drawing.Rectangle(tOffx, tOffy + l, width, 1),
                            ImageLockMode.ReadWrite, pixelFormat);

                        IntPtr ptr = dstdata.Scan0;
                        System.Runtime.InteropServices.Marshal.Copy(rowvalues, 0, ptr, rowvalues.Length);
                        dst.UnlockBits(dstdata);
                    }
                }
            }
            return dst;
        }
All Usage Examples Of CSJ2K.j2k.fileformat.reader.FileFormatReader::readFileFormat