예제 #1
0
        /// <summary>
        /// If this font file is using the Compact Font File Format, then this method
        /// will return the raw bytes needed for the font stream.
        /// </summary>
        /// <remarks>
        /// If this font file is using the Compact Font File Format, then this method
        /// will return the raw bytes needed for the font stream. If this method is
        /// ever made public: make sure to add a test if (cff == true).
        /// </remarks>
        /// <returns>a byte array</returns>
        public virtual byte[] ReadCffFont()
        {
            if (!IsCff())
            {
                return(null);
            }
            RandomAccessFileOrArray rf2 = null;

            try {
                rf2 = raf.CreateView();
                rf2.Seek(cffOffset);
                byte[] cff = new byte[cffLength];
                rf2.ReadFully(cff);
                return(cff);
            }
            finally {
                try {
                    if (rf2 != null)
                    {
                        rf2.Close();
                    }
                }
                catch (Exception) {
                }
            }
        }
예제 #2
0
        private void ExtractEncrypted(String encryptedName, String wrapperName, byte[] password)
        {
            String      inPath   = sourceFolder + "cmp_" + wrapperName;
            String      cmpPath  = sourceFolder + "cmp_" + encryptedName;
            String      outPath  = destinationFolder + encryptedName;
            String      diff     = "diff_" + encryptedName + "_";
            PdfDocument document = new PdfDocument(new PdfReader(inPath));
            PdfEncryptedPayloadDocument encryptedDocument = document.GetEncryptedPayloadDocument();

            byte[]     encryptedDocumentBytes = encryptedDocument.GetDocumentBytes();
            FileStream fos = new FileStream(outPath, FileMode.Create);

            fos.Write(encryptedDocumentBytes);
            fos.Dispose();
            document.Close();
            PdfEncryptedPayload ep = encryptedDocument.GetEncryptedPayload();

            NUnit.Framework.Assert.AreEqual(PdfEncryptedPayloadFileSpecFactory.GenerateFileDisplay(ep), encryptedDocument
                                            .GetName());
            if (password != null)
            {
                NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outPath, cmpPath, destinationFolder, diff
                                                                                 , password, password));
            }
            else
            {
                RandomAccessFileOrArray raf = new RandomAccessFileOrArray(new RandomAccessSourceFactory().CreateBestSource
                                                                              (cmpPath));
                byte[] cmpBytes = new byte[(int)raf.Length()];
                raf.ReadFully(cmpBytes);
                raf.Close();
                NUnit.Framework.Assert.AreEqual(cmpBytes, encryptedDocumentBytes);
            }
        }
예제 #3
0
        public virtual void SeekTest()
        {
            RandomAccessFileOrArray raf = new RandomAccessFileOrArray(new RandomAccessSourceFactory().CreateBestSource
                                                                          (SOURCE_FOLDER + "NotoSansCJKjp-Bold.otf"));

            byte[] cff = new byte[16014190];
            try {
                raf.Seek(283192);
                raf.ReadFully(cff);
            }
            finally {
                raf.Close();
            }
            CFFFont cffFont = new CFFFont(cff);

            cffFont.Seek(0);
            // Get int (bin 0000 0001 0000 0000  0000 0100 0000 0011)
            NUnit.Framework.Assert.AreEqual(16778243, cffFont.GetInt());
            cffFont.Seek(0);
            // Gets the first short (bin 0000 0001 0000 0000)
            NUnit.Framework.Assert.AreEqual(256, cffFont.GetShort());
            cffFont.Seek(2);
            // Gets the second short (bin 0000 0100 0000 0011)
            NUnit.Framework.Assert.AreEqual(1027, cffFont.GetShort());
        }
예제 #4
0
        private String ReadString(int n)
        {
            byte[] b = new byte[n];
            input.ReadFully(b);
            int k;

            for (k = 0; k < b.Length; ++k)
            {
                if (b[k] == 0)
                {
                    break;
                }
            }
            return(iText.IO.Util.JavaUtil.GetStringForBytes(b, 0, k, "ISO-8859-1"));
        }
예제 #5
0
        internal static byte[] ReadFontBytesFromPath(String path)
        {
            RandomAccessFileOrArray raf = new RandomAccessFileOrArray(new RandomAccessSourceFactory().CreateBestSource
                                                                          (path));
            int bufLen = (int)raf.Length();

            if (bufLen < raf.Length())
            {
                throw new iText.IO.IOException(MessageFormatUtil.Format("Source data from \"{0}\" is bigger than byte array can hold."
                                                                        , path));
            }
            byte[] buf = new byte[bufLen];
            raf.ReadFully(buf);
            return(buf);
        }
예제 #6
0
        public virtual void GetPositionTest()
        {
            RandomAccessFileOrArray raf = new RandomAccessFileOrArray(new RandomAccessSourceFactory().CreateBestSource
                                                                          (SOURCE_FOLDER + "NotoSansCJKjp-Bold.otf"));

            byte[] cff = new byte[16014190];
            try {
                raf.Seek(283192);
                raf.ReadFully(cff);
            }
            finally {
                raf.Close();
            }
            CFFFont cffFont = new CFFFont(cff);

            cffFont.Seek(0);
            NUnit.Framework.Assert.AreEqual(0, cffFont.GetPosition());
            cffFont.Seek(16);
            NUnit.Framework.Assert.AreEqual(16, cffFont.GetPosition());
        }
예제 #7
0
        public virtual byte[] GetFullFont()
        {
            RandomAccessFileOrArray rf2 = null;

            try {
                rf2 = raf.CreateView();
                byte[] b = new byte[(int)rf2.Length()];
                rf2.ReadFully(b);
                return(b);
            }
            finally {
                try {
                    if (rf2 != null)
                    {
                        rf2.Close();
                    }
                }
                catch (Exception) {
                }
            }
        }
예제 #8
0
        /// <summary>
        /// Reads a page from a TIFF image.
        /// by direct byte copying. It's faster but may not work
        /// every time
        /// </summary>
        /// <param name="s">the file source</param>
        /// <param name="page">the page to get. The first page is 1</param>
        /// <param name="direct">for single strip, CCITT images, generate the image</param>
        /// <returns>the  Image </returns>
        public static Image GetTiffImage(RandomAccessFileOrArray s, int page, bool direct)
        {
            if (page < 1)
            {
                throw new InvalidOperationException("The page number must be >= 1.");
            }

            var dir = new TiffDirectory(s, page - 1);

            if (dir.IsTagPresent(TiffConstants.TIFFTAG_TILEWIDTH))
            {
                throw new InvalidOperationException("Tiles are not supported.");
            }

            var compression = (int)dir.GetFieldAsLong(TiffConstants.TIFFTAG_COMPRESSION);

            switch (compression)
            {
            case TiffConstants.COMPRESSION_CCITTRLEW:
            case TiffConstants.COMPRESSION_CCITTRLE:
            case TiffConstants.COMPRESSION_CCITTFAX3:
            case TiffConstants.COMPRESSION_CCITTFAX4:
                break;

            default:
                return(GetTiffImageColor(dir, s));
            }
            float rotation = 0;

            if (dir.IsTagPresent(TiffConstants.TIFFTAG_ORIENTATION))
            {
                var rot = (int)dir.GetFieldAsLong(TiffConstants.TIFFTAG_ORIENTATION);
                if (rot == TiffConstants.ORIENTATION_BOTRIGHT || rot == TiffConstants.ORIENTATION_BOTLEFT)
                {
                    rotation = (float)Math.PI;
                }
                else if (rot == TiffConstants.ORIENTATION_LEFTTOP || rot == TiffConstants.ORIENTATION_LEFTBOT)
                {
                    rotation = (float)(Math.PI / 2.0);
                }
                else if (rot == TiffConstants.ORIENTATION_RIGHTTOP || rot == TiffConstants.ORIENTATION_RIGHTBOT)
                {
                    rotation = -(float)(Math.PI / 2.0);
                }
            }

            Image img            = null;
            long  tiffT4Options  = 0;
            long  tiffT6Options  = 0;
            var   fillOrder      = 1;
            var   h              = (int)dir.GetFieldAsLong(TiffConstants.TIFFTAG_IMAGELENGTH);
            var   w              = (int)dir.GetFieldAsLong(TiffConstants.TIFFTAG_IMAGEWIDTH);
            var   dpiX           = 0;
            var   dpiY           = 0;
            float xyRatio        = 0;
            var   resolutionUnit = TiffConstants.RESUNIT_INCH;

            if (dir.IsTagPresent(TiffConstants.TIFFTAG_RESOLUTIONUNIT))
            {
                resolutionUnit = (int)dir.GetFieldAsLong(TiffConstants.TIFFTAG_RESOLUTIONUNIT);
            }

            dpiX = getDpi(dir.GetField(TiffConstants.TIFFTAG_XRESOLUTION), resolutionUnit);
            dpiY = getDpi(dir.GetField(TiffConstants.TIFFTAG_YRESOLUTION), resolutionUnit);
            if (resolutionUnit == TiffConstants.RESUNIT_NONE)
            {
                if (dpiY != 0)
                {
                    xyRatio = dpiX / (float)dpiY;
                }

                dpiX = 0;
                dpiY = 0;
            }
            var rowsStrip = h;

            if (dir.IsTagPresent(TiffConstants.TIFFTAG_ROWSPERSTRIP))
            {
                rowsStrip = (int)dir.GetFieldAsLong(TiffConstants.TIFFTAG_ROWSPERSTRIP);
            }

            if (rowsStrip <= 0 || rowsStrip > h)
            {
                rowsStrip = h;
            }

            var offset = getArrayLongShort(dir, TiffConstants.TIFFTAG_STRIPOFFSETS);
            var size   = getArrayLongShort(dir, TiffConstants.TIFFTAG_STRIPBYTECOUNTS);

            if ((size == null || (size.Length == 1 && (size[0] == 0 || size[0] + offset[0] > s.Length))) && h == rowsStrip)
            { // some TIFF producers are really lousy, so...
                size = new long[] { s.Length - (int)offset[0] };
            }
            var reverse        = false;
            var fillOrderField = dir.GetField(TiffConstants.TIFFTAG_FILLORDER);

            if (fillOrderField != null)
            {
                fillOrder = fillOrderField.GetAsInt(0);
            }

            reverse = (fillOrder == TiffConstants.FILLORDER_LSB2MSB);
            var paramsn = 0;

            if (dir.IsTagPresent(TiffConstants.TIFFTAG_PHOTOMETRIC))
            {
                var photo = dir.GetFieldAsLong(TiffConstants.TIFFTAG_PHOTOMETRIC);
                if (photo == TiffConstants.PHOTOMETRIC_MINISBLACK)
                {
                    paramsn |= Element.CCITT_BLACKIS1;
                }
            }
            var imagecomp = 0;

            switch (compression)
            {
            case TiffConstants.COMPRESSION_CCITTRLEW:
            case TiffConstants.COMPRESSION_CCITTRLE:
                imagecomp = Element.CCITTG3_1D;
                paramsn  |= Element.CCITT_ENCODEDBYTEALIGN | Element.CCITT_ENDOFBLOCK;
                break;

            case TiffConstants.COMPRESSION_CCITTFAX3:
                imagecomp = Element.CCITTG3_1D;
                paramsn  |= Element.CCITT_ENDOFLINE | Element.CCITT_ENDOFBLOCK;
                var t4OptionsField = dir.GetField(TiffConstants.TIFFTAG_GROUP3OPTIONS);
                if (t4OptionsField != null)
                {
                    tiffT4Options = t4OptionsField.GetAsLong(0);
                    if ((tiffT4Options & TiffConstants.GROUP3OPT_2DENCODING) != 0)
                    {
                        imagecomp = Element.CCITTG3_2D;
                    }

                    if ((tiffT4Options & TiffConstants.GROUP3OPT_FILLBITS) != 0)
                    {
                        paramsn |= Element.CCITT_ENCODEDBYTEALIGN;
                    }
                }
                break;

            case TiffConstants.COMPRESSION_CCITTFAX4:
                imagecomp = Element.CCITTG4;
                var t6OptionsField = dir.GetField(TiffConstants.TIFFTAG_GROUP4OPTIONS);
                if (t6OptionsField != null)
                {
                    tiffT6Options = t6OptionsField.GetAsLong(0);
                }

                break;
            }
            if (direct && rowsStrip == h)
            { //single strip, direct
                var im = new byte[(int)size[0]];
                s.Seek(offset[0]);
                s.ReadFully(im);
                img          = Image.GetInstance(w, h, false, imagecomp, paramsn, im);
                img.Inverted = true;
            }
            else
            {
                var rowsLeft = h;
                var g4       = new Ccittg4Encoder(w);
                for (var k = 0; k < offset.Length; ++k)
                {
                    var im = new byte[(int)size[k]];
                    s.Seek(offset[k]);
                    s.ReadFully(im);
                    var height  = Math.Min(rowsStrip, rowsLeft);
                    var decoder = new TiffFaxDecoder(fillOrder, w, height);
                    var outBuf  = new byte[(w + 7) / 8 * height];
                    switch (compression)
                    {
                    case TiffConstants.COMPRESSION_CCITTRLEW:
                    case TiffConstants.COMPRESSION_CCITTRLE:
                        decoder.Decode1D(outBuf, im, 0, height);
                        g4.Fax4Encode(outBuf, height);
                        break;

                    case TiffConstants.COMPRESSION_CCITTFAX3:
                        try
                        {
                            decoder.Decode2D(outBuf, im, 0, height, tiffT4Options);
                        }
                        catch (Exception e)
                        {
                            // let's flip the fill bits and try again...
                            tiffT4Options ^= TiffConstants.GROUP3OPT_FILLBITS;
                            try
                            {
                                decoder.Decode2D(outBuf, im, 0, height, tiffT4Options);
                            }
                            catch
                            {
                                throw e;
                            }
                        }
                        g4.Fax4Encode(outBuf, height);
                        break;

                    case TiffConstants.COMPRESSION_CCITTFAX4:
                        decoder.DecodeT6(outBuf, im, 0, height, tiffT6Options);
                        g4.Fax4Encode(outBuf, height);
                        break;
                    }
                    rowsLeft -= rowsStrip;
                }
                var g4Pic = g4.Close();
                img = Image.GetInstance(w, h, false, Element.CCITTG4, paramsn & Element.CCITT_BLACKIS1, g4Pic);
            }
            img.SetDpi(dpiX, dpiY);
            img.XyRatio = xyRatio;
            if (dir.IsTagPresent(TiffConstants.TIFFTAG_ICCPROFILE))
            {
                try
                {
                    var fd      = dir.GetField(TiffConstants.TIFFTAG_ICCPROFILE);
                    var iccProf = IccProfile.GetInstance(fd.GetAsBytes());
                    if (iccProf.NumComponents == 1)
                    {
                        img.TagIcc = iccProf;
                    }
                }
                catch
                {
                    //empty
                }
            }
            img.OriginalType = Image.ORIGINAL_TIFF;
            if (rotation.ApproxNotEqual(0))
            {
                img.InitialRotation = rotation;
            }

            return(img);
        }
예제 #9
0
        /** Reads a page from a TIFF image.
        * @param s the file source
        * @param page the page to get. The first page is 1
        * @param direct for single strip, CCITT images, generate the image
        * by direct byte copying. It's faster but may not work
        * every time
        * @return the <CODE>Image</CODE>
        */
        public static Image GetTiffImage(RandomAccessFileOrArray s, int page, bool direct)
        {
            if (page < 1)
                throw new ArgumentException("The page number must be >= 1.");
            TIFFDirectory dir = new TIFFDirectory(s, page - 1);
            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_TILEWIDTH))
                throw new ArgumentException("Tiles are not supported.");
            int compression = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_COMPRESSION);
            switch (compression) {
                case TIFFConstants.COMPRESSION_CCITTRLEW:
                case TIFFConstants.COMPRESSION_CCITTRLE:
                case TIFFConstants.COMPRESSION_CCITTFAX3:
                case TIFFConstants.COMPRESSION_CCITTFAX4:
                    break;
                default:
                    return GetTiffImageColor(dir, s);
            }
            float rotation = 0;
            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_ORIENTATION)) {
                int rot = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_ORIENTATION);
                if (rot == TIFFConstants.ORIENTATION_BOTRIGHT || rot == TIFFConstants.ORIENTATION_BOTLEFT)
                    rotation = (float)Math.PI;
                else if (rot == TIFFConstants.ORIENTATION_LEFTTOP || rot == TIFFConstants.ORIENTATION_LEFTBOT)
                    rotation = (float)(Math.PI / 2.0);
                else if (rot == TIFFConstants.ORIENTATION_RIGHTTOP || rot == TIFFConstants.ORIENTATION_RIGHTBOT)
                    rotation = -(float)(Math.PI / 2.0);
            }

            Image img = null;
            long tiffT4Options = 0;
            long tiffT6Options = 0;
            int fillOrder = 1;
            int h = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_IMAGELENGTH);
            int w = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_IMAGEWIDTH);
            int dpiX = 0;
            int dpiY = 0;
            float XYRatio = 0;
            int resolutionUnit = TIFFConstants.RESUNIT_INCH;
            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_RESOLUTIONUNIT))
                resolutionUnit = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_RESOLUTIONUNIT);
            dpiX = GetDpi(dir.GetField(TIFFConstants.TIFFTAG_XRESOLUTION), resolutionUnit);
            dpiY = GetDpi(dir.GetField(TIFFConstants.TIFFTAG_YRESOLUTION), resolutionUnit);
            if (resolutionUnit == TIFFConstants.RESUNIT_NONE) {
                if (dpiY != 0)
                    XYRatio = (float)dpiX / (float)dpiY;
                dpiX = 0;
                dpiY = 0;
            }
            int rowsStrip = h;
            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_ROWSPERSTRIP))
                rowsStrip = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_ROWSPERSTRIP);
            if (rowsStrip <= 0 || rowsStrip > h)
                rowsStrip = h;
            long[] offset = GetArrayLongShort(dir, TIFFConstants.TIFFTAG_STRIPOFFSETS);
            long[] size = GetArrayLongShort(dir, TIFFConstants.TIFFTAG_STRIPBYTECOUNTS);
            if ((size == null || (size.Length == 1 && (size[0] == 0 || size[0] + offset[0] > s.Length))) && h == rowsStrip) { // some TIFF producers are really lousy, so...
                size = new long[]{s.Length - (int)offset[0]};
            }
            bool reverse = false;
            TIFFField fillOrderField =  dir.GetField(TIFFConstants.TIFFTAG_FILLORDER);
            if (fillOrderField != null)
                fillOrder = fillOrderField.GetAsInt(0);
            reverse = (fillOrder == TIFFConstants.FILLORDER_LSB2MSB);
            int paramsn = 0;
            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_PHOTOMETRIC)) {
                long photo = dir.GetFieldAsLong(TIFFConstants.TIFFTAG_PHOTOMETRIC);
                if (photo == TIFFConstants.PHOTOMETRIC_MINISBLACK)
                    paramsn |= Image.CCITT_BLACKIS1;
            }
            int imagecomp = 0;
            switch (compression) {
                case TIFFConstants.COMPRESSION_CCITTRLEW:
                case TIFFConstants.COMPRESSION_CCITTRLE:
                    imagecomp = Image.CCITTG3_1D;
                    paramsn |= Image.CCITT_ENCODEDBYTEALIGN | Image.CCITT_ENDOFBLOCK;
                    break;
                case TIFFConstants.COMPRESSION_CCITTFAX3:
                    imagecomp = Image.CCITTG3_1D;
                    paramsn |= Image.CCITT_ENDOFLINE | Image.CCITT_ENDOFBLOCK;
                    TIFFField t4OptionsField = dir.GetField(TIFFConstants.TIFFTAG_GROUP3OPTIONS);
                    if (t4OptionsField != null) {
                        tiffT4Options = t4OptionsField.GetAsLong(0);
                    if ((tiffT4Options & TIFFConstants.GROUP3OPT_2DENCODING) != 0)
                        imagecomp = Image.CCITTG3_2D;
                    if ((tiffT4Options & TIFFConstants.GROUP3OPT_FILLBITS) != 0)
                        paramsn |= Image.CCITT_ENCODEDBYTEALIGN;
                    }
                    break;
                case TIFFConstants.COMPRESSION_CCITTFAX4:
                    imagecomp = Image.CCITTG4;
                    TIFFField t6OptionsField = dir.GetField(TIFFConstants.TIFFTAG_GROUP4OPTIONS);
                    if (t6OptionsField != null)
                        tiffT6Options = t6OptionsField.GetAsLong(0);
                    break;
            }
            if (direct && rowsStrip == h) { //single strip, direct
                byte[] im = new byte[(int)size[0]];
                s.Seek(offset[0]);
                s.ReadFully(im);
                img = Image.GetInstance(w, h, false, imagecomp, paramsn, im);
                img.Inverted = true;
            }
            else {
                int rowsLeft = h;
                CCITTG4Encoder g4 = new CCITTG4Encoder(w);
                for (int k = 0; k < offset.Length; ++k) {
                    byte[] im = new byte[(int)size[k]];
                    s.Seek(offset[k]);
                    s.ReadFully(im);
                    int height = Math.Min(rowsStrip, rowsLeft);
                    TIFFFaxDecoder decoder = new TIFFFaxDecoder(fillOrder, w, height);
                    byte[] outBuf = new byte[(w + 7) / 8 * height];
                    switch (compression) {
                        case TIFFConstants.COMPRESSION_CCITTRLEW:
                        case TIFFConstants.COMPRESSION_CCITTRLE:
                            decoder.Decode1D(outBuf, im, 0, height);
                            g4.Fax4Encode(outBuf, height);
                            break;
                        case TIFFConstants.COMPRESSION_CCITTFAX3:
                            try {
                                decoder.Decode2D(outBuf, im, 0, height, tiffT4Options);
                            }
                            catch (Exception e) {
                                // let's flip the fill bits and try again...
                                tiffT4Options ^= TIFFConstants.GROUP3OPT_FILLBITS;
                                try {
                                    decoder.Decode2D(outBuf, im, 0, height, tiffT4Options);
                                }
                                catch {
                                    throw e;
                                }
                            }
                            g4.Fax4Encode(outBuf, height);
                            break;
                        case TIFFConstants.COMPRESSION_CCITTFAX4:
                            decoder.DecodeT6(outBuf, im, 0, height, tiffT6Options);
                            g4.Fax4Encode(outBuf, height);
                            break;
                    }
                    rowsLeft -= rowsStrip;
                }
                byte[] g4pic = g4.Close();
                img = Image.GetInstance(w, h, false, Image.CCITTG4, paramsn & Image.CCITT_BLACKIS1, g4pic);
            }
            img.SetDpi(dpiX, dpiY);
            img.XYRatio = XYRatio;
            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_ICCPROFILE)) {
                try {
                    TIFFField fd = dir.GetField(TIFFConstants.TIFFTAG_ICCPROFILE);
                    ICC_Profile icc_prof = ICC_Profile.GetInstance(fd.GetAsBytes());
                    if (icc_prof.NumComponents == 1)
                        img.TagICC = icc_prof;
                }
                catch {
                    //empty
                }
            }
            img.OriginalType = Image.ORIGINAL_TIFF;
            if (rotation != 0)
                img.InitialRotation = rotation;
            return img;
        }
예제 #10
0
        private void Initialize(RandomAccessFileOrArray stream)
        {
            long nextTagOffset = 0L;
            long maxOffset = (long)stream.Length;
            int  i, j;

            IFDOffset = stream.FilePointer;

            numEntries = ReadUnsignedShort(stream);
            fields     = new TIFFField[numEntries];

            for (i = 0; (i < numEntries) && (nextTagOffset < maxOffset); i++)
            {
                int  tag        = ReadUnsignedShort(stream);
                int  type       = ReadUnsignedShort(stream);
                int  count      = (int)(ReadUnsignedInt(stream));
                bool processTag = true;

                // The place to return to to read the next tag
                nextTagOffset = stream.FilePointer + 4;

                try {
                    // If the tag data can't fit in 4 bytes, the next 4 bytes
                    // contain the starting offset of the data
                    if (count * sizeOfType[type] > 4)
                    {
                        long valueOffset = ReadUnsignedInt(stream);

                        // bounds check offset for EOF
                        if (valueOffset < maxOffset)
                        {
                            stream.Seek(valueOffset);
                        }
                        else
                        {
                            // bad offset pointer .. skip tag
                            processTag = false;
                        }
                    }
                } catch (ArgumentOutOfRangeException) {
                    // if the data type is unknown we should skip this TIFF Field
                    processTag = false;
                }

                if (processTag)
                {
                    fieldIndex[tag] = i;
                    Object obj = null;

                    switch (type)
                    {
                    case TIFFField.TIFF_BYTE:
                    case TIFFField.TIFF_SBYTE:
                    case TIFFField.TIFF_UNDEFINED:
                    case TIFFField.TIFF_ASCII:
                        byte[] bvalues = new byte[count];
                        stream.ReadFully(bvalues, 0, count);

                        if (type == TIFFField.TIFF_ASCII)
                        {
                            // Can be multiple strings
                            int       index = 0, prevIndex = 0;
                            ArrayList v = new ArrayList();

                            while (index < count)
                            {
                                while ((index < count) && (bvalues[index++] != 0))
                                {
                                    ;
                                }

                                // When we encountered zero, means one string has ended
                                char[] cht = new char[index - prevIndex];
                                Array.Copy(bvalues, prevIndex, cht, 0, index - prevIndex);
                                v.Add(new String(cht));
                                prevIndex = index;
                            }

                            count = v.Count;
                            String[] strings = new String[count];
                            for (int c = 0; c < count; c++)
                            {
                                strings[c] = (String)v[c];
                            }

                            obj = strings;
                        }
                        else
                        {
                            obj = bvalues;
                        }

                        break;

                    case TIFFField.TIFF_SHORT:
                        char[] cvalues = new char[count];
                        for (j = 0; j < count; j++)
                        {
                            cvalues[j] = (char)(ReadUnsignedShort(stream));
                        }
                        obj = cvalues;
                        break;

                    case TIFFField.TIFF_LONG:
                        long[] lvalues = new long[count];
                        for (j = 0; j < count; j++)
                        {
                            lvalues[j] = ReadUnsignedInt(stream);
                        }
                        obj = lvalues;
                        break;

                    case TIFFField.TIFF_RATIONAL:
                        long[][] llvalues = new long[count][];
                        for (j = 0; j < count; j++)
                        {
                            long v0 = ReadUnsignedInt(stream);
                            long v1 = ReadUnsignedInt(stream);
                            llvalues[j] = new long[] { v0, v1 };
                        }
                        obj = llvalues;
                        break;

                    case TIFFField.TIFF_SSHORT:
                        short[] svalues = new short[count];
                        for (j = 0; j < count; j++)
                        {
                            svalues[j] = ReadShort(stream);
                        }
                        obj = svalues;
                        break;

                    case TIFFField.TIFF_SLONG:
                        int[] ivalues = new int[count];
                        for (j = 0; j < count; j++)
                        {
                            ivalues[j] = ReadInt(stream);
                        }
                        obj = ivalues;
                        break;

                    case TIFFField.TIFF_SRATIONAL:
                        int[,] iivalues = new int[count, 2];
                        for (j = 0; j < count; j++)
                        {
                            iivalues[j, 0] = ReadInt(stream);
                            iivalues[j, 1] = ReadInt(stream);
                        }
                        obj = iivalues;
                        break;

                    case TIFFField.TIFF_FLOAT:
                        float[] fvalues = new float[count];
                        for (j = 0; j < count; j++)
                        {
                            fvalues[j] = ReadFloat(stream);
                        }
                        obj = fvalues;
                        break;

                    case TIFFField.TIFF_DOUBLE:
                        double[] dvalues = new double[count];
                        for (j = 0; j < count; j++)
                        {
                            dvalues[j] = ReadDouble(stream);
                        }
                        obj = dvalues;
                        break;

                    default:
                        break;
                    }

                    fields[i] = new TIFFField(tag, type, count, obj);
                }

                stream.Seek(nextTagOffset);
            }

            // Read the offset of the next IFD.
            try {
                nextIFDOffset = ReadUnsignedInt(stream);
            }
            catch {
                // broken tiffs may not have this pointer
                nextIFDOffset = 0;
            }
        }
예제 #11
0
        //  0 = n/a
        //  1 = byte
        //  2 = ascii
        //  3 = short
        //  4 = long
        //  5 = rational
        //  6 = sbyte
        //  7 = undefined
        //  8 = sshort
        //  9 = slong
        // 10 = srational
        // 11 = float
        // 12 = double
        /// <exception cref="System.IO.IOException"/>
        private void Initialize(RandomAccessFileOrArray stream)
        {
            long nextTagOffset = 0L;
            long maxOffset     = stream.Length();
            int  i;
            int  j;

            IFDOffset  = stream.GetPosition();
            numEntries = ReadUnsignedShort(stream);
            fields     = new TIFFField[numEntries];
            for (i = 0; i < numEntries && nextTagOffset < maxOffset; i++)
            {
                int  tag        = ReadUnsignedShort(stream);
                int  type       = ReadUnsignedShort(stream);
                int  count      = (int)ReadUnsignedInt(stream);
                bool processTag = true;
                // The place to return to to read the next tag
                nextTagOffset = stream.GetPosition() + 4;
                try {
                    // If the tag data can't fit in 4 bytes, the next 4 bytes
                    // contain the starting offset of the data
                    if (count * sizeOfType[type] > 4)
                    {
                        long valueOffset = ReadUnsignedInt(stream);
                        // bounds check offset for EOF
                        if (valueOffset < maxOffset)
                        {
                            stream.Seek(valueOffset);
                        }
                        else
                        {
                            // bad offset pointer .. skip tag
                            processTag = false;
                        }
                    }
                }
                catch (IndexOutOfRangeException) {
                    // if the data type is unknown we should skip this TIFF Field
                    processTag = false;
                }
                if (processTag)
                {
                    fieldIndex[tag] = i;
                    Object obj = null;
                    switch (type)
                    {
                    case TIFFField.TIFF_BYTE:
                    case TIFFField.TIFF_SBYTE:
                    case TIFFField.TIFF_UNDEFINED:
                    case TIFFField.TIFF_ASCII: {
                        byte[] bvalues = new byte[count];
                        stream.ReadFully(bvalues, 0, count);
                        if (type == TIFFField.TIFF_ASCII)
                        {
                            // Can be multiple strings
                            int            index     = 0;
                            int            prevIndex = 0;
                            IList <String> v         = new List <String>();
                            while (index < count)
                            {
                                while (index < count && bvalues[index++] != 0)
                                {
                                }
                                // When we encountered zero, means one string has ended
                                v.Add(iText.IO.Util.JavaUtil.GetStringForBytes(bvalues, prevIndex, (index - prevIndex)));
                                prevIndex = index;
                            }
                            count = v.Count;
                            String[] strings = new String[count];
                            for (int c = 0; c < count; c++)
                            {
                                strings[c] = v[c];
                            }
                            obj = strings;
                        }
                        else
                        {
                            obj = bvalues;
                        }
                        break;
                    }

                    case TIFFField.TIFF_SHORT: {
                        char[] cvalues = new char[count];
                        for (j = 0; j < count; j++)
                        {
                            cvalues[j] = (char)ReadUnsignedShort(stream);
                        }
                        obj = cvalues;
                        break;
                    }

                    case TIFFField.TIFF_LONG: {
                        long[] lvalues = new long[count];
                        for (j = 0; j < count; j++)
                        {
                            lvalues[j] = ReadUnsignedInt(stream);
                        }
                        obj = lvalues;
                        break;
                    }

                    case TIFFField.TIFF_RATIONAL: {
                        long[][] llvalues = new long[count][];
                        for (j = 0; j < count; j++)
                        {
                            llvalues[j]    = new long[2];
                            llvalues[j][0] = ReadUnsignedInt(stream);
                            llvalues[j][1] = ReadUnsignedInt(stream);
                        }
                        obj = llvalues;
                        break;
                    }

                    case TIFFField.TIFF_SSHORT: {
                        short[] svalues = new short[count];
                        for (j = 0; j < count; j++)
                        {
                            svalues[j] = ReadShort(stream);
                        }
                        obj = svalues;
                        break;
                    }

                    case TIFFField.TIFF_SLONG: {
                        int[] ivalues = new int[count];
                        for (j = 0; j < count; j++)
                        {
                            ivalues[j] = ReadInt(stream);
                        }
                        obj = ivalues;
                        break;
                    }

                    case TIFFField.TIFF_SRATIONAL: {
                        int[][] iivalues = new int[count][];
                        for (j = 0; j < count; j++)
                        {
                            iivalues[j]    = new int[2];
                            iivalues[j][0] = ReadInt(stream);
                            iivalues[j][1] = ReadInt(stream);
                        }
                        obj = iivalues;
                        break;
                    }

                    case TIFFField.TIFF_FLOAT: {
                        float[] fvalues = new float[count];
                        for (j = 0; j < count; j++)
                        {
                            fvalues[j] = ReadFloat(stream);
                        }
                        obj = fvalues;
                        break;
                    }

                    case TIFFField.TIFF_DOUBLE: {
                        double[] dvalues = new double[count];
                        for (j = 0; j < count; j++)
                        {
                            dvalues[j] = ReadDouble(stream);
                        }
                        obj = dvalues;
                        break;
                    }

                    default: {
                        break;
                    }
                    }
                    fields[i] = new TIFFField(tag, type, count, obj);
                }
                stream.Seek(nextTagOffset);
            }
            // Read the offset of the next IFD.
            try {
                nextIFDOffset = ReadUnsignedInt(stream);
            }
            catch (Exception) {
                // broken tiffs may not have this pointer
                nextIFDOffset = 0;
            }
        }
예제 #12
0
        private static void ProcessTiffImage(RandomAccessFileOrArray s, TiffImageHelper.TiffParameters tiff)
        {
            bool recoverFromImageError = tiff.image.IsRecoverFromImageError();
            int  page   = tiff.image.GetPage();
            bool direct = tiff.image.IsDirect();

            if (page < 1)
            {
                throw new iText.IO.IOException(iText.IO.IOException.PageNumberMustBeGtEq1);
            }
            try {
                TIFFDirectory dir = new TIFFDirectory(s, page - 1);
                if (dir.IsTagPresent(TIFFConstants.TIFFTAG_TILEWIDTH))
                {
                    throw new iText.IO.IOException(iText.IO.IOException.TilesAreNotSupported);
                }
                int compression = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_COMPRESSION);
                switch (compression)
                {
                case TIFFConstants.COMPRESSION_CCITTRLEW:
                case TIFFConstants.COMPRESSION_CCITTRLE:
                case TIFFConstants.COMPRESSION_CCITTFAX3:
                case TIFFConstants.COMPRESSION_CCITTFAX4: {
                    break;
                }

                default: {
                    ProcessTiffImageColor(dir, s, tiff);
                    return;
                }
                }
                float rotation = 0;
                if (dir.IsTagPresent(TIFFConstants.TIFFTAG_ORIENTATION))
                {
                    int rot = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_ORIENTATION);
                    if (rot == TIFFConstants.ORIENTATION_BOTRIGHT || rot == TIFFConstants.ORIENTATION_BOTLEFT)
                    {
                        rotation = (float)Math.PI;
                    }
                    else
                    {
                        if (rot == TIFFConstants.ORIENTATION_LEFTTOP || rot == TIFFConstants.ORIENTATION_LEFTBOT)
                        {
                            rotation = (float)(Math.PI / 2.0);
                        }
                        else
                        {
                            if (rot == TIFFConstants.ORIENTATION_RIGHTTOP || rot == TIFFConstants.ORIENTATION_RIGHTBOT)
                            {
                                rotation = -(float)(Math.PI / 2.0);
                            }
                        }
                    }
                }
                long  tiffT4Options  = 0;
                long  tiffT6Options  = 0;
                int   fillOrder      = 1;
                int   h              = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_IMAGELENGTH);
                int   w              = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_IMAGEWIDTH);
                float XYRatio        = 0;
                int   resolutionUnit = TIFFConstants.RESUNIT_INCH;
                if (dir.IsTagPresent(TIFFConstants.TIFFTAG_RESOLUTIONUNIT))
                {
                    resolutionUnit = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_RESOLUTIONUNIT);
                }
                int dpiX = GetDpi(dir.GetField(TIFFConstants.TIFFTAG_XRESOLUTION), resolutionUnit);
                int dpiY = GetDpi(dir.GetField(TIFFConstants.TIFFTAG_YRESOLUTION), resolutionUnit);
                if (resolutionUnit == TIFFConstants.RESUNIT_NONE)
                {
                    if (dpiY != 0)
                    {
                        XYRatio = (float)dpiX / (float)dpiY;
                    }
                    dpiX = 0;
                    dpiY = 0;
                }
                int rowsStrip = h;
                if (dir.IsTagPresent(TIFFConstants.TIFFTAG_ROWSPERSTRIP))
                {
                    rowsStrip = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_ROWSPERSTRIP);
                }
                if (rowsStrip <= 0 || rowsStrip > h)
                {
                    rowsStrip = h;
                }
                long[] offset = GetArrayLongShort(dir, TIFFConstants.TIFFTAG_STRIPOFFSETS);
                long[] size   = GetArrayLongShort(dir, TIFFConstants.TIFFTAG_STRIPBYTECOUNTS);
                if ((size == null || (size.Length == 1 && (size[0] == 0 || size[0] + offset[0] > s.Length()))) && h == rowsStrip
                    )
                {
                    // some TIFF producers are really lousy, so...
                    size = new long[] { s.Length() - (int)offset[0] };
                }
                bool      reverse        = false;
                TIFFField fillOrderField = dir.GetField(TIFFConstants.TIFFTAG_FILLORDER);
                if (fillOrderField != null)
                {
                    fillOrder = fillOrderField.GetAsInt(0);
                }
                reverse = (fillOrder == TIFFConstants.FILLORDER_LSB2MSB);
                int parameters = 0;
                if (dir.IsTagPresent(TIFFConstants.TIFFTAG_PHOTOMETRIC))
                {
                    long photo = dir.GetFieldAsLong(TIFFConstants.TIFFTAG_PHOTOMETRIC);
                    if (photo == TIFFConstants.PHOTOMETRIC_MINISBLACK)
                    {
                        parameters |= RawImageData.CCITT_BLACKIS1;
                    }
                }
                int imagecomp = 0;
                switch (compression)
                {
                case TIFFConstants.COMPRESSION_CCITTRLEW:
                case TIFFConstants.COMPRESSION_CCITTRLE: {
                    imagecomp   = RawImageData.CCITTG3_1D;
                    parameters |= RawImageData.CCITT_ENCODEDBYTEALIGN | RawImageData.CCITT_ENDOFBLOCK;
                    break;
                }

                case TIFFConstants.COMPRESSION_CCITTFAX3: {
                    imagecomp   = RawImageData.CCITTG3_1D;
                    parameters |= RawImageData.CCITT_ENDOFLINE | RawImageData.CCITT_ENDOFBLOCK;
                    TIFFField t4OptionsField = dir.GetField(TIFFConstants.TIFFTAG_GROUP3OPTIONS);
                    if (t4OptionsField != null)
                    {
                        tiffT4Options = t4OptionsField.GetAsLong(0);
                        if ((tiffT4Options & TIFFConstants.GROUP3OPT_2DENCODING) != 0)
                        {
                            imagecomp = RawImageData.CCITTG3_2D;
                        }
                        if ((tiffT4Options & TIFFConstants.GROUP3OPT_FILLBITS) != 0)
                        {
                            parameters |= RawImageData.CCITT_ENCODEDBYTEALIGN;
                        }
                    }
                    break;
                }

                case TIFFConstants.COMPRESSION_CCITTFAX4: {
                    imagecomp = RawImageData.CCITTG4;
                    TIFFField t6OptionsField = dir.GetField(TIFFConstants.TIFFTAG_GROUP4OPTIONS);
                    if (t6OptionsField != null)
                    {
                        tiffT6Options = t6OptionsField.GetAsLong(0);
                    }
                    break;
                }
                }
                if (direct && rowsStrip == h)
                {
                    //single strip, direct
                    byte[] im = new byte[(int)size[0]];
                    s.Seek(offset[0]);
                    s.ReadFully(im);
                    RawImageHelper.UpdateRawImageParameters(tiff.image, w, h, false, imagecomp, parameters, im, null);
                    tiff.image.SetInverted(true);
                }
                else
                {
                    int            rowsLeft = h;
                    CCITTG4Encoder g4       = new CCITTG4Encoder(w);
                    for (int k = 0; k < offset.Length; ++k)
                    {
                        byte[] im = new byte[(int)size[k]];
                        s.Seek(offset[k]);
                        s.ReadFully(im);
                        int            height  = Math.Min(rowsStrip, rowsLeft);
                        TIFFFaxDecoder decoder = new TIFFFaxDecoder(fillOrder, w, height);
                        decoder.SetRecoverFromImageError(recoverFromImageError);
                        byte[] outBuf = new byte[(w + 7) / 8 * height];
                        switch (compression)
                        {
                        case TIFFConstants.COMPRESSION_CCITTRLEW:
                        case TIFFConstants.COMPRESSION_CCITTRLE: {
                            decoder.Decode1D(outBuf, im, 0, height);
                            g4.Fax4Encode(outBuf, height);
                            break;
                        }

                        case TIFFConstants.COMPRESSION_CCITTFAX3: {
                            try {
                                decoder.Decode2D(outBuf, im, 0, height, tiffT4Options);
                            }
                            catch (Exception e) {
                                // let's flip the fill bits and try again...
                                tiffT4Options ^= TIFFConstants.GROUP3OPT_FILLBITS;
                                try {
                                    decoder.Decode2D(outBuf, im, 0, height, tiffT4Options);
                                }
                                catch (Exception) {
                                    if (!recoverFromImageError)
                                    {
                                        throw e;
                                    }
                                    if (rowsStrip == 1)
                                    {
                                        throw e;
                                    }
                                    // repeat of reading the tiff directly (the if section of this if else structure)
                                    // copy pasted to avoid making a method with 10 tiff
                                    im = new byte[(int)size[0]];
                                    s.Seek(offset[0]);
                                    s.ReadFully(im);
                                    RawImageHelper.UpdateRawImageParameters(tiff.image, w, h, false, imagecomp, parameters, im, null);
                                    tiff.image.SetInverted(true);
                                    tiff.image.SetDpi(dpiX, dpiY);
                                    tiff.image.SetXYRatio(XYRatio);
                                    if (rotation != 0)
                                    {
                                        tiff.image.SetRotation(rotation);
                                    }
                                    return;
                                }
                            }
                            g4.Fax4Encode(outBuf, height);
                            break;
                        }

                        case TIFFConstants.COMPRESSION_CCITTFAX4: {
                            try {
                                decoder.DecodeT6(outBuf, im, 0, height, tiffT6Options);
                            }
                            catch (iText.IO.IOException e) {
                                if (!recoverFromImageError)
                                {
                                    throw;
                                }
                            }
                            g4.Fax4Encode(outBuf, height);
                            break;
                        }
                        }
                        rowsLeft -= rowsStrip;
                    }
                    byte[] g4pic = g4.Close();
                    RawImageHelper.UpdateRawImageParameters(tiff.image, w, h, false, RawImageData.CCITTG4, parameters & RawImageData
                                                            .CCITT_BLACKIS1, g4pic, null);
                }
                tiff.image.SetDpi(dpiX, dpiY);
                if (dir.IsTagPresent(TIFFConstants.TIFFTAG_ICCPROFILE))
                {
                    try {
                        TIFFField  fd       = dir.GetField(TIFFConstants.TIFFTAG_ICCPROFILE);
                        IccProfile icc_prof = IccProfile.GetInstance(fd.GetAsBytes());
                        if (icc_prof.GetNumComponents() == 1)
                        {
                            tiff.image.SetProfile(icc_prof);
                        }
                    }
                    catch (Exception) {
                    }
                }
                //empty
                if (rotation != 0)
                {
                    tiff.image.SetRotation(rotation);
                }
            }
            catch (Exception) {
                throw new iText.IO.IOException(iText.IO.IOException.CannotReadTiffImage);
            }
        }
예제 #13
0
        private static void ProcessTiffImageColor(TIFFDirectory dir, RandomAccessFileOrArray s, TiffImageHelper.TiffParameters
                                                  tiff)
        {
            try {
                int            compression = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_COMPRESSION);
                int            predictor   = 1;
                TIFFLZWDecoder lzwDecoder  = null;
                switch (compression)
                {
                case TIFFConstants.COMPRESSION_NONE:
                case TIFFConstants.COMPRESSION_LZW:
                case TIFFConstants.COMPRESSION_PACKBITS:
                case TIFFConstants.COMPRESSION_DEFLATE:
                case TIFFConstants.COMPRESSION_ADOBE_DEFLATE:
                case TIFFConstants.COMPRESSION_OJPEG:
                case TIFFConstants.COMPRESSION_JPEG: {
                    break;
                }

                default: {
                    throw new iText.IO.IOException(iText.IO.IOException.Compression1IsNotSupported).SetMessageParams(compression
                                                                                                                     );
                }
                }
                int photometric = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_PHOTOMETRIC);
                switch (photometric)
                {
                case TIFFConstants.PHOTOMETRIC_MINISWHITE:
                case TIFFConstants.PHOTOMETRIC_MINISBLACK:
                case TIFFConstants.PHOTOMETRIC_RGB:
                case TIFFConstants.PHOTOMETRIC_SEPARATED:
                case TIFFConstants.PHOTOMETRIC_PALETTE: {
                    break;
                }

                default: {
                    if (compression != TIFFConstants.COMPRESSION_OJPEG && compression != TIFFConstants.COMPRESSION_JPEG)
                    {
                        throw new iText.IO.IOException(iText.IO.IOException.Photometric1IsNotSupported).SetMessageParams(photometric
                                                                                                                         );
                    }
                    break;
                }
                }
                float rotation = 0;
                if (dir.IsTagPresent(TIFFConstants.TIFFTAG_ORIENTATION))
                {
                    int rot = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_ORIENTATION);
                    if (rot == TIFFConstants.ORIENTATION_BOTRIGHT || rot == TIFFConstants.ORIENTATION_BOTLEFT)
                    {
                        rotation = (float)Math.PI;
                    }
                    else
                    {
                        if (rot == TIFFConstants.ORIENTATION_LEFTTOP || rot == TIFFConstants.ORIENTATION_LEFTBOT)
                        {
                            rotation = (float)(Math.PI / 2.0);
                        }
                        else
                        {
                            if (rot == TIFFConstants.ORIENTATION_RIGHTTOP || rot == TIFFConstants.ORIENTATION_RIGHTBOT)
                            {
                                rotation = -(float)(Math.PI / 2.0);
                            }
                        }
                    }
                }
                if (dir.IsTagPresent(TIFFConstants.TIFFTAG_PLANARCONFIG) && dir.GetFieldAsLong(TIFFConstants.TIFFTAG_PLANARCONFIG
                                                                                               ) == TIFFConstants.PLANARCONFIG_SEPARATE)
                {
                    throw new iText.IO.IOException(iText.IO.IOException.PlanarImagesAreNotSupported);
                }
                int extraSamples = 0;
                if (dir.IsTagPresent(TIFFConstants.TIFFTAG_EXTRASAMPLES))
                {
                    extraSamples = 1;
                }
                int samplePerPixel = 1;
                if (dir.IsTagPresent(TIFFConstants.TIFFTAG_SAMPLESPERPIXEL))
                {
                    // 1,3,4
                    samplePerPixel = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_SAMPLESPERPIXEL);
                }
                int bitsPerSample = 1;
                if (dir.IsTagPresent(TIFFConstants.TIFFTAG_BITSPERSAMPLE))
                {
                    bitsPerSample = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_BITSPERSAMPLE);
                }
                switch (bitsPerSample)
                {
                case 1:
                case 2:
                case 4:
                case 8: {
                    break;
                }

                default: {
                    throw new iText.IO.IOException(iText.IO.IOException.BitsPerSample1IsNotSupported).SetMessageParams(bitsPerSample
                                                                                                                       );
                }
                }
                int h = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_IMAGELENGTH);
                int w = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_IMAGEWIDTH);
                int dpiX;
                int dpiY;
                int resolutionUnit = TIFFConstants.RESUNIT_INCH;
                if (dir.IsTagPresent(TIFFConstants.TIFFTAG_RESOLUTIONUNIT))
                {
                    resolutionUnit = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_RESOLUTIONUNIT);
                }
                dpiX = GetDpi(dir.GetField(TIFFConstants.TIFFTAG_XRESOLUTION), resolutionUnit);
                dpiY = GetDpi(dir.GetField(TIFFConstants.TIFFTAG_YRESOLUTION), resolutionUnit);
                int       fillOrder      = 1;
                TIFFField fillOrderField = dir.GetField(TIFFConstants.TIFFTAG_FILLORDER);
                if (fillOrderField != null)
                {
                    fillOrder = fillOrderField.GetAsInt(0);
                }
                bool reverse   = (fillOrder == TIFFConstants.FILLORDER_LSB2MSB);
                int  rowsStrip = h;
                if (dir.IsTagPresent(TIFFConstants.TIFFTAG_ROWSPERSTRIP))
                {
                    //another hack for broken tiffs
                    rowsStrip = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_ROWSPERSTRIP);
                }
                if (rowsStrip <= 0 || rowsStrip > h)
                {
                    rowsStrip = h;
                }
                long[] offset = GetArrayLongShort(dir, TIFFConstants.TIFFTAG_STRIPOFFSETS);
                long[] size   = GetArrayLongShort(dir, TIFFConstants.TIFFTAG_STRIPBYTECOUNTS);
                if ((size == null || (size.Length == 1 && (size[0] == 0 || size[0] + offset[0] > s.Length()))) && h == rowsStrip
                    )
                {
                    // some TIFF producers are really lousy, so...
                    size = new long[] { s.Length() - (int)offset[0] };
                }
                if (compression == TIFFConstants.COMPRESSION_LZW || compression == TIFFConstants.COMPRESSION_DEFLATE || compression
                    == TIFFConstants.COMPRESSION_ADOBE_DEFLATE)
                {
                    TIFFField predictorField = dir.GetField(TIFFConstants.TIFFTAG_PREDICTOR);
                    if (predictorField != null)
                    {
                        predictor = predictorField.GetAsInt(0);
                        if (predictor != 1 && predictor != 2)
                        {
                            throw new iText.IO.IOException(iText.IO.IOException.IllegalValueForPredictorInTiffFile);
                        }
                        if (predictor == 2 && bitsPerSample != 8)
                        {
                            throw new iText.IO.IOException(iText.IO.IOException._1BitSamplesAreNotSupportedForHorizontalDifferencingPredictor
                                                           ).SetMessageParams(bitsPerSample);
                        }
                    }
                }
                if (compression == TIFFConstants.COMPRESSION_LZW)
                {
                    lzwDecoder = new TIFFLZWDecoder(w, predictor, samplePerPixel);
                }
                int rowsLeft = h;
                ByteArrayOutputStream stream  = null;
                ByteArrayOutputStream mstream = null;
                DeflaterOutputStream  zip     = null;
                DeflaterOutputStream  mzip    = null;
                if (extraSamples > 0)
                {
                    mstream = new ByteArrayOutputStream();
                    mzip    = new DeflaterOutputStream(mstream);
                }
                CCITTG4Encoder g4 = null;
                if (bitsPerSample == 1 && samplePerPixel == 1 && photometric != TIFFConstants.PHOTOMETRIC_PALETTE)
                {
                    g4 = new CCITTG4Encoder(w);
                }
                else
                {
                    stream = new ByteArrayOutputStream();
                    if (compression != TIFFConstants.COMPRESSION_OJPEG && compression != TIFFConstants.COMPRESSION_JPEG)
                    {
                        zip = new DeflaterOutputStream(stream);
                    }
                }
                if (compression == TIFFConstants.COMPRESSION_OJPEG)
                {
                    // Assume that the TIFFTAG_JPEGIFBYTECOUNT tag is optional, since it's obsolete and
                    // is often missing
                    if ((!dir.IsTagPresent(TIFFConstants.TIFFTAG_JPEGIFOFFSET)))
                    {
                        throw new iText.IO.IOException(iText.IO.IOException.MissingTagsForOjpegCompression);
                    }
                    int jpegOffset = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_JPEGIFOFFSET);
                    int jpegLength = (int)s.Length() - jpegOffset;
                    if (dir.IsTagPresent(TIFFConstants.TIFFTAG_JPEGIFBYTECOUNT))
                    {
                        jpegLength = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_JPEGIFBYTECOUNT) + (int)size[0];
                    }
                    byte[] jpeg           = new byte[Math.Min(jpegLength, (int)s.Length() - jpegOffset)];
                    int    posFilePointer = (int)s.GetPosition();
                    posFilePointer += jpegOffset;
                    s.Seek(posFilePointer);
                    s.ReadFully(jpeg);
                    tiff.image.data = jpeg;
                    tiff.image.SetOriginalType(ImageType.JPEG);
                    JpegImageHelper.ProcessImage(tiff.image);
                    tiff.jpegProcessing = true;
                }
                else
                {
                    if (compression == TIFFConstants.COMPRESSION_JPEG)
                    {
                        if (size.Length > 1)
                        {
                            throw new iText.IO.IOException(iText.IO.IOException.CompressionJpegIsOnlySupportedWithASingleStripThisImageHas1Strips
                                                           ).SetMessageParams(size.Length);
                        }
                        byte[] jpeg = new byte[(int)size[0]];
                        s.Seek(offset[0]);
                        s.ReadFully(jpeg);
                        // if quantization and/or Huffman tables are stored separately in the tiff,
                        // we need to add them to the jpeg data
                        TIFFField jpegtables = dir.GetField(TIFFConstants.TIFFTAG_JPEGTABLES);
                        if (jpegtables != null)
                        {
                            byte[] temp        = jpegtables.GetAsBytes();
                            int    tableoffset = 0;
                            int    tablelength = temp.Length;
                            // remove FFD8 from start
                            if (temp[0] == (byte)0xFF && temp[1] == (byte)0xD8)
                            {
                                tableoffset  = 2;
                                tablelength -= 2;
                            }
                            // remove FFD9 from end
                            if (temp[temp.Length - 2] == (byte)0xFF && temp[temp.Length - 1] == (byte)0xD9)
                            {
                                tablelength -= 2;
                            }
                            byte[] tables = new byte[tablelength];
                            System.Array.Copy(temp, tableoffset, tables, 0, tablelength);
                            // TODO insert after JFIF header, instead of at the start
                            byte[] jpegwithtables = new byte[jpeg.Length + tables.Length];
                            System.Array.Copy(jpeg, 0, jpegwithtables, 0, 2);
                            System.Array.Copy(tables, 0, jpegwithtables, 2, tables.Length);
                            System.Array.Copy(jpeg, 2, jpegwithtables, tables.Length + 2, jpeg.Length - 2);
                            jpeg = jpegwithtables;
                        }
                        tiff.image.data = jpeg;
                        tiff.image.SetOriginalType(ImageType.JPEG);
                        JpegImageHelper.ProcessImage(tiff.image);
                        tiff.jpegProcessing = true;
                        if (photometric == TIFFConstants.PHOTOMETRIC_RGB)
                        {
                            tiff.image.SetColorTransform(0);
                        }
                    }
                    else
                    {
                        for (int k = 0; k < offset.Length; ++k)
                        {
                            byte[] im = new byte[(int)size[k]];
                            s.Seek(offset[k]);
                            s.ReadFully(im);
                            int    height = Math.Min(rowsStrip, rowsLeft);
                            byte[] outBuf = null;
                            if (compression != TIFFConstants.COMPRESSION_NONE)
                            {
                                outBuf = new byte[(w * bitsPerSample * samplePerPixel + 7) / 8 * height];
                            }
                            if (reverse)
                            {
                                TIFFFaxDecoder.ReverseBits(im);
                            }
                            switch (compression)
                            {
                            case TIFFConstants.COMPRESSION_DEFLATE:
                            case TIFFConstants.COMPRESSION_ADOBE_DEFLATE: {
                                FilterUtil.InflateData(im, outBuf);
                                ApplyPredictor(outBuf, predictor, w, height, samplePerPixel);
                                break;
                            }

                            case TIFFConstants.COMPRESSION_NONE: {
                                outBuf = im;
                                break;
                            }

                            case TIFFConstants.COMPRESSION_PACKBITS: {
                                DecodePackbits(im, outBuf);
                                break;
                            }

                            case TIFFConstants.COMPRESSION_LZW: {
                                lzwDecoder.Decode(im, outBuf, height);
                                break;
                            }
                            }
                            if (bitsPerSample == 1 && samplePerPixel == 1 && photometric != TIFFConstants.PHOTOMETRIC_PALETTE)
                            {
                                g4.Fax4Encode(outBuf, height);
                            }
                            else
                            {
                                if (extraSamples > 0)
                                {
                                    ProcessExtraSamples(zip, mzip, outBuf, samplePerPixel, bitsPerSample, w, height);
                                }
                                else
                                {
                                    zip.Write(outBuf);
                                }
                            }
                            rowsLeft -= rowsStrip;
                        }
                        if (bitsPerSample == 1 && samplePerPixel == 1 && photometric != TIFFConstants.PHOTOMETRIC_PALETTE)
                        {
                            RawImageHelper.UpdateRawImageParameters(tiff.image, w, h, false, RawImageData.CCITTG4, photometric == TIFFConstants
                                                                    .PHOTOMETRIC_MINISBLACK ? RawImageData.CCITT_BLACKIS1 : 0, g4.Close(), null);
                        }
                        else
                        {
                            zip.Close();
                            RawImageHelper.UpdateRawImageParameters(tiff.image, w, h, samplePerPixel - extraSamples, bitsPerSample, stream
                                                                    .ToArray());
                            tiff.image.SetDeflated(true);
                        }
                    }
                }
                tiff.image.SetDpi(dpiX, dpiY);
                if (compression != TIFFConstants.COMPRESSION_OJPEG && compression != TIFFConstants.COMPRESSION_JPEG)
                {
                    if (dir.IsTagPresent(TIFFConstants.TIFFTAG_ICCPROFILE))
                    {
                        try {
                            TIFFField  fd       = dir.GetField(TIFFConstants.TIFFTAG_ICCPROFILE);
                            IccProfile icc_prof = IccProfile.GetInstance(fd.GetAsBytes());
                            if (samplePerPixel - extraSamples == icc_prof.GetNumComponents())
                            {
                                tiff.image.SetProfile(icc_prof);
                            }
                        }
                        catch (Exception) {
                        }
                    }
                    //empty
                    if (dir.IsTagPresent(TIFFConstants.TIFFTAG_COLORMAP))
                    {
                        TIFFField fd      = dir.GetField(TIFFConstants.TIFFTAG_COLORMAP);
                        char[]    rgb     = fd.GetAsChars();
                        byte[]    palette = new byte[rgb.Length];
                        int       gColor  = rgb.Length / 3;
                        int       bColor  = gColor * 2;
                        for (int k = 0; k < gColor; ++k)
                        {
                            //there is no sense in >>> for unsigned char
                            palette[k * 3]     = (byte)(rgb[k] >> 8);
                            palette[k * 3 + 1] = (byte)(rgb[k + gColor] >> 8);
                            palette[k * 3 + 2] = (byte)(rgb[k + bColor] >> 8);
                        }
                        // Colormap components are supposed to go from 0 to 655535 but,
                        // as usually, some tiff producers just put values from 0 to 255.
                        // Let's check for these broken tiffs.
                        bool colormapBroken = true;
                        for (int k_1 = 0; k_1 < palette.Length; ++k_1)
                        {
                            if (palette[k_1] != 0)
                            {
                                colormapBroken = false;
                                break;
                            }
                        }
                        if (colormapBroken)
                        {
                            for (int k_2 = 0; k_2 < gColor; ++k_2)
                            {
                                palette[k_2 * 3]     = (byte)rgb[k_2];
                                palette[k_2 * 3 + 1] = (byte)rgb[k_2 + gColor];
                                palette[k_2 * 3 + 2] = (byte)rgb[k_2 + bColor];
                            }
                        }
                        Object[] indexed = new Object[4];
                        indexed[0]      = "Indexed";
                        indexed[1]      = "DeviceRGB";
                        indexed[2]      = gColor - 1;
                        indexed[3]      = PdfEncodings.ConvertToString(palette, null);
                        tiff.additional = new Dictionary <String, Object>();
                        tiff.additional["ColorSpace"] = indexed;
                    }
                }
                if (photometric == TIFFConstants.PHOTOMETRIC_MINISWHITE)
                {
                    tiff.image.SetInverted(true);
                }
                if (rotation != 0)
                {
                    tiff.image.SetRotation(rotation);
                }
                if (extraSamples > 0)
                {
                    mzip.Close();
                    RawImageData mimg = (RawImageData)ImageDataFactory.CreateRawImage(null);
                    RawImageHelper.UpdateRawImageParameters(mimg, w, h, 1, bitsPerSample, mstream.ToArray());
                    mimg.MakeMask();
                    mimg.SetDeflated(true);
                    tiff.image.SetImageMask(mimg);
                }
            }
            catch (Exception) {
                throw new iText.IO.IOException(iText.IO.IOException.CannotGetTiffImageColor);
            }
        }
예제 #14
0
        protected static Image GetTiffImageColor(TIFFDirectory dir, RandomAccessFileOrArray s)
        {
            int            predictor   = 1;
            TIFFLZWDecoder lzwDecoder  = null;
            int            compression = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_COMPRESSION);

            switch (compression)
            {
            case TIFFConstants.COMPRESSION_NONE:
            case TIFFConstants.COMPRESSION_LZW:
            case TIFFConstants.COMPRESSION_PACKBITS:
            case TIFFConstants.COMPRESSION_DEFLATE:
            case TIFFConstants.COMPRESSION_ADOBE_DEFLATE:
            case TIFFConstants.COMPRESSION_OJPEG:
            case TIFFConstants.COMPRESSION_JPEG:
                break;

            default:
                throw new ArgumentException(MessageLocalization.GetComposedMessage("the.compression.1.is.not.supported", compression));
            }
            int photometric = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_PHOTOMETRIC);

            switch (photometric)
            {
            case TIFFConstants.PHOTOMETRIC_MINISWHITE:
            case TIFFConstants.PHOTOMETRIC_MINISBLACK:
            case TIFFConstants.PHOTOMETRIC_RGB:
            case TIFFConstants.PHOTOMETRIC_SEPARATED:
            case TIFFConstants.PHOTOMETRIC_PALETTE:
                break;

            default:
                if (compression != TIFFConstants.COMPRESSION_OJPEG && compression != TIFFConstants.COMPRESSION_JPEG)
                {
                    throw new ArgumentException(MessageLocalization.GetComposedMessage("the.photometric.1.is.not.supported", photometric));
                }
                break;
            }
            float rotation = 0;

            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_ORIENTATION))
            {
                int rot = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_ORIENTATION);
                if (rot == TIFFConstants.ORIENTATION_BOTRIGHT || rot == TIFFConstants.ORIENTATION_BOTLEFT)
                {
                    rotation = (float)Math.PI;
                }
                else if (rot == TIFFConstants.ORIENTATION_LEFTTOP || rot == TIFFConstants.ORIENTATION_LEFTBOT)
                {
                    rotation = (float)(Math.PI / 2.0);
                }
                else if (rot == TIFFConstants.ORIENTATION_RIGHTTOP || rot == TIFFConstants.ORIENTATION_RIGHTBOT)
                {
                    rotation = -(float)(Math.PI / 2.0);
                }
            }

            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_PLANARCONFIG) &&
                dir.GetFieldAsLong(TIFFConstants.TIFFTAG_PLANARCONFIG) == TIFFConstants.PLANARCONFIG_SEPARATE)
            {
                throw new ArgumentException(MessageLocalization.GetComposedMessage("planar.images.are.not.supported"));
            }
            int extraSamples = 0;

            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_EXTRASAMPLES))
            {
                extraSamples = 1;
            }
            int samplePerPixel = 1;

            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_SAMPLESPERPIXEL)) // 1,3,4
            {
                samplePerPixel = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_SAMPLESPERPIXEL);
            }
            int bitsPerSample = 1;

            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_BITSPERSAMPLE))
            {
                bitsPerSample = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_BITSPERSAMPLE);
            }
            switch (bitsPerSample)
            {
            case 1:
            case 2:
            case 4:
            case 8:
                break;

            default:
                throw new ArgumentException(MessageLocalization.GetComposedMessage("bits.per.sample.1.is.not.supported", bitsPerSample));
            }
            Image img = null;

            int h              = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_IMAGELENGTH);
            int w              = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_IMAGEWIDTH);
            int dpiX           = 0;
            int dpiY           = 0;
            int resolutionUnit = TIFFConstants.RESUNIT_INCH;

            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_RESOLUTIONUNIT))
            {
                resolutionUnit = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_RESOLUTIONUNIT);
            }
            dpiX = GetDpi(dir.GetField(TIFFConstants.TIFFTAG_XRESOLUTION), resolutionUnit);
            dpiY = GetDpi(dir.GetField(TIFFConstants.TIFFTAG_YRESOLUTION), resolutionUnit);
            int       fillOrder      = 1;
            bool      reverse        = false;
            TIFFField fillOrderField = dir.GetField(TIFFConstants.TIFFTAG_FILLORDER);

            if (fillOrderField != null)
            {
                fillOrder = fillOrderField.GetAsInt(0);
            }
            reverse = (fillOrder == TIFFConstants.FILLORDER_LSB2MSB);
            int rowsStrip = h;

            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_ROWSPERSTRIP)) //another hack for broken tiffs
            {
                rowsStrip = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_ROWSPERSTRIP);
            }
            if (rowsStrip <= 0 || rowsStrip > h)
            {
                rowsStrip = h;
            }
            long[] offset = GetArrayLongShort(dir, TIFFConstants.TIFFTAG_STRIPOFFSETS);
            long[] size   = GetArrayLongShort(dir, TIFFConstants.TIFFTAG_STRIPBYTECOUNTS);
            if ((size == null || (size.Length == 1 && (size[0] == 0 || size[0] + offset[0] > s.Length))) && h == rowsStrip)   // some TIFF producers are really lousy, so...
            {
                size = new long[] { s.Length - (int)offset[0] };
            }
            if (compression == TIFFConstants.COMPRESSION_LZW || compression == TIFFConstants.COMPRESSION_DEFLATE || compression == TIFFConstants.COMPRESSION_ADOBE_DEFLATE)
            {
                TIFFField predictorField = dir.GetField(TIFFConstants.TIFFTAG_PREDICTOR);
                if (predictorField != null)
                {
                    predictor = predictorField.GetAsInt(0);
                    if (predictor != 1 && predictor != 2)
                    {
                        throw new Exception(MessageLocalization.GetComposedMessage("illegal.value.for.predictor.in.tiff.file"));
                    }
                    if (predictor == 2 && bitsPerSample != 8)
                    {
                        throw new Exception(MessageLocalization.GetComposedMessage("1.bit.samples.are.not.supported.for.horizontal.differencing.predictor", bitsPerSample));
                    }
                }
            }
            if (compression == TIFFConstants.COMPRESSION_LZW)
            {
                lzwDecoder = new TIFFLZWDecoder(w, predictor, samplePerPixel);
            }
            int                   rowsLeft = h;
            MemoryStream          stream   = null;
            MemoryStream          mstream  = null;
            ZDeflaterOutputStream zip      = null;
            ZDeflaterOutputStream mzip     = null;

            if (extraSamples > 0)
            {
                mstream = new MemoryStream();
                mzip    = new ZDeflaterOutputStream(mstream);
            }

            CCITTG4Encoder g4 = null;

            if (bitsPerSample == 1 && samplePerPixel == 1 && photometric != TIFFConstants.PHOTOMETRIC_PALETTE)
            {
                g4 = new CCITTG4Encoder(w);
            }
            else
            {
                stream = new MemoryStream();
                if (compression != TIFFConstants.COMPRESSION_OJPEG && compression != TIFFConstants.COMPRESSION_JPEG)
                {
                    zip = new ZDeflaterOutputStream(stream);
                }
            }
            if (compression == TIFFConstants.COMPRESSION_OJPEG)
            {
                // Assume that the TIFFTAG_JPEGIFBYTECOUNT tag is optional, since it's obsolete and
                // is often missing

                if ((!dir.IsTagPresent(TIFFConstants.TIFFTAG_JPEGIFOFFSET)))
                {
                    throw new IOException(MessageLocalization.GetComposedMessage("missing.tag.s.for.ojpeg.compression"));
                }
                int jpegOffset = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_JPEGIFOFFSET);
                int jpegLength = (int)s.Length - jpegOffset;

                if (dir.IsTagPresent(TIFFConstants.TIFFTAG_JPEGIFBYTECOUNT))
                {
                    jpegLength = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_JPEGIFBYTECOUNT) +
                                 (int)size[0];
                }

                byte[] jpeg = new byte[Math.Min(jpegLength, s.Length - jpegOffset)];

                int posFilePointer = (int)s.FilePointer;
                posFilePointer += jpegOffset;
                s.Seek(posFilePointer);
                s.ReadFully(jpeg);
                // if quantization and/or Huffman tables are stored separately in the tiff,
                // we need to add them to the jpeg data
                TIFFField jpegtables = dir.GetField(TIFFConstants.TIFFTAG_JPEGTABLES);
                if (jpegtables != null)
                {
                    byte[] temp        = jpegtables.GetAsBytes();
                    int    tableoffset = 0;
                    int    tablelength = temp.Length;
                    // remove FFD8 from start
                    if (temp[0] == (byte)0xFF && temp[1] == (byte)0xD8)
                    {
                        tableoffset  = 2;
                        tablelength -= 2;
                    }
                    // remove FFD9 from end
                    if (temp[temp.Length - 2] == (byte)0xFF && temp[temp.Length - 1] == (byte)0xD9)
                    {
                        tablelength -= 2;
                    }
                    byte[] tables = new byte[tablelength];
                    Array.Copy(temp, tableoffset, tables, 0, tablelength);
                    // TODO insert after JFIF header, instead of at the start
                    byte[] jpegwithtables = new byte[jpeg.Length + tables.Length];
                    Array.Copy(jpeg, 0, jpegwithtables, 0, 2);
                    Array.Copy(tables, 0, jpegwithtables, 2, tables.Length);
                    Array.Copy(jpeg, 2, jpegwithtables, tables.Length + 2, jpeg.Length - 2);
                    jpeg = jpegwithtables;
                }
                img = new Jpeg(jpeg);
            }
            else if (compression == TIFFConstants.COMPRESSION_JPEG)
            {
                if (size.Length > 1)
                {
                    throw new IOException(MessageLocalization.GetComposedMessage("compression.jpeg.is.only.supported.with.a.single.strip.this.image.has.1.strips", size.Length));
                }
                byte[] jpeg = new byte[(int)size[0]];
                s.Seek(offset[0]);
                s.ReadFully(jpeg);
                img = new Jpeg(jpeg);
            }
            else
            {
                for (int k = 0; k < offset.Length; ++k)
                {
                    byte[] im = new byte[(int)size[k]];
                    s.Seek(offset[k]);
                    s.ReadFully(im);
                    int    height = Math.Min(rowsStrip, rowsLeft);
                    byte[] outBuf = null;
                    if (compression != TIFFConstants.COMPRESSION_NONE)
                    {
                        outBuf = new byte[(w * bitsPerSample * samplePerPixel + 7) / 8 * height];
                    }
                    if (reverse)
                    {
                        TIFFFaxDecoder.ReverseBits(im);
                    }
                    switch (compression)
                    {
                    case TIFFConstants.COMPRESSION_DEFLATE:
                    case TIFFConstants.COMPRESSION_ADOBE_DEFLATE:
                        Inflate(im, outBuf);
                        ApplyPredictor(outBuf, predictor, w, height, samplePerPixel);
                        break;

                    case TIFFConstants.COMPRESSION_NONE:
                        outBuf = im;
                        break;

                    case TIFFConstants.COMPRESSION_PACKBITS:
                        DecodePackbits(im, outBuf);
                        break;

                    case TIFFConstants.COMPRESSION_LZW:
                        lzwDecoder.Decode(im, outBuf, height);
                        break;
                    }
                    if (bitsPerSample == 1 && samplePerPixel == 1 && photometric != TIFFConstants.PHOTOMETRIC_PALETTE)
                    {
                        g4.Fax4Encode(outBuf, height);
                    }
                    else
                    {
                        if (extraSamples > 0)
                        {
                            ProcessExtraSamples(zip, mzip, outBuf, samplePerPixel, bitsPerSample, w, height);
                        }
                        else
                        {
                            zip.Write(outBuf, 0, outBuf.Length);
                        }
                    }
                    rowsLeft -= rowsStrip;
                }
                if (bitsPerSample == 1 && samplePerPixel == 1 && photometric != TIFFConstants.PHOTOMETRIC_PALETTE)
                {
                    img = Image.GetInstance(w, h, false, Image.CCITTG4,
                                            photometric == TIFFConstants.PHOTOMETRIC_MINISBLACK ? Image.CCITT_BLACKIS1 : 0, g4.Close());
                }
                else
                {
                    zip.Close();
                    img          = new ImgRaw(w, h, samplePerPixel - extraSamples, bitsPerSample, stream.ToArray());
                    img.Deflated = true;
                }
            }
            img.SetDpi(dpiX, dpiY);
            if (compression != TIFFConstants.COMPRESSION_OJPEG && compression != TIFFConstants.COMPRESSION_JPEG)
            {
                if (dir.IsTagPresent(TIFFConstants.TIFFTAG_ICCPROFILE))
                {
                    try {
                        TIFFField   fd       = dir.GetField(TIFFConstants.TIFFTAG_ICCPROFILE);
                        ICC_Profile icc_prof = ICC_Profile.GetInstance(fd.GetAsBytes());
                        if (samplePerPixel - extraSamples == icc_prof.NumComponents)
                        {
                            img.TagICC = icc_prof;
                        }
                    }
                    catch {
                        //empty
                    }
                }
                if (dir.IsTagPresent(TIFFConstants.TIFFTAG_COLORMAP))
                {
                    TIFFField fd      = dir.GetField(TIFFConstants.TIFFTAG_COLORMAP);
                    char[]    rgb     = fd.GetAsChars();
                    byte[]    palette = new byte[rgb.Length];
                    int       gColor  = rgb.Length / 3;
                    int       bColor  = gColor * 2;
                    for (int k = 0; k < gColor; ++k)
                    {
                        palette[k * 3]     = (byte)(rgb[k] >> 8);
                        palette[k * 3 + 1] = (byte)(rgb[k + gColor] >> 8);
                        palette[k * 3 + 2] = (byte)(rgb[k + bColor] >> 8);
                    }
                    // Colormap components are supposed to go from 0 to 655535 but,
                    // as usually, some tiff producers just put values from 0 to 255.
                    // Let's check for these broken tiffs.
                    bool colormapBroken = true;
                    for (int k = 0; k < palette.Length; ++k)
                    {
                        if (palette[k] != 0)
                        {
                            colormapBroken = false;
                            break;
                        }
                    }
                    if (colormapBroken)
                    {
                        for (int k = 0; k < gColor; ++k)
                        {
                            palette[k * 3]     = (byte)rgb[k];
                            palette[k * 3 + 1] = (byte)rgb[k + gColor];
                            palette[k * 3 + 2] = (byte)rgb[k + bColor];
                        }
                    }
                    PdfArray indexed = new PdfArray();
                    indexed.Add(PdfName.INDEXED);
                    indexed.Add(PdfName.DEVICERGB);
                    indexed.Add(new PdfNumber(gColor - 1));
                    indexed.Add(new PdfString(palette));
                    PdfDictionary additional = new PdfDictionary();
                    additional.Put(PdfName.COLORSPACE, indexed);
                    img.Additional = additional;
                }
                img.OriginalType = Image.ORIGINAL_TIFF;
            }
            if (photometric == TIFFConstants.PHOTOMETRIC_MINISWHITE)
            {
                img.Inverted = true;
            }
            if (rotation != 0)
            {
                img.InitialRotation = rotation;
            }
            if (extraSamples > 0)
            {
                mzip.Close();
                Image mimg = Image.GetInstance(w, h, 1, bitsPerSample, mstream.ToArray());
                mimg.MakeMask();
                mimg.Deflated = true;
                img.ImageMask = mimg;
            }
            return(img);
        }
예제 #15
0
        /** Reads a page from a TIFF image.
         * @param s the file source
         * @param page the page to get. The first page is 1
         * @param direct for single strip, CCITT images, generate the image
         * by direct byte copying. It's faster but may not work
         * every time
         * @return the <CODE>Image</CODE>
         */
        public static Image GetTiffImage(RandomAccessFileOrArray s, int page, bool direct)
        {
            if (page < 1)
            {
                throw new ArgumentException(MessageLocalization.GetComposedMessage("the.page.number.must.be.gt.eq.1"));
            }
            TIFFDirectory dir = new TIFFDirectory(s, page - 1);

            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_TILEWIDTH))
            {
                throw new ArgumentException(MessageLocalization.GetComposedMessage("tiles.are.not.supported"));
            }
            int compression = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_COMPRESSION);

            switch (compression)
            {
            case TIFFConstants.COMPRESSION_CCITTRLEW:
            case TIFFConstants.COMPRESSION_CCITTRLE:
            case TIFFConstants.COMPRESSION_CCITTFAX3:
            case TIFFConstants.COMPRESSION_CCITTFAX4:
                break;

            default:
                return(GetTiffImageColor(dir, s));
            }
            float rotation = 0;

            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_ORIENTATION))
            {
                int rot = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_ORIENTATION);
                if (rot == TIFFConstants.ORIENTATION_BOTRIGHT || rot == TIFFConstants.ORIENTATION_BOTLEFT)
                {
                    rotation = (float)Math.PI;
                }
                else if (rot == TIFFConstants.ORIENTATION_LEFTTOP || rot == TIFFConstants.ORIENTATION_LEFTBOT)
                {
                    rotation = (float)(Math.PI / 2.0);
                }
                else if (rot == TIFFConstants.ORIENTATION_RIGHTTOP || rot == TIFFConstants.ORIENTATION_RIGHTBOT)
                {
                    rotation = -(float)(Math.PI / 2.0);
                }
            }

            Image img            = null;
            long  tiffT4Options  = 0;
            long  tiffT6Options  = 0;
            int   fillOrder      = 1;
            int   h              = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_IMAGELENGTH);
            int   w              = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_IMAGEWIDTH);
            int   dpiX           = 0;
            int   dpiY           = 0;
            float XYRatio        = 0;
            int   resolutionUnit = TIFFConstants.RESUNIT_INCH;

            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_RESOLUTIONUNIT))
            {
                resolutionUnit = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_RESOLUTIONUNIT);
            }
            dpiX = GetDpi(dir.GetField(TIFFConstants.TIFFTAG_XRESOLUTION), resolutionUnit);
            dpiY = GetDpi(dir.GetField(TIFFConstants.TIFFTAG_YRESOLUTION), resolutionUnit);
            if (resolutionUnit == TIFFConstants.RESUNIT_NONE)
            {
                if (dpiY != 0)
                {
                    XYRatio = (float)dpiX / (float)dpiY;
                }
                dpiX = 0;
                dpiY = 0;
            }
            int rowsStrip = h;

            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_ROWSPERSTRIP))
            {
                rowsStrip = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_ROWSPERSTRIP);
            }
            if (rowsStrip <= 0 || rowsStrip > h)
            {
                rowsStrip = h;
            }
            long[] offset = GetArrayLongShort(dir, TIFFConstants.TIFFTAG_STRIPOFFSETS);
            long[] size   = GetArrayLongShort(dir, TIFFConstants.TIFFTAG_STRIPBYTECOUNTS);
            if ((size == null || (size.Length == 1 && (size[0] == 0 || size[0] + offset[0] > s.Length))) && h == rowsStrip)   // some TIFF producers are really lousy, so...
            {
                size = new long[] { s.Length - (int)offset[0] };
            }
            bool      reverse        = false;
            TIFFField fillOrderField = dir.GetField(TIFFConstants.TIFFTAG_FILLORDER);

            if (fillOrderField != null)
            {
                fillOrder = fillOrderField.GetAsInt(0);
            }
            reverse = (fillOrder == TIFFConstants.FILLORDER_LSB2MSB);
            int paramsn = 0;

            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_PHOTOMETRIC))
            {
                long photo = dir.GetFieldAsLong(TIFFConstants.TIFFTAG_PHOTOMETRIC);
                if (photo == TIFFConstants.PHOTOMETRIC_MINISBLACK)
                {
                    paramsn |= Image.CCITT_BLACKIS1;
                }
            }
            int imagecomp = 0;

            switch (compression)
            {
            case TIFFConstants.COMPRESSION_CCITTRLEW:
            case TIFFConstants.COMPRESSION_CCITTRLE:
                imagecomp = Image.CCITTG3_1D;
                paramsn  |= Image.CCITT_ENCODEDBYTEALIGN | Image.CCITT_ENDOFBLOCK;
                break;

            case TIFFConstants.COMPRESSION_CCITTFAX3:
                imagecomp = Image.CCITTG3_1D;
                paramsn  |= Image.CCITT_ENDOFLINE | Image.CCITT_ENDOFBLOCK;
                TIFFField t4OptionsField = dir.GetField(TIFFConstants.TIFFTAG_GROUP3OPTIONS);
                if (t4OptionsField != null)
                {
                    tiffT4Options = t4OptionsField.GetAsLong(0);
                    if ((tiffT4Options & TIFFConstants.GROUP3OPT_2DENCODING) != 0)
                    {
                        imagecomp = Image.CCITTG3_2D;
                    }
                    if ((tiffT4Options & TIFFConstants.GROUP3OPT_FILLBITS) != 0)
                    {
                        paramsn |= Image.CCITT_ENCODEDBYTEALIGN;
                    }
                }
                break;

            case TIFFConstants.COMPRESSION_CCITTFAX4:
                imagecomp = Image.CCITTG4;
                TIFFField t6OptionsField = dir.GetField(TIFFConstants.TIFFTAG_GROUP4OPTIONS);
                if (t6OptionsField != null)
                {
                    tiffT6Options = t6OptionsField.GetAsLong(0);
                }
                break;
            }
            if (direct && rowsStrip == h)   //single strip, direct
            {
                byte[] im = new byte[(int)size[0]];
                s.Seek(offset[0]);
                s.ReadFully(im);
                img          = Image.GetInstance(w, h, false, imagecomp, paramsn, im);
                img.Inverted = true;
            }
            else
            {
                int            rowsLeft = h;
                CCITTG4Encoder g4       = new CCITTG4Encoder(w);
                for (int k = 0; k < offset.Length; ++k)
                {
                    byte[] im = new byte[(int)size[k]];
                    s.Seek(offset[k]);
                    s.ReadFully(im);
                    int            height  = Math.Min(rowsStrip, rowsLeft);
                    TIFFFaxDecoder decoder = new TIFFFaxDecoder(fillOrder, w, height);
                    byte[]         outBuf  = new byte[(w + 7) / 8 * height];
                    switch (compression)
                    {
                    case TIFFConstants.COMPRESSION_CCITTRLEW:
                    case TIFFConstants.COMPRESSION_CCITTRLE:
                        decoder.Decode1D(outBuf, im, 0, height);
                        g4.Fax4Encode(outBuf, height);
                        break;

                    case TIFFConstants.COMPRESSION_CCITTFAX3:
                        try {
                            decoder.Decode2D(outBuf, im, 0, height, tiffT4Options);
                        }
                        catch (Exception e) {
                            // let's flip the fill bits and try again...
                            tiffT4Options ^= TIFFConstants.GROUP3OPT_FILLBITS;
                            try {
                                decoder.Decode2D(outBuf, im, 0, height, tiffT4Options);
                            }
                            catch {
                                throw e;
                            }
                        }
                        g4.Fax4Encode(outBuf, height);
                        break;

                    case TIFFConstants.COMPRESSION_CCITTFAX4:
                        decoder.DecodeT6(outBuf, im, 0, height, tiffT6Options);
                        g4.Fax4Encode(outBuf, height);
                        break;
                    }
                    rowsLeft -= rowsStrip;
                }
                byte[] g4pic = g4.Close();
                img = Image.GetInstance(w, h, false, Image.CCITTG4, paramsn & Image.CCITT_BLACKIS1, g4pic);
            }
            img.SetDpi(dpiX, dpiY);
            img.XYRatio = XYRatio;
            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_ICCPROFILE))
            {
                try {
                    TIFFField   fd       = dir.GetField(TIFFConstants.TIFFTAG_ICCPROFILE);
                    ICC_Profile icc_prof = ICC_Profile.GetInstance(fd.GetAsBytes());
                    if (icc_prof.NumComponents == 1)
                    {
                        img.TagICC = icc_prof;
                    }
                }
                catch {
                    //empty
                }
            }
            img.OriginalType = Image.ORIGINAL_TIFF;
            if (rotation != 0)
            {
                img.InitialRotation = rotation;
            }
            return(img);
        }
예제 #16
0
        protected static Image GetTiffImageColor(TiffDirectory dir, RandomAccessFileOrArray s)
        {
            var            predictor   = 1;
            TifflzwDecoder lzwDecoder  = null;
            var            compression = (int)dir.GetFieldAsLong(TiffConstants.TIFFTAG_COMPRESSION);

            switch (compression)
            {
            case TiffConstants.COMPRESSION_NONE:
            case TiffConstants.COMPRESSION_LZW:
            case TiffConstants.COMPRESSION_PACKBITS:
            case TiffConstants.COMPRESSION_DEFLATE:
            case TiffConstants.COMPRESSION_ADOBE_DEFLATE:
            case TiffConstants.COMPRESSION_OJPEG:
            case TiffConstants.COMPRESSION_JPEG:
                break;

            default:
                throw new InvalidOperationException("The compression " + compression + " is not supported.");
            }
            var photometric = (int)dir.GetFieldAsLong(TiffConstants.TIFFTAG_PHOTOMETRIC);

            switch (photometric)
            {
            case TiffConstants.PHOTOMETRIC_MINISWHITE:
            case TiffConstants.PHOTOMETRIC_MINISBLACK:
            case TiffConstants.PHOTOMETRIC_RGB:
            case TiffConstants.PHOTOMETRIC_SEPARATED:
            case TiffConstants.PHOTOMETRIC_PALETTE:
                break;

            default:
                if (compression != TiffConstants.COMPRESSION_OJPEG && compression != TiffConstants.COMPRESSION_JPEG)
                {
                    throw new InvalidOperationException("The photometric " + photometric + " is not supported.");
                }

                break;
            }
            float rotation = 0;

            if (dir.IsTagPresent(TiffConstants.TIFFTAG_ORIENTATION))
            {
                var rot = (int)dir.GetFieldAsLong(TiffConstants.TIFFTAG_ORIENTATION);
                if (rot == TiffConstants.ORIENTATION_BOTRIGHT || rot == TiffConstants.ORIENTATION_BOTLEFT)
                {
                    rotation = (float)Math.PI;
                }
                else if (rot == TiffConstants.ORIENTATION_LEFTTOP || rot == TiffConstants.ORIENTATION_LEFTBOT)
                {
                    rotation = (float)(Math.PI / 2.0);
                }
                else if (rot == TiffConstants.ORIENTATION_RIGHTTOP || rot == TiffConstants.ORIENTATION_RIGHTBOT)
                {
                    rotation = -(float)(Math.PI / 2.0);
                }
            }

            if (dir.IsTagPresent(TiffConstants.TIFFTAG_PLANARCONFIG) &&
                dir.GetFieldAsLong(TiffConstants.TIFFTAG_PLANARCONFIG) == TiffConstants.PLANARCONFIG_SEPARATE)
            {
                throw new InvalidOperationException("Planar images are not supported.");
            }

            if (dir.IsTagPresent(TiffConstants.TIFFTAG_EXTRASAMPLES))
            {
                throw new InvalidOperationException("Extra samples are not supported.");
            }

            var samplePerPixel = 1;

            if (dir.IsTagPresent(TiffConstants.TIFFTAG_SAMPLESPERPIXEL)) // 1,3,4
            {
                samplePerPixel = (int)dir.GetFieldAsLong(TiffConstants.TIFFTAG_SAMPLESPERPIXEL);
            }

            var bitsPerSample = 1;

            if (dir.IsTagPresent(TiffConstants.TIFFTAG_BITSPERSAMPLE))
            {
                bitsPerSample = (int)dir.GetFieldAsLong(TiffConstants.TIFFTAG_BITSPERSAMPLE);
            }

            switch (bitsPerSample)
            {
            case 1:
            case 2:
            case 4:
            case 8:
                break;

            default:
                throw new InvalidOperationException("Bits per sample " + bitsPerSample + " is not supported.");
            }
            Image img = null;

            var h              = (int)dir.GetFieldAsLong(TiffConstants.TIFFTAG_IMAGELENGTH);
            var w              = (int)dir.GetFieldAsLong(TiffConstants.TIFFTAG_IMAGEWIDTH);
            var dpiX           = 0;
            var dpiY           = 0;
            var resolutionUnit = TiffConstants.RESUNIT_INCH;

            if (dir.IsTagPresent(TiffConstants.TIFFTAG_RESOLUTIONUNIT))
            {
                resolutionUnit = (int)dir.GetFieldAsLong(TiffConstants.TIFFTAG_RESOLUTIONUNIT);
            }

            dpiX = getDpi(dir.GetField(TiffConstants.TIFFTAG_XRESOLUTION), resolutionUnit);
            dpiY = getDpi(dir.GetField(TiffConstants.TIFFTAG_YRESOLUTION), resolutionUnit);
            var fillOrder      = 1;
            var reverse        = false;
            var fillOrderField = dir.GetField(TiffConstants.TIFFTAG_FILLORDER);

            if (fillOrderField != null)
            {
                fillOrder = fillOrderField.GetAsInt(0);
            }

            reverse = (fillOrder == TiffConstants.FILLORDER_LSB2MSB);
            var rowsStrip = h;

            if (dir.IsTagPresent(TiffConstants.TIFFTAG_ROWSPERSTRIP)) //another hack for broken tiffs
            {
                rowsStrip = (int)dir.GetFieldAsLong(TiffConstants.TIFFTAG_ROWSPERSTRIP);
            }

            if (rowsStrip <= 0 || rowsStrip > h)
            {
                rowsStrip = h;
            }

            var offset = getArrayLongShort(dir, TiffConstants.TIFFTAG_STRIPOFFSETS);
            var size   = getArrayLongShort(dir, TiffConstants.TIFFTAG_STRIPBYTECOUNTS);

            if ((size == null || (size.Length == 1 && (size[0] == 0 || size[0] + offset[0] > s.Length))) && h == rowsStrip)
            { // some TIFF producers are really lousy, so...
                size = new long[] { s.Length - (int)offset[0] };
            }
            if (compression == TiffConstants.COMPRESSION_LZW)
            {
                var predictorField = dir.GetField(TiffConstants.TIFFTAG_PREDICTOR);
                if (predictorField != null)
                {
                    predictor = predictorField.GetAsInt(0);
                    if (predictor != 1 && predictor != 2)
                    {
                        throw new InvalidOperationException("Illegal value for Predictor in TIFF file.");
                    }
                    if (predictor == 2 && bitsPerSample != 8)
                    {
                        throw new InvalidOperationException(bitsPerSample + "-bit samples are not supported for Horizontal differencing Predictor.");
                    }
                }
                lzwDecoder = new TifflzwDecoder(w, predictor,
                                                samplePerPixel);
            }
            var                   rowsLeft = h;
            MemoryStream          stream   = null;
            ZDeflaterOutputStream zip      = null;
            Ccittg4Encoder        g4       = null;

            if (bitsPerSample == 1 && samplePerPixel == 1)
            {
                g4 = new Ccittg4Encoder(w);
            }
            else
            {
                stream = new MemoryStream();
                if (compression != TiffConstants.COMPRESSION_OJPEG && compression != TiffConstants.COMPRESSION_JPEG)
                {
                    zip = new ZDeflaterOutputStream(stream);
                }
            }
            if (compression == TiffConstants.COMPRESSION_OJPEG)
            {
                // Assume that the TIFFTAG_JPEGIFBYTECOUNT tag is optional, since it's obsolete and
                // is often missing

                if ((!dir.IsTagPresent(TiffConstants.TIFFTAG_JPEGIFOFFSET)))
                {
                    throw new IOException("Missing tag(s) for OJPEG compression.");
                }
                var jpegOffset = (int)dir.GetFieldAsLong(TiffConstants.TIFFTAG_JPEGIFOFFSET);
                var jpegLength = s.Length - jpegOffset;

                if (dir.IsTagPresent(TiffConstants.TIFFTAG_JPEGIFBYTECOUNT))
                {
                    jpegLength = (int)dir.GetFieldAsLong(TiffConstants.TIFFTAG_JPEGIFBYTECOUNT) +
                                 (int)size[0];
                }

                var jpeg = new byte[Math.Min(jpegLength, s.Length - jpegOffset)];

                var posFilePointer = s.FilePointer;
                posFilePointer += jpegOffset;
                s.Seek(posFilePointer);
                s.ReadFully(jpeg);
                img = new Jpeg(jpeg);
            }
            else if (compression == TiffConstants.COMPRESSION_JPEG)
            {
                if (size.Length > 1)
                {
                    throw new IOException("Compression JPEG is only supported with a single strip. This image has " + size.Length + " strips.");
                }

                var jpeg = new byte[(int)size[0]];
                s.Seek(offset[0]);
                s.ReadFully(jpeg);
                img = new Jpeg(jpeg);
            }
            else
            {
                for (var k = 0; k < offset.Length; ++k)
                {
                    var im = new byte[(int)size[k]];
                    s.Seek(offset[k]);
                    s.ReadFully(im);
                    var    height = Math.Min(rowsStrip, rowsLeft);
                    byte[] outBuf = null;
                    if (compression != TiffConstants.COMPRESSION_NONE)
                    {
                        outBuf = new byte[(w * bitsPerSample * samplePerPixel + 7) / 8 * height];
                    }

                    if (reverse)
                    {
                        TiffFaxDecoder.ReverseBits(im);
                    }

                    switch (compression)
                    {
                    case TiffConstants.COMPRESSION_DEFLATE:
                    case TiffConstants.COMPRESSION_ADOBE_DEFLATE:
                        Inflate(im, outBuf);
                        break;

                    case TiffConstants.COMPRESSION_NONE:
                        outBuf = im;
                        break;

                    case TiffConstants.COMPRESSION_PACKBITS:
                        DecodePackbits(im, outBuf);
                        break;

                    case TiffConstants.COMPRESSION_LZW:
                        lzwDecoder.Decode(im, outBuf, height);
                        break;
                    }
                    if (bitsPerSample == 1 && samplePerPixel == 1)
                    {
                        g4.Fax4Encode(outBuf, height);
                    }
                    else
                    {
                        zip.Write(outBuf, 0, outBuf.Length);
                    }
                    rowsLeft -= rowsStrip;
                }
                if (bitsPerSample == 1 && samplePerPixel == 1)
                {
                    img = Image.GetInstance(w, h, false, Element.CCITTG4,
                                            photometric == TiffConstants.PHOTOMETRIC_MINISBLACK ? Element.CCITT_BLACKIS1 : 0, g4.Close());
                }
                else
                {
                    zip.Close();
                    img          = Image.GetInstance(w, h, samplePerPixel, bitsPerSample, stream.ToArray());
                    img.Deflated = true;
                }
            }
            img.SetDpi(dpiX, dpiY);
            if (compression != TiffConstants.COMPRESSION_OJPEG && compression != TiffConstants.COMPRESSION_JPEG)
            {
                if (dir.IsTagPresent(TiffConstants.TIFFTAG_ICCPROFILE))
                {
                    try
                    {
                        var fd      = dir.GetField(TiffConstants.TIFFTAG_ICCPROFILE);
                        var iccProf = IccProfile.GetInstance(fd.GetAsBytes());
                        if (samplePerPixel == iccProf.NumComponents)
                        {
                            img.TagIcc = iccProf;
                        }
                    }
                    catch
                    {
                        //empty
                    }
                }
                if (dir.IsTagPresent(TiffConstants.TIFFTAG_COLORMAP))
                {
                    var fd      = dir.GetField(TiffConstants.TIFFTAG_COLORMAP);
                    var rgb     = fd.GetAsChars();
                    var palette = new byte[rgb.Length];
                    var gColor  = rgb.Length / 3;
                    var bColor  = gColor * 2;
                    for (var k = 0; k < gColor; ++k)
                    {
                        palette[k * 3]     = (byte)(rgb[k] >> 8);
                        palette[k * 3 + 1] = (byte)(rgb[k + gColor] >> 8);
                        palette[k * 3 + 2] = (byte)(rgb[k + bColor] >> 8);
                    }
                    var indexed = new PdfArray();
                    indexed.Add(PdfName.Indexed);
                    indexed.Add(PdfName.Devicergb);
                    indexed.Add(new PdfNumber(gColor - 1));
                    indexed.Add(new PdfString(palette));
                    var additional = new PdfDictionary();
                    additional.Put(PdfName.Colorspace, indexed);
                    img.Additional = additional;
                }
                img.OriginalType = Image.ORIGINAL_TIFF;
            }
            if (photometric == TiffConstants.PHOTOMETRIC_MINISWHITE)
            {
                img.Inverted = true;
            }

            if (rotation.ApproxNotEqual(0))
            {
                img.InitialRotation = rotation;
            }

            return(img);
        }
예제 #17
0
        /// <exception cref="System.IO.IOException"/>
        protected internal virtual void AssembleFont()
        {
            int[]          tableLocation;
            int            fullFontSize = 0;
            IList <String> tableNames   = new List <String>();

            tableNames.AddAll(tableNamesSimple);
            if (includeExtras)
            {
                tableNames.AddAll(tableNamesExtra);
            }
            else
            {
                if (includeCmap)
                {
                    tableNames.AddAll(tableNamesCmap);
                }
            }
            int tablesUsed = 2;

            foreach (String name in tableNames)
            {
                if (name.Equals("glyf") || name.Equals("loca"))
                {
                    continue;
                }
                tableLocation = tableDirectory.Get(name);
                if (tableLocation == null)
                {
                    continue;
                }
                tablesUsed++;
                fullFontSize += tableLocation[TABLE_LENGTH] + 3 & ~3;
            }
            fullFontSize += newLocaTableOut.Length;
            fullFontSize += newGlyfTable.Length;
            int reference = 16 * tablesUsed + 12;

            fullFontSize += reference;
            outFont       = new byte[fullFontSize];
            fontPtr       = 0;
            WriteFontInt(0x00010000);
            WriteFontShort(tablesUsed);
            int selector = entrySelectors[tablesUsed];

            WriteFontShort((1 << selector) * 16);
            WriteFontShort(selector);
            WriteFontShort((tablesUsed - (1 << selector)) * 16);
            foreach (String name in tableNames)
            {
                int len;
                tableLocation = tableDirectory.Get(name);
                if (tableLocation == null)
                {
                    continue;
                }
                WriteFontString(name);
                switch (name)
                {
                case "glyf": {
                    WriteFontInt(CalculateChecksum(newGlyfTable));
                    len = glyfTableRealSize;
                    break;
                }

                case "loca": {
                    WriteFontInt(CalculateChecksum(newLocaTableOut));
                    len = locaTableRealSize;
                    break;
                }

                default: {
                    WriteFontInt(tableLocation[TABLE_CHECKSUM]);
                    len = tableLocation[TABLE_LENGTH];
                    break;
                }
                }
                WriteFontInt(reference);
                WriteFontInt(len);
                reference += len + 3 & ~3;
            }
            foreach (String name in tableNames)
            {
                tableLocation = tableDirectory.Get(name);
                if (tableLocation == null)
                {
                    continue;
                }
                switch (name)
                {
                case "glyf": {
                    Array.Copy(newGlyfTable, 0, outFont, fontPtr, newGlyfTable.Length);
                    fontPtr     += newGlyfTable.Length;
                    newGlyfTable = null;
                    break;
                }

                case "loca": {
                    Array.Copy(newLocaTableOut, 0, outFont, fontPtr, newLocaTableOut.Length);
                    fontPtr        += newLocaTableOut.Length;
                    newLocaTableOut = null;
                    break;
                }

                default: {
                    rf.Seek(tableLocation[TABLE_OFFSET]);
                    rf.ReadFully(outFont, fontPtr, tableLocation[TABLE_LENGTH]);
                    fontPtr += tableLocation[TABLE_LENGTH] + 3 & ~3;
                    break;
                }
                }
            }
        }
예제 #18
0
        /// <summary>Reads the windows metrics table.</summary>
        /// <remarks>
        /// Reads the windows metrics table. The metrics are extracted from the table 'OS/2'.
        /// Depends on
        /// <see cref="HeaderTable.unitsPerEm"/>
        /// property.
        /// </remarks>
        private void ReadOs_2Table()
        {
            int[] table_location = tables.Get("OS/2");
            if (table_location == null)
            {
                if (fileName != null)
                {
                    throw new iText.IO.IOException(iText.IO.IOException.TableDoesNotExistsIn).SetMessageParams("os/2", fileName
                                                                                                               );
                }
                else
                {
                    throw new iText.IO.IOException(iText.IO.IOException.TableDoesNotExist).SetMessageParams("os/2");
                }
            }
            os_2 = new OpenTypeParser.WindowsMetrics();
            raf.Seek(table_location[0]);
            int version = raf.ReadUnsignedShort();

            os_2.xAvgCharWidth       = raf.ReadShort();
            os_2.usWeightClass       = raf.ReadUnsignedShort();
            os_2.usWidthClass        = raf.ReadUnsignedShort();
            os_2.fsType              = raf.ReadShort();
            os_2.ySubscriptXSize     = raf.ReadShort();
            os_2.ySubscriptYSize     = raf.ReadShort();
            os_2.ySubscriptXOffset   = raf.ReadShort();
            os_2.ySubscriptYOffset   = raf.ReadShort();
            os_2.ySuperscriptXSize   = raf.ReadShort();
            os_2.ySuperscriptYSize   = raf.ReadShort();
            os_2.ySuperscriptXOffset = raf.ReadShort();
            os_2.ySuperscriptYOffset = raf.ReadShort();
            os_2.yStrikeoutSize      = raf.ReadShort();
            os_2.yStrikeoutPosition  = raf.ReadShort();
            os_2.sFamilyClass        = raf.ReadShort();
            raf.ReadFully(os_2.panose);
            raf.SkipBytes(16);
            raf.ReadFully(os_2.achVendID);
            os_2.fsSelection      = raf.ReadUnsignedShort();
            os_2.usFirstCharIndex = raf.ReadUnsignedShort();
            os_2.usLastCharIndex  = raf.ReadUnsignedShort();
            os_2.sTypoAscender    = raf.ReadShort();
            os_2.sTypoDescender   = raf.ReadShort();
            if (os_2.sTypoDescender > 0)
            {
                os_2.sTypoDescender = (short)-os_2.sTypoDescender;
            }
            os_2.sTypoLineGap = raf.ReadShort();
            os_2.usWinAscent  = raf.ReadUnsignedShort();
            os_2.usWinDescent = raf.ReadUnsignedShort();
            if (os_2.usWinDescent > 0)
            {
                os_2.usWinDescent = (short)-os_2.usWinDescent;
            }
            os_2.ulCodePageRange1 = 0;
            os_2.ulCodePageRange2 = 0;
            if (version > 0)
            {
                os_2.ulCodePageRange1 = raf.ReadInt();
                os_2.ulCodePageRange2 = raf.ReadInt();
            }
            if (version > 1)
            {
                // todo os_2.sxHeight = raf.readShort();
                raf.SkipBytes(2);
                os_2.sCapHeight = raf.ReadShort();
            }
            else
            {
                os_2.sCapHeight = (int)(0.7 * head.unitsPerEm);
            }
        }
예제 #19
0
        protected static Image GetTiffImageColor(TIFFDirectory dir, RandomAccessFileOrArray s)
        {
            int predictor = 1;
            TIFFLZWDecoder lzwDecoder = null;
            int compression = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_COMPRESSION);
            switch (compression) {
                case TIFFConstants.COMPRESSION_NONE:
                case TIFFConstants.COMPRESSION_LZW:
                case TIFFConstants.COMPRESSION_PACKBITS:
                case TIFFConstants.COMPRESSION_DEFLATE:
                case TIFFConstants.COMPRESSION_ADOBE_DEFLATE:
                case TIFFConstants.COMPRESSION_OJPEG:
                case TIFFConstants.COMPRESSION_JPEG:
                    break;
                default:
                    throw new ArgumentException("The compression " + compression + " is not supported.");
            }
            int photometric = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_PHOTOMETRIC);
            switch (photometric) {
                case TIFFConstants.PHOTOMETRIC_MINISWHITE:
                case TIFFConstants.PHOTOMETRIC_MINISBLACK:
                case TIFFConstants.PHOTOMETRIC_RGB:
                case TIFFConstants.PHOTOMETRIC_SEPARATED:
                case TIFFConstants.PHOTOMETRIC_PALETTE:
                    break;
                default:
                    if (compression != TIFFConstants.COMPRESSION_OJPEG && compression != TIFFConstants.COMPRESSION_JPEG)
                        throw new ArgumentException("The photometric " + photometric + " is not supported.");
                    break;
            }
            float rotation = 0;
            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_ORIENTATION)) {
                int rot = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_ORIENTATION);
                if (rot == TIFFConstants.ORIENTATION_BOTRIGHT || rot == TIFFConstants.ORIENTATION_BOTLEFT)
                    rotation = (float)Math.PI;
                else if (rot == TIFFConstants.ORIENTATION_LEFTTOP || rot == TIFFConstants.ORIENTATION_LEFTBOT)
                    rotation = (float)(Math.PI / 2.0);
                else if (rot == TIFFConstants.ORIENTATION_RIGHTTOP || rot == TIFFConstants.ORIENTATION_RIGHTBOT)
                    rotation = -(float)(Math.PI / 2.0);
            }

            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_PLANARCONFIG)
                && dir.GetFieldAsLong(TIFFConstants.TIFFTAG_PLANARCONFIG) == TIFFConstants.PLANARCONFIG_SEPARATE)
                throw new ArgumentException("Planar images are not supported.");
            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_EXTRASAMPLES))
                throw new ArgumentException("Extra samples are not supported.");
            int samplePerPixel = 1;
            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_SAMPLESPERPIXEL)) // 1,3,4
                samplePerPixel = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_SAMPLESPERPIXEL);
            int bitsPerSample = 1;
            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_BITSPERSAMPLE))
                bitsPerSample = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_BITSPERSAMPLE);
            switch (bitsPerSample) {
                case 1:
                case 2:
                case 4:
                case 8:
                    break;
                default:
                    throw new ArgumentException("Bits per sample " + bitsPerSample + " is not supported.");
            }
            Image img = null;

            int h = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_IMAGELENGTH);
            int w = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_IMAGEWIDTH);
            int dpiX = 0;
            int dpiY = 0;
            int resolutionUnit = TIFFConstants.RESUNIT_INCH;
            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_RESOLUTIONUNIT))
                resolutionUnit = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_RESOLUTIONUNIT);
            dpiX = GetDpi(dir.GetField(TIFFConstants.TIFFTAG_XRESOLUTION), resolutionUnit);
            dpiY = GetDpi(dir.GetField(TIFFConstants.TIFFTAG_YRESOLUTION), resolutionUnit);
            int fillOrder = 1;
            bool reverse = false;
            TIFFField fillOrderField =  dir.GetField(TIFFConstants.TIFFTAG_FILLORDER);
            if (fillOrderField != null)
                fillOrder = fillOrderField.GetAsInt(0);
            reverse = (fillOrder == TIFFConstants.FILLORDER_LSB2MSB);
            int rowsStrip = h;
            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_ROWSPERSTRIP)) //another hack for broken tiffs
                rowsStrip = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_ROWSPERSTRIP);
            if (rowsStrip <= 0 || rowsStrip > h)
                rowsStrip = h;
            long[] offset = GetArrayLongShort(dir, TIFFConstants.TIFFTAG_STRIPOFFSETS);
            long[] size = GetArrayLongShort(dir, TIFFConstants.TIFFTAG_STRIPBYTECOUNTS);
            if ((size == null || (size.Length == 1 && (size[0] == 0 || size[0] + offset[0] > s.Length))) && h == rowsStrip) { // some TIFF producers are really lousy, so...
                size = new long[]{s.Length - (int)offset[0]};
            }
            if (compression == TIFFConstants.COMPRESSION_LZW) {
                TIFFField predictorField = dir.GetField(TIFFConstants.TIFFTAG_PREDICTOR);
                if (predictorField != null) {
                    predictor = predictorField.GetAsInt(0);
                    if (predictor != 1 && predictor != 2) {
                        throw new Exception("Illegal value for Predictor in TIFF file.");
                    }
                    if (predictor == 2 && bitsPerSample != 8) {
                        throw new Exception(bitsPerSample + "-bit samples are not supported for Horizontal differencing Predictor.");
                    }
                }
                lzwDecoder = new TIFFLZWDecoder(w, predictor,
                                                samplePerPixel);
            }
            int rowsLeft = h;
            MemoryStream stream = null;
            ZOutputStream zip = null;
            CCITTG4Encoder g4 = null;
            if (bitsPerSample == 1 && samplePerPixel == 1) {
                g4 = new CCITTG4Encoder(w);
            }
            else {
                stream = new MemoryStream();
                if (compression != TIFFConstants.COMPRESSION_OJPEG && compression != TIFFConstants.COMPRESSION_JPEG)
                    zip = new ZOutputStream(stream);
            }
            if (compression == TIFFConstants.COMPRESSION_OJPEG) {

                // Assume that the TIFFTAG_JPEGIFBYTECOUNT tag is optional, since it's obsolete and
                // is often missing

                if ((!dir.IsTagPresent(TIFFConstants.TIFFTAG_JPEGIFOFFSET))) {
                    throw new IOException("Missing tag(s) for OJPEG compression.");
                }
                int jpegOffset = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_JPEGIFOFFSET);
                int jpegLength = s.Length - jpegOffset;

                if (dir.IsTagPresent(TIFFConstants.TIFFTAG_JPEGIFBYTECOUNT)) {
                    jpegLength = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_JPEGIFBYTECOUNT) +
                        (int)size[0];
                }

                byte[] jpeg = new byte[Math.Min(jpegLength, s.Length - jpegOffset)];

                int posFilePointer = s.FilePointer;
                posFilePointer += jpegOffset;
                s.Seek(posFilePointer);
                s.ReadFully(jpeg);
                img = new Jpeg(jpeg);
            }
            else if (compression == TIFFConstants.COMPRESSION_JPEG) {
                if (size.Length > 1)
                    throw new IOException("Compression JPEG is only supported with a single strip. This image has " + size.Length + " strips.");
                byte[] jpeg = new byte[(int)size[0]];
                s.Seek(offset[0]);
                s.ReadFully(jpeg);
                img = new Jpeg(jpeg);
            }
            else {
                for (int k = 0; k < offset.Length; ++k) {
                    byte[] im = new byte[(int)size[k]];
                    s.Seek(offset[k]);
                    s.ReadFully(im);
                    int height = Math.Min(rowsStrip, rowsLeft);
                    byte[] outBuf = null;
                    if (compression != TIFFConstants.COMPRESSION_NONE)
                        outBuf = new byte[(w * bitsPerSample * samplePerPixel + 7) / 8 * height];
                    if (reverse)
                        TIFFFaxDecoder.ReverseBits(im);
                    switch (compression) {
                        case TIFFConstants.COMPRESSION_DEFLATE:
                        case TIFFConstants.COMPRESSION_ADOBE_DEFLATE:
                            Inflate(im, outBuf);
                            break;
                        case TIFFConstants.COMPRESSION_NONE:
                            outBuf = im;
                            break;
                        case TIFFConstants.COMPRESSION_PACKBITS:
                            DecodePackbits(im,  outBuf);
                            break;
                        case TIFFConstants.COMPRESSION_LZW:
                            lzwDecoder.Decode(im, outBuf, height);
                            break;
                    }
                    if (bitsPerSample == 1 && samplePerPixel == 1) {
                        g4.Fax4Encode(outBuf, height);
                    }
                    else {
                        zip.Write(outBuf, 0, outBuf.Length);
                    }
                    rowsLeft -= rowsStrip;
                }
                if (bitsPerSample == 1 && samplePerPixel == 1) {
                    img = Image.GetInstance(w, h, false, Image.CCITTG4,
                        photometric == TIFFConstants.PHOTOMETRIC_MINISBLACK ? Image.CCITT_BLACKIS1 : 0, g4.Close());
                }
                else {
                    zip.Close();
                    img = Image.GetInstance(w, h, samplePerPixel, bitsPerSample, stream.ToArray());
                    img.Deflated = true;
                }
            }
            img.SetDpi(dpiX, dpiY);
            if (compression != TIFFConstants.COMPRESSION_OJPEG && compression != TIFFConstants.COMPRESSION_JPEG) {
                if (dir.IsTagPresent(TIFFConstants.TIFFTAG_ICCPROFILE)) {
                    try {
                        TIFFField fd = dir.GetField(TIFFConstants.TIFFTAG_ICCPROFILE);
                        ICC_Profile icc_prof = ICC_Profile.GetInstance(fd.GetAsBytes());
                        if (samplePerPixel == icc_prof.NumComponents)
                            img.TagICC = icc_prof;
                    }
                    catch {
                        //empty
                    }
                }
                if (dir.IsTagPresent(TIFFConstants.TIFFTAG_COLORMAP)) {
                    TIFFField fd = dir.GetField(TIFFConstants.TIFFTAG_COLORMAP);
                    char[] rgb = fd.GetAsChars();
                    byte[] palette = new byte[rgb.Length];
                    int gColor = rgb.Length / 3;
                    int bColor = gColor * 2;
                    for (int k = 0; k < gColor; ++k) {
                        palette[k * 3] = (byte)(rgb[k] >> 8);
                        palette[k * 3 + 1] = (byte)(rgb[k + gColor] >> 8);
                        palette[k * 3 + 2] = (byte)(rgb[k + bColor] >> 8);
                    }
                    PdfArray indexed = new PdfArray();
                    indexed.Add(PdfName.INDEXED);
                    indexed.Add(PdfName.DEVICERGB);
                    indexed.Add(new PdfNumber(gColor - 1));
                    indexed.Add(new PdfString(palette));
                    PdfDictionary additional = new PdfDictionary();
                    additional.Put(PdfName.COLORSPACE, indexed);
                    img.Additional = additional;
                }
                img.OriginalType = Image.ORIGINAL_TIFF;
            }
            if (photometric == TIFFConstants.PHOTOMETRIC_MINISWHITE)
                img.Inverted = true;
            if (rotation != 0)
                img.InitialRotation = rotation;
            return img;
        }