Exemple #1
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="buffer">字节数组</param>
        /// <param name="width">图像的宽</param>
        /// <param name="height">图像的高</param>
        /// <param name="filePath"></param>
        /// <param name="rowsPerStrip">图像的实际高度</param>
        /// <param name="xResolution">x分辨率</param>
        /// <param name="yResolution">y分辨率</param>
        /// <param name="resUnit">分辨率单位,默认选inch</param>
        /// <param name="planarConfig">数据平面存储方式</param>
        /// <param name="bytePerSample">单个像素是多少位</param>
        /// <param name="photometric">图像模式</param>
        /// <param name="compression">压缩方式</param>
        /// <param name="samplePerPixel">一个像素几个采样</param>
        /// <param name="orientation">方向</param>
        /// <param name="fillOrder">大小端</param>
        public static void CreateGrayScaleTiff(byte[] buffer, int width, int height, string filePath, int rowsPerStrip,
                                               int xResolution, int yResolution, ResUnit resUnit = ResUnit.INCH,
                                               PlanarConfig planarConfig = PlanarConfig.CONTIG,
                                               int bytePerSample         = 16, Photometric photometric = Photometric.MINISBLACK,
                                               Compression compression   = Compression.NONE,
                                               int samplePerPixel        = 1, Orientation orientation = Orientation.TOPLEFT,
                                               FillOrder fillOrder       = FillOrder.MSB2LSB)
        {
            var info = CreateDoubleByteTiffInfo(buffer, null, width, height, filePath, height, width, height);

            Create16BitGrayScaleTiff(info);
        }
Exemple #2
0
        public TiffDirectory()
        {
            td_subfiletype  = 0;
            td_compression  = 0;
            td_photometric  = 0;
            td_planarconfig = 0;

            td_fillorder            = FillOrder.MSB2LSB;
            td_bitspersample        = 1;
            td_threshholding        = Threshold.BILEVEL;
            td_orientation          = Orientation.TOPLEFT;
            td_samplesperpixel      = 1;
            td_rowsperstrip         = -1;
            td_tiledepth            = 1;
            td_stripbytecountsorted = true; // Our own arrays always sorted.
            td_resolutionunit       = ResUnit.INCH;
            td_sampleformat         = SampleFormat.UINT;
            td_imagedepth           = 1;
            td_ycbcrsubsampling[0]  = 2;
            td_ycbcrsubsampling[1]  = 2;
            td_ycbcrpositioning     = YCbCrPosition.CENTERED;
        }
Exemple #3
0
        public byte[] buffernull = null;   // return null array

        // Read and Write Images for simulation
        public byte[] ReadImage(string Layerpath, int row, int col)
        {
            byte[] buffer;
            // Open the TIFF image
            using (Tiff image = Tiff.Open(Layerpath, "r"))
            {
                if (image == null)
                {
                    MessageBox.Show("Could not open incoming image" + Layerpath);
                    //throw new System.InvalidOperationException("Could not open incoming image"+Layerpath);
                    return(buffernull);
                }

                // Check that it is of a type that we support
                FieldValue[] value = image.GetField(TiffTag.BITSPERSAMPLE);
                if (value == null)
                {
                    MessageBox.Show("Undefined number of bits per sample");
                    return(buffernull);
                }
                short bps = value[0].ToShort();
                if (bps != 8)
                {
                    MessageBox.Show("Bits per sample is not 8");
                    return(buffernull);
                }

                value = image.GetField(TiffTag.SAMPLESPERPIXEL);
                if (value == null)
                {
                    MessageBox.Show("Undefined number of samples per pixel");
                    return(buffernull);
                }
                short spp = value[0].ToShort();
                if (spp != 1)
                {
                    MessageBox.Show("Samples per pixel is not 1");
                    return(buffernull);
                }

                value = image.GetField(TiffTag.IMAGEWIDTH);
                if (value == null)
                {
                    MessageBox.Show("Image does not define its width");
                    return(buffernull);
                }
                int col1 = value[0].ToInt();

                value = image.GetField(TiffTag.IMAGELENGTH);
                if (value == null)
                {
                    MessageBox.Show("Image does not define its width");
                    return(buffernull);
                }
                int row1 = value[0].ToInt();

                if (row != row1 || col != col1)
                {
                    MessageBox.Show("All the images are not of the same size. Please verify this."); return(buffernull);
                }
                buffer = new byte[row * col];
                int c = 0;
                for (int r = 0; r < row; r++)
                {
                    byte[] buf = new byte[col];
                    image.ReadScanline(buf, r);
                    for (int j = 0; j < col; j++)
                    {
                        buffer[c + j] = buf[j];
                    }
                    c += col;
                }

                // Deal with photometric interpretations
                value = image.GetField(TiffTag.PHOTOMETRIC);
                if (value == null)
                {
                    MessageBox.Show("Image has an undefined photometric interpretation");
                    return(buffernull);
                }

                Photometric photo = (Photometric)value[0].ToInt();
                if (photo != Photometric.MINISWHITE)
                {
                    // Flip bits
                    MessageBox.Show("Fixing the photometric interpretation");

                    for (int count = 0; count < row * col; count++)
                    {
                        buffer[count] = (byte)~buffer[count];
                    }
                }

                // Deal with fillorder
                value = image.GetField(TiffTag.FILLORDER);
                if (value == null)
                {
                    MessageBox.Show("Image has an undefined fillorder");
                    return(buffernull);
                }

                FillOrder fillorder = (FillOrder)value[0].ToInt();
                if (fillorder != FillOrder.MSB2LSB)
                {
                    // We need to swap bits -- ABCDEFGH becomes HGFEDCBA
                    MessageBox.Show("Fixing the fillorder");

                    for (int count = 0; count < row * col; count++)
                    {
                        byte tempbyte = 0;
                        if ((buffer[count] & 128) != 0)
                        {
                            tempbyte += 1;
                        }
                        if ((buffer[count] & 64) != 0)
                        {
                            tempbyte += 2;
                        }
                        if ((buffer[count] & 32) != 0)
                        {
                            tempbyte += 4;
                        }
                        if ((buffer[count] & 16) != 0)
                        {
                            tempbyte += 8;
                        }
                        if ((buffer[count] & 8) != 0)
                        {
                            tempbyte += 16;
                        }
                        if ((buffer[count] & 4) != 0)
                        {
                            tempbyte += 32;
                        }
                        if ((buffer[count] & 2) != 0)
                        {
                            tempbyte += 64;
                        }
                        if ((buffer[count] & 1) != 0)
                        {
                            tempbyte += 128;
                        }
                        buffer[count] = tempbyte;
                    }
                }
                image.Close();
            }
            return(buffer);
        }
Exemple #4
0
        public bool ReadHeaders(Tiff tif)
        {
            stride = tif.ScanlineSize();
            if (stride < 1)
            {
                return(false);
            }

            pxWidth  = tif.GetField(TiffTag.IMAGEWIDTH)[0].ToInt();
            pxHeight = tif.GetField(TiffTag.IMAGELENGTH)[0].ToInt();

            bpp = tif.GetField(TiffTag.BITSPERSAMPLE)[0].ToShort();
            if (bpp != 1)
            {
                return(false);
            }

            photo = (Photometric)(tif.GetField(TiffTag.PHOTOMETRIC)[0].ToInt());
            if (photo != Photometric.MINISBLACK && photo != Photometric.MINISWHITE)
            {
                return(false);
            }

            FieldValue[] fieldValue;

            fieldValue = tif.GetField(TiffTag.XRESOLUTION);
            if (fieldValue != null)
            {
                xRes = fieldValue[0].ToFloat();
            }
            else
            {
                xRes = 72.0F;
            }
            printWidth = (float)Math.Round(pxWidth / xRes, 2);

            fieldValue = tif.GetField(TiffTag.YRESOLUTION);
            if (fieldValue != null)
            {
                yRes = fieldValue[0].ToFloat();
            }
            else
            {
                yRes = 72.0F;
            }
            printHeight = (float)Math.Round(pxHeight / yRes, 2);

            fieldValue = tif.GetField(TiffTag.MAKE);
            if (fieldValue != null)
            {
                Make = fieldValue[0].ToString();
            }

            fieldValue = tif.GetField(TiffTag.MODEL);
            if (fieldValue != null)
            {
                Model = fieldValue[0].ToString();
            }

            fieldValue = tif.GetField(TiffTag.SOFTWARE);
            if (fieldValue != null)
            {
                Software = fieldValue[0].ToString();
            }

            return(true);
        }
Exemple #5
0
        private static Bitmap tiffToBitmap(string fileName)
        {
            using (Tiff tif = Tiff.Open(fileName, "r"))
            {
                if (tif == null)
                {
                    return(null);
                }

                FieldValue[] imageHeight = tif.GetField(TiffTag.IMAGELENGTH);
                int          height      = imageHeight[0].ToInt();

                FieldValue[] imageWidth = tif.GetField(TiffTag.IMAGEWIDTH);
                int          width      = imageWidth[0].ToInt();

                FieldValue[] bitsPerSample = tif.GetField(TiffTag.BITSPERSAMPLE);
                short        bpp           = bitsPerSample[0].ToShort();
                if (bpp != 1)
                {
                    return(null);
                }

                FieldValue[] samplesPerPixel = tif.GetField(TiffTag.SAMPLESPERPIXEL);
                short        spp             = samplesPerPixel[0].ToShort();
                if (spp != 1)
                {
                    return(null);
                }

                FieldValue[] photoMetric = tif.GetField(TiffTag.PHOTOMETRIC);
                Photometric  photo       = (Photometric)photoMetric[0].ToInt();
                if (photo != Photometric.MINISBLACK && photo != Photometric.MINISWHITE)
                {
                    return(null);
                }

                int    stride = tif.ScanlineSize();
                Bitmap result = new Bitmap(width, height, PixelFormat.Format1bppIndexed);

                // update bitmap palette according to Photometric value
                bool         minIsWhite = (photo == Photometric.MINISWHITE);
                ColorPalette palette    = result.Palette;
                palette.Entries[0] = (minIsWhite ? Color.White : Color.Black);
                palette.Entries[1] = (minIsWhite ? Color.Black : Color.White);
                result.Palette     = palette;

                for (int i = 0; i < height; i++)
                {
                    Rectangle  imgRect = new Rectangle(0, i, width, 1);
                    BitmapData imgData = result.LockBits(imgRect, ImageLockMode.WriteOnly, PixelFormat.Format1bppIndexed);

                    byte[] buffer = new byte[stride];
                    tif.ReadScanline(buffer, i);

                    Marshal.Copy(buffer, 0, imgData.Scan0, buffer.Length);
                    result.UnlockBits(imgData);
                }

                return(result);
            }
        }
Exemple #6
0
        private static Bitmap getBitmap8Bit(string inputName)
        {
            Bitmap result;

            using (Tiff tif = Tiff.Open(inputName, "r"))
            {
                FieldValue[] res    = tif.GetField(TiffTag.IMAGELENGTH);
                int          height = res[0].ToInt();

                res = tif.GetField(TiffTag.IMAGEWIDTH);
                int width = res[0].ToInt();

                res = tif.GetField(TiffTag.BITSPERSAMPLE);
                short bpp = res[0].ToShort();
                if (bpp != 16)
                {
                    return(null);
                }

                res = tif.GetField(TiffTag.SAMPLESPERPIXEL);
                short spp = res[0].ToShort();
                if (spp != 1)
                {
                    return(null);
                }

                res = tif.GetField(TiffTag.PHOTOMETRIC);
                Photometric photo = (Photometric)res[0].ToInt();
                if (photo != Photometric.MINISBLACK && photo != Photometric.MINISWHITE)
                {
                    return(null);
                }

                int    stride = tif.ScanlineSize();
                byte[] buffer = new byte[stride];

                result = new Bitmap(width, height, PixelFormat.Format8bppIndexed);
                byte[] buffer8Bit = null;

                for (int i = 0; i < height; i++)
                {
                    Rectangle  imgRect = new Rectangle(0, i, width, 1);
                    BitmapData imgData = result.LockBits(imgRect, ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed);

                    if (buffer8Bit == null)
                    {
                        buffer8Bit = new byte[imgData.Stride];
                    }
                    else
                    {
                        Array.Clear(buffer8Bit, 0, buffer8Bit.Length);
                    }

                    tif.ReadScanline(buffer, i);
                    convertBuffer(buffer, buffer8Bit);

                    Marshal.Copy(buffer8Bit, 0, imgData.Scan0, buffer8Bit.Length);
                    result.UnlockBits(imgData);
                }
            }

            return(result);
        }
Exemple #7
0
        /*
        This function sets the input directory to the directory of a given
        page and determines information about the image.  It checks
        the image characteristics to determine if it is possible to convert
        the image data into a page of PDF output, setting values of the T2P
        struct for this page.  It determines what color space is used in
        the output PDF to represent the image.

        It determines if the image can be converted as raw data without
        requiring transcoding of the image data.
        */
        private void read_tiff_data(Tiff input)
        {
            m_pdf_transcode = t2p_transcode_t.T2P_TRANSCODE_ENCODE;
            m_pdf_sample = t2p_sample_t.T2P_SAMPLE_NOTHING;
            m_pdf_switchdecode = m_pdf_colorspace_invert;

            input.SetDirectory(m_tiff_pages[m_pdf_page].page_directory);

            FieldValue[] result = input.GetField(TiffTag.IMAGEWIDTH);
            m_tiff_width = result[0].ToInt();
            if (m_tiff_width == 0)
            {
                Tiff.Error(Tiff2PdfConstants.TIFF2PDF_MODULE, "No support for {0} with zero width", input.FileName());
                m_error = true;
                return;
            }

            result = input.GetField(TiffTag.IMAGELENGTH);
            m_tiff_length = result[0].ToInt();
            if (m_tiff_length == 0)
            {
                Tiff.Error(Tiff2PdfConstants.TIFF2PDF_MODULE, 
                    "No support for {0} with zero length", input.FileName());
                m_error = true;
                return;
            }

            result = input.GetField(TiffTag.COMPRESSION);
            if (result == null)
            {
                Tiff.Error(Tiff2PdfConstants.TIFF2PDF_MODULE, 
                    "No support for {0} with no compression tag", input.FileName());
                m_error = true;
                return;
            }
            else
                m_tiff_compression = (Compression)result[0].ToInt();

            if (!input.IsCodecConfigured(m_tiff_compression))
            {
                Tiff.Error(Tiff2PdfConstants.TIFF2PDF_MODULE, 
                    "No support for {0} with compression type {1}:  not configured", 
                    input.FileName(), m_tiff_compression);
                m_error = true;
                return;

            }

            result = input.GetFieldDefaulted(TiffTag.BITSPERSAMPLE);
            m_tiff_bitspersample = result[0].ToShort();

            switch (m_tiff_bitspersample)
            {
                case 1:
                case 2:
                case 4:
                case 8:
                    break;
                case 0:
                    Tiff.Warning(Tiff2PdfConstants.TIFF2PDF_MODULE, 
                        "Image {0} has 0 bits per sample, assuming 1", input.FileName());
                    m_tiff_bitspersample = 1;
                    break;
                default:
                    Tiff.Error(Tiff2PdfConstants.TIFF2PDF_MODULE, 
                        "No support for {0} with {1} bits per sample",
                        input.FileName(), m_tiff_bitspersample);
                    m_error = true;
                    return;
            }

            result = input.GetFieldDefaulted(TiffTag.SAMPLESPERPIXEL);
            m_tiff_samplesperpixel = result[0].ToShort();
            if (m_tiff_samplesperpixel > 4)
            {
                Tiff.Error(Tiff2PdfConstants.TIFF2PDF_MODULE, 
                    "No support for {0} with {1} samples per pixel", input.FileName(), m_tiff_samplesperpixel);
                m_error = true;
                return;
            }

            if (m_tiff_samplesperpixel == 0)
            {
                Tiff.Warning(Tiff2PdfConstants.TIFF2PDF_MODULE, 
                    "Image {0} has 0 samples per pixel, assuming 1", input.FileName());
                m_tiff_samplesperpixel = 1;
            }

            result = input.GetField(TiffTag.SAMPLEFORMAT);
            if (result != null)
            {
                SampleFormat f = (SampleFormat)result[0].ToByte();
                switch (f)
                {
                    case 0:
                    case SampleFormat.UINT:
                    case SampleFormat.VOID:
                        break;

                    default:
                        Tiff.Error(Tiff2PdfConstants.TIFF2PDF_MODULE, 
                            "No support for {0} with sample format {1}", input.FileName(), f);
                        m_error = true;
                        return;
                }
            }

            result = input.GetFieldDefaulted(TiffTag.FILLORDER);
            m_tiff_fillorder = (FillOrder)result[0].ToByte();

            result = input.GetField(TiffTag.PHOTOMETRIC);
            if (result == null)
            {
                Tiff.Error(Tiff2PdfConstants.TIFF2PDF_MODULE, 
                    "No support for {0} with no photometric interpretation tag", input.FileName());
                m_error = true;
                return;
            }
            else
                m_tiff_photometric = (Photometric)result[0].ToInt();

            short[] r;
            short[] g;
            short[] b;
            short[] a;
            bool photometric_palette;
            bool photometric_palette_cmyk;

            switch (m_tiff_photometric)
            {
                case Photometric.MINISWHITE:
                case Photometric.MINISBLACK:
                    if (m_tiff_bitspersample == 1)
                    {
                        m_pdf_colorspace = t2p_cs_t.T2P_CS_BILEVEL;
                        if (m_tiff_photometric == Photometric.MINISWHITE)
                            m_pdf_switchdecode ^= true;
                    }
                    else
                    {
                        m_pdf_colorspace = t2p_cs_t.T2P_CS_GRAY;
                        if (m_tiff_photometric == Photometric.MINISWHITE)
                            m_pdf_switchdecode ^= true;
                    }
                    break;
               
                case Photometric.RGB:
                case Photometric.PALETTE:
                    photometric_palette = (m_tiff_photometric == Photometric.PALETTE);
                    if (!photometric_palette)
                    {
                        m_pdf_colorspace = t2p_cs_t.T2P_CS_RGB;
                        if (m_tiff_samplesperpixel == 3)
                            break;

                        result = input.GetField(TiffTag.INDEXED);
                        if (result != null)
                        {
                            if (result[0].ToInt() == 1)
                                photometric_palette = true;
                        }
                    }

                    if (!photometric_palette)
                    {
                        if (m_tiff_samplesperpixel > 3)
                        {
                            if (m_tiff_samplesperpixel == 4)
                            {
                                m_pdf_colorspace = t2p_cs_t.T2P_CS_RGB;

                                result = input.GetField(TiffTag.EXTRASAMPLES);
                                if (result != null && result[0].ToInt() == 1)
                                {
                                    byte[] xuint16p = result[1].ToByteArray();
                                    if ((ExtraSample)xuint16p[0] == ExtraSample.ASSOCALPHA)
                                    {
                                        m_pdf_sample = t2p_sample_t.T2P_SAMPLE_RGBAA_TO_RGB;
                                        break;
                                    }

                                    if ((ExtraSample)xuint16p[0] == ExtraSample.UNASSALPHA)
                                    {
                                        m_pdf_sample = t2p_sample_t.T2P_SAMPLE_RGBA_TO_RGB;
                                        break;
                                    }
                                    
                                    Tiff.Warning(Tiff2PdfConstants.TIFF2PDF_MODULE,
                                        "RGB image {0} has 4 samples per pixel, assuming RGBA", input.FileName());
                                    break;
                                }

                                m_pdf_colorspace = t2p_cs_t.T2P_CS_CMYK;
                                m_pdf_switchdecode ^= true;
                                Tiff.Warning(Tiff2PdfConstants.TIFF2PDF_MODULE, 
                                    "RGB image {0} has 4 samples per pixel, assuming inverse CMYK", input.FileName());
                                break;
                            }
                            else
                            {
                                Tiff.Error(Tiff2PdfConstants.TIFF2PDF_MODULE,
                                    "No support for RGB image {0} with {1} samples per pixel", 
                                    input.FileName(), m_tiff_samplesperpixel);
                                m_error = true;
                                break;
                            }
                        }
                        else
                        {
                            Tiff.Error(Tiff2PdfConstants.TIFF2PDF_MODULE,
                                "No support for RGB image {0} with {1} samples per pixel",
                                input.FileName(), m_tiff_samplesperpixel);
                            m_error = true;
                            break;
                        }
                    }

                    if (photometric_palette)
                    {
                        if (m_tiff_samplesperpixel != 1)
                        {
                            Tiff.Error(Tiff2PdfConstants.TIFF2PDF_MODULE,
                                "No support for palletized image {0} with not one sample per pixel",
                                input.FileName());
                            m_error = true;
                            return;
                        }

                        m_pdf_colorspace = (t2p_cs_t)(t2p_cs_t.T2P_CS_RGB | t2p_cs_t.T2P_CS_PALETTE);
                        m_pdf_palettesize = 0x0001 << m_tiff_bitspersample;

                        result = input.GetField(TiffTag.COLORMAP);
                        if (result == null)
                        {
                            Tiff.Error(Tiff2PdfConstants.TIFF2PDF_MODULE, 
                                "Palletized image {0} has no color map", input.FileName());
                            m_error = true;
                            return;
                        }
                        else
                        {
                            r = result[0].ToShortArray();
                            g = result[1].ToShortArray();
                            b = result[2].ToShortArray();
                        }

                        m_pdf_palette = new byte [m_pdf_palettesize * 3];
                        for (int i = 0; i < m_pdf_palettesize; i++)
                        {
                            m_pdf_palette[i * 3] = (byte)(r[i] >> 8);
                            m_pdf_palette[i * 3 + 1] = (byte)(g[i] >> 8);
                            m_pdf_palette[i * 3 + 2] = (byte)(b[i] >> 8);
                        }

                        m_pdf_palettesize *= 3;
                    }
                    break;

                case Photometric.SEPARATED:
                    photometric_palette_cmyk = false;
                    result = input.GetField(TiffTag.INDEXED);
                    if (result != null)
                    {
                        if (result[0].ToInt() == 1)
                            photometric_palette_cmyk = true;
                    }

                    if (!photometric_palette_cmyk)
                    {
                        result = input.GetField(TiffTag.INKSET);
                        if (result != null)
                        {
                            if ((InkSet)result[0].ToByte() != InkSet.CMYK)
                            {
                                Tiff.Error(Tiff2PdfConstants.TIFF2PDF_MODULE,
                                    "No support for {0} because its inkset is not CMYK", input.FileName());
                                m_error = true;
                                return;
                            }
                        }
                        
                        if (m_tiff_samplesperpixel == 4)
                        {
                            m_pdf_colorspace = t2p_cs_t.T2P_CS_CMYK;
                        }
                        else
                        {
                            Tiff.Error(Tiff2PdfConstants.TIFF2PDF_MODULE,
                                "No support for {0} because it has {1} samples per pixel",
                                input.FileName(), m_tiff_samplesperpixel);
                            m_error = true;
                            return;
                        }
                    }
                    else
                    {
                        if (m_tiff_samplesperpixel != 1)
                        {
                            Tiff.Error(Tiff2PdfConstants.TIFF2PDF_MODULE,
                                "No support for palletized CMYK image {0} with not one sample per pixel",
                                input.FileName());
                            m_error = true;
                            return;
                        }
                        
                        m_pdf_colorspace = (t2p_cs_t)(t2p_cs_t.T2P_CS_CMYK | t2p_cs_t.T2P_CS_PALETTE);
                        m_pdf_palettesize = 0x0001 << m_tiff_bitspersample;
                        
                        result = input.GetField(TiffTag.COLORMAP);
                        if (result == null)
                        {
                            Tiff.Error(Tiff2PdfConstants.TIFF2PDF_MODULE,
                                "Palletized image {0} has no color map", input.FileName());
                            m_error = true;
                            return;
                        }
                        else
                        {
                            r = result[0].ToShortArray();
                            g = result[1].ToShortArray();
                            b = result[2].ToShortArray();
                            a = result[3].ToShortArray();
                        }
                        
                        m_pdf_palette = new byte [m_pdf_palettesize * 4];
                        for (int i = 0; i < m_pdf_palettesize; i++)
                        {
                            m_pdf_palette[i * 4] = (byte)(r[i] >> 8);
                            m_pdf_palette[i * 4 + 1] = (byte)(g[i] >> 8);
                            m_pdf_palette[i * 4 + 2] = (byte)(b[i] >> 8);
                            m_pdf_palette[i * 4 + 3] = (byte)(a[i] >> 8);
                        }

                        m_pdf_palettesize *= 4;
                    }
                    break;
                
                case Photometric.YCBCR:
                    m_pdf_colorspace = t2p_cs_t.T2P_CS_RGB;
                    if (m_tiff_samplesperpixel == 1)
                    {
                        m_pdf_colorspace = t2p_cs_t.T2P_CS_GRAY;
                        m_tiff_photometric = Photometric.MINISBLACK;
                        break;
                    }

                    m_pdf_sample = t2p_sample_t.T2P_SAMPLE_YCBCR_TO_RGB;
                    if (m_pdf_defaultcompression == t2p_compress_t.T2P_COMPRESS_JPEG)
                        m_pdf_sample = t2p_sample_t.T2P_SAMPLE_NOTHING;

                    break;

                case Photometric.CIELAB:
                    m_pdf_labrange[0] = -127;
                    m_pdf_labrange[1] = 127;
                    m_pdf_labrange[2] = -127;
                    m_pdf_labrange[3] = 127;
                    m_pdf_sample = t2p_sample_t.T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED;
                    m_pdf_colorspace = t2p_cs_t.T2P_CS_LAB;
                    break;

                case Photometric.ICCLAB:
                    m_pdf_labrange[0] = 0;
                    m_pdf_labrange[1] = 255;
                    m_pdf_labrange[2] = 0;
                    m_pdf_labrange[3] = 255;
                    m_pdf_colorspace = t2p_cs_t.T2P_CS_LAB;
                    break;

                case Photometric.ITULAB:
                    m_pdf_labrange[0] = -85;
                    m_pdf_labrange[1] = 85;
                    m_pdf_labrange[2] = -75;
                    m_pdf_labrange[3] = 124;
                    m_pdf_sample = t2p_sample_t.T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED;
                    m_pdf_colorspace = t2p_cs_t.T2P_CS_LAB;
                    break;

                case Photometric.LOGL:
                case Photometric.LOGLUV:
                    Tiff.Error(Tiff2PdfConstants.TIFF2PDF_MODULE,
                        "No support for {0} with photometric interpretation LogL/LogLuv", input.FileName());
                    m_error = true;
                    return;
                default:
                    Tiff.Error(Tiff2PdfConstants.TIFF2PDF_MODULE,
                        "No support for {0} with photometric interpretation {1}",
                        input.FileName(), m_tiff_photometric);
                    m_error = true;
                    return;
            }

            result = input.GetField(TiffTag.PLANARCONFIG);
            if (result != null)
            {
                m_tiff_planar = (PlanarConfig)result[0].ToShort();
                switch (m_tiff_planar)
                {
                    case 0:
                        Tiff.Warning(Tiff2PdfConstants.TIFF2PDF_MODULE,
                            "Image {0} has planar configuration 0, assuming 1", input.FileName());
                        m_tiff_planar = PlanarConfig.CONTIG;
                        break;

                    case PlanarConfig.CONTIG:
                        break;
                    
                    case PlanarConfig.SEPARATE:
                        m_pdf_sample = t2p_sample_t.T2P_SAMPLE_PLANAR_SEPARATE_TO_CONTIG;
                        if (m_tiff_bitspersample != 8)
                        {
                            Tiff.Error(Tiff2PdfConstants.TIFF2PDF_MODULE,
                                "No support for {0} with separated planar configuration and {1} bits per sample",
                                input.FileName(), m_tiff_bitspersample);
                            m_error = true;
                            return;
                        }
                        break;
                    
                    default:
                        Tiff.Error(Tiff2PdfConstants.TIFF2PDF_MODULE,
                            "No support for {0} with planar configuration {1}",
                            input.FileName(), m_tiff_planar);
                        m_error = true;
                        return;
                }
            }

            result = input.GetFieldDefaulted(TiffTag.ORIENTATION);
            m_tiff_orientation = (Orientation)result[0].ToByte();

            if (m_tiff_orientation > Orientation.LEFTBOT)
            {
                Tiff.Warning(Tiff2PdfConstants.TIFF2PDF_MODULE,
                    "Image {0} has orientation {1}, assuming 0", 
                    input.FileName(), m_tiff_orientation);
                m_tiff_orientation = 0;
            }

            result = input.GetField(TiffTag.XRESOLUTION);
            if (result == null)
                m_tiff_xres = 0.0f;
            else
                m_tiff_xres = result[0].ToFloat();

            result = input.GetField(TiffTag.YRESOLUTION);
            if (result == null)
                m_tiff_yres = 0.0f;
            else
                m_tiff_yres = result[0].ToFloat();

            result = input.GetFieldDefaulted(TiffTag.RESOLUTIONUNIT);
            m_tiff_resunit = (ResUnit)result[0].ToByte();
            if (m_tiff_resunit == ResUnit.CENTIMETER)
            {
                m_tiff_xres *= 2.54F;
                m_tiff_yres *= 2.54F;
            }
            else if (m_tiff_resunit != ResUnit.INCH && m_pdf_centimeters)
            {
                m_tiff_xres *= 2.54F;
                m_tiff_yres *= 2.54F;
            }

            compose_pdf_page();

            m_pdf_transcode = t2p_transcode_t.T2P_TRANSCODE_ENCODE;
            if (!m_pdf_nopassthrough)
            {
                if (m_tiff_compression == Compression.CCITTFAX4)
                {
                    if (input.IsTiled() || (input.NumberOfStrips() == 1))
                    {
                        m_pdf_transcode = t2p_transcode_t.T2P_TRANSCODE_RAW;
                        m_pdf_compression = t2p_compress_t.T2P_COMPRESS_G4;
                    }
                }

                if (m_tiff_compression == Compression.ADOBE_DEFLATE || m_tiff_compression == Compression.DEFLATE)
                {
                    if (input.IsTiled() || (input.NumberOfStrips() == 1))
                    {
                        m_pdf_transcode = t2p_transcode_t.T2P_TRANSCODE_RAW;
                        m_pdf_compression = t2p_compress_t.T2P_COMPRESS_ZIP;
                    }
                }

                if (m_tiff_compression == Compression.JPEG)
                {
                    m_pdf_transcode = t2p_transcode_t.T2P_TRANSCODE_RAW;
                    m_pdf_compression = t2p_compress_t.T2P_COMPRESS_JPEG;
                }
            }

            if (m_pdf_transcode != t2p_transcode_t.T2P_TRANSCODE_RAW)
                m_pdf_compression = m_pdf_defaultcompression;

            if (m_pdf_defaultcompression == t2p_compress_t.T2P_COMPRESS_JPEG)
            {
                if ((m_pdf_colorspace & t2p_cs_t.T2P_CS_PALETTE) != 0)
                {
                    m_pdf_sample = (t2p_sample_t)(m_pdf_sample | t2p_sample_t.T2P_SAMPLE_REALIZE_PALETTE);
                    m_pdf_colorspace = (t2p_cs_t)(m_pdf_colorspace ^ t2p_cs_t.T2P_CS_PALETTE);
                    m_tiff_pages[m_pdf_page].page_extra--;
                }
            }

            if (m_tiff_compression == Compression.JPEG)
            {
                if (m_tiff_planar == PlanarConfig.SEPARATE)
                {
                    Tiff.Error(Tiff2PdfConstants.TIFF2PDF_MODULE,
                        "No support for {0} with JPEG compression and separated planar configuration",
                        input.FileName());
                    m_error = true;
                    return;
                }
            }

            if ((m_pdf_sample & t2p_sample_t.T2P_SAMPLE_REALIZE_PALETTE) != 0)
            {
                if ((m_pdf_colorspace & t2p_cs_t.T2P_CS_CMYK) != 0)
                {
                    m_tiff_samplesperpixel = 4;
                    m_tiff_photometric = Photometric.SEPARATED;
                }
                else
                {
                    m_tiff_samplesperpixel = 3;
                    m_tiff_photometric = Photometric.RGB;
                }
            }

            result = input.GetField(TiffTag.TRANSFERFUNCTION);
            if (result != null)
            {
                m_tiff_transferfunction[0] = result[0].GetBytes();
                m_tiff_transferfunction[1] = result[1].GetBytes();
                m_tiff_transferfunction[2] = result[2].GetBytes();

                if (m_tiff_transferfunction[1] != m_tiff_transferfunction[0])
                    m_tiff_transferfunctioncount = 3;
                else
                    m_tiff_transferfunctioncount = 1;
            }
            else
            {
                m_tiff_transferfunctioncount = 0;
            }

            result = input.GetField(TiffTag.WHITEPOINT);
            if (result != null)
            {
                float[] xfloatp = result[0].ToFloatArray();
                m_tiff_whitechromaticities[0] = xfloatp[0];
                m_tiff_whitechromaticities[1] = xfloatp[1];
                
                if ((m_pdf_colorspace & t2p_cs_t.T2P_CS_GRAY) != 0)
                    m_pdf_colorspace = (t2p_cs_t)(m_pdf_colorspace | t2p_cs_t.T2P_CS_CALGRAY);

                if ((m_pdf_colorspace & t2p_cs_t.T2P_CS_RGB) != 0)
                    m_pdf_colorspace = (t2p_cs_t)(m_pdf_colorspace | t2p_cs_t.T2P_CS_CALRGB);
            }
            
            result = input.GetField(TiffTag.PRIMARYCHROMATICITIES);
            if (result != null)
            {
                float[] xfloatp = result[0].ToFloatArray();
                m_tiff_primarychromaticities[0] = xfloatp[0];
                m_tiff_primarychromaticities[1] = xfloatp[1];
                m_tiff_primarychromaticities[2] = xfloatp[2];
                m_tiff_primarychromaticities[3] = xfloatp[3];
                m_tiff_primarychromaticities[4] = xfloatp[4];
                m_tiff_primarychromaticities[5] = xfloatp[5];

                if ((m_pdf_colorspace & t2p_cs_t.T2P_CS_RGB) != 0)
                    m_pdf_colorspace = (t2p_cs_t)(m_pdf_colorspace | t2p_cs_t.T2P_CS_CALRGB);
            }

            if ((m_pdf_colorspace & t2p_cs_t.T2P_CS_LAB) != 0)
            {
                result = input.GetField(TiffTag.WHITEPOINT);
                if (result != null)
                {
                    float[] xfloatp = result[0].ToFloatArray();
                    m_tiff_whitechromaticities[0] = xfloatp[0];
                    m_tiff_whitechromaticities[1] = xfloatp[1];
                }
                else
                {
                    m_tiff_whitechromaticities[0] = 0.3457F; /* 0.3127F; */
                    m_tiff_whitechromaticities[1] = 0.3585F; /* 0.3290F; */
                }
            }

            result = input.GetField(TiffTag.ICCPROFILE);
            if (result != null)
            {
                m_tiff_iccprofilelength = result[0].ToInt();
                m_tiff_iccprofile = result[1].ToByteArray();
                m_pdf_colorspace = (t2p_cs_t)(m_pdf_colorspace | t2p_cs_t.T2P_CS_ICCBASED);
            }
            else
            {
                m_tiff_iccprofilelength = 0;
                m_tiff_iccprofile = null;
            }

            if (m_tiff_bitspersample == 1 && m_tiff_samplesperpixel == 1)
                m_pdf_compression = t2p_compress_t.T2P_COMPRESS_G4;
        }
Exemple #8
0
        private bool JPEGSetupDecode()
        {
            TiffDirectory td = m_tif.m_dir;

            InitializeLibJPEG(false, true);

            Debug.Assert(m_common.IsDecompressor);

            /* Read JPEGTables if it is present */
            if (m_tif.fieldSet(FIELD_JPEGTABLES))
            {
                m_decompression.Src = new JpegTablesSource(this);
                if (TIFFjpeg_read_header(false) != ReadResult.Header_Tables_Only)
                {
                    Tiff.ErrorExt(m_tif, m_tif.m_clientdata, "JPEGSetupDecode", "Bogus JPEGTables field");
                    return false;
                }
            }

            /* Grab parameters that are same for all strips/tiles */
            m_photometric = td.td_photometric;
            switch (m_photometric)
            {
                case Photometric.YCBCR:
                    m_h_sampling = td.td_ycbcrsubsampling[0];
                    m_v_sampling = td.td_ycbcrsubsampling[1];
                    break;
                default:
                    /* TIFF 6.0 forbids subsampling of all other color spaces */
                    m_h_sampling = 1;
                    m_v_sampling = 1;
                    break;
            }

            /* Set up for reading normal data */
            m_decompression.Src = new JpegStdSource(this);
            m_tif.m_postDecodeMethod = Tiff.PostDecodeMethodType.pdmNone; /* override byte swapping */
            return true;
        }
Exemple #9
0
        public static void SaveTiff(float[] data, int width, string path, float xRes = 100,
                                    float yRes = 100, ResUnit resUnit = ResUnit.CENTIMETER, Photometric photometric = Photometric.MINISBLACK)
        {
            var samplesPerPixel = 1;
            var perfectDivided  = data.Length % (samplesPerPixel * width) == 0;

            if (!perfectDivided)
            {
                throw new InvalidOperationException(
                          $"Data length({data.Length}) is incompatible with current samplesPerPixel({samplesPerPixel}) and width({width})");
            }

            var byteArray = new byte[data.Length * 4];

            Buffer.BlockCopy(data, 0, byteArray, 0, byteArray.Length);

            // Calcualte suitable ROWSPERSTRIP
            var optimalSizePerStrip       = 8000.0;
            var optimalRowsPerStripDouble = optimalSizePerStrip / sizeof(float) / width / samplesPerPixel;
            var optimalRowsPerStrip       = optimalRowsPerStripDouble < 1 ? 1 : (int)optimalRowsPerStripDouble;
            var height = data.Length / samplesPerPixel / width;

            using (Tiff image = Tiff.Open(path, "w"))
            {
                if (image == null)
                {
                    throw new InvalidOperationException($"Can not open image: {path}");
                }

                // We need to set some values for basic tags before we can add any data
                image.SetField(TiffTag.SAMPLEFORMAT, SampleFormat.IEEEFP);
                image.SetField(TiffTag.IMAGEWIDTH, width);
                image.SetField(TiffTag.IMAGELENGTH, height);
                image.SetField(TiffTag.BITSPERSAMPLE, sizeof(float) * 8);
                image.SetField(TiffTag.SAMPLESPERPIXEL, samplesPerPixel);
                image.SetField(TiffTag.ROWSPERSTRIP, optimalRowsPerStrip);
                image.SetField(TiffTag.PHOTOMETRIC, photometric);
                image.SetField(TiffTag.FILLORDER, FillOrder.MSB2LSB);
                image.SetField(TiffTag.PLANARCONFIG, PlanarConfig.CONTIG);

                image.SetField(TiffTag.XRESOLUTION, xRes);
                image.SetField(TiffTag.YRESOLUTION, yRes);
                image.SetField(TiffTag.RESOLUTIONUNIT, resUnit);

                var maxStrip         = Math.Ceiling((float)height / optimalRowsPerStrip);
                var byteCountEachRow = width * samplesPerPixel * sizeof(float);
                for (int stripIndex = 0; stripIndex < maxStrip; stripIndex++)
                {
                    // Write the information to the file
                    var currentStripLength = (stripIndex == maxStrip - 1) && (height % optimalRowsPerStrip != 0)
                        ? height % optimalRowsPerStrip
                        : optimalRowsPerStrip;
                    var offset = stripIndex * byteCountEachRow * optimalRowsPerStrip;

                    var ret = image.WriteEncodedStrip(stripIndex, byteArray, offset,
                                                      currentStripLength * byteCountEachRow);
                    if (ret == -1)
                    {
                        throw new InvalidOperationException("Error when writing the image");
                    }
                }

                // file will be auto-closed during disposal
                // but you can close image yourself
                image.Close();
            }
        }
Exemple #10
0
        public unsafe override Bitmap LoadPage(int pageNumber)
        {
            if (!File.Exists(fileName))
            {
                throw new Exception("File does not exist.");
            }

            if (bmp != null)
            {
                bmp.Dispose();
            }

            using (var tiff = Tiff.Open(fileName, "r"))
            {
                tiff.SetDirectory(Convert.ToInt16(--pageNumber));
                FieldValue[] field;
                field = tiff.GetField(TiffTag.IMAGEWIDTH);
                int pxWidth = field[0].ToInt();
                field = tiff.GetField(TiffTag.IMAGELENGTH);
                int pxHeight = field[0].ToInt();
                field = tiff.GetField(TiffTag.BITSPERSAMPLE);
                int bpp = field[0].ToInt();
                field = tiff.GetField(TiffTag.SAMPLESPERPIXEL);
                int spp    = field[0].ToInt() == 0 ? 1 : field[0].ToInt();
                int stride = tiff.ScanlineSize();

                if (bpp == 1 && spp == 1)
                {
                    try
                    {
                        bmp = new Bitmap(pxWidth, pxHeight, PixelFormat.Format1bppIndexed);
                    }
                    catch (Exception)
                    {
                        throw new Exception("Not enough memory.");
                    }
                    field = tiff.GetField(TiffTag.PHOTOMETRIC);
                    Photometric photo = (Photometric)field[0].ToInt();

                    BitmapData bdDst = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, bmp.PixelFormat);
                    byte *     pDst  = (byte *)bdDst.Scan0.ToPointer();

                    for (int y = 0; y < pxHeight; y++)
                    {
                        byte[] buffer = new byte[stride];
                        tiff.ReadScanline(buffer, y);
                        for (int x = 0; x < stride; x++)
                        {
                            pDst[y * bdDst.Stride + x] = buffer[x];
                        }
                    }

                    if (photo == Photometric.MINISBLACK)
                    {
                        for (int y = 0; y < pxHeight; y++)
                        {
                            for (int x = 0; x < bdDst.Stride; x++)
                            {
                                pDst[y * bdDst.Stride + x] ^= 0xFF;
                            }
                        }
                    }
                    pDst = null;
                    bmp.UnlockBits(bdDst);
                }
                else if (bpp == 8 && spp == 1)
                {
                    try
                    {
                        bmp = new Bitmap(pxWidth, pxHeight, PixelFormat.Format8bppIndexed);
                    }
                    catch (Exception)
                    {
                        throw new Exception("Not enough memory.");
                    }
                    BitmapData bdDst = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, bmp.PixelFormat);
                    byte *     pDst  = (byte *)bdDst.Scan0.ToPointer();

                    for (int y = 0; y < pxHeight; y++)
                    {
                        byte[] buffer = new byte[stride];
                        tiff.ReadScanline(buffer, y);
                        for (int x = 0; x < stride; x++)
                        {
                            pDst[y * bdDst.Stride + x] = buffer[x];
                        }
                    }
                    pDst = null;
                    bmp.UnlockBits(bdDst);
                }
                else if (bpp == 8 && spp == 3)
                {
                    try
                    {
                        bmp = new Bitmap(pxWidth, pxHeight, PixelFormat.Format24bppRgb);
                    }
                    catch (Exception)
                    {
                        throw new Exception("Not enough memory.");
                    }
                    BitmapData bdDst = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, bmp.PixelFormat);
                    byte *     pDst  = (byte *)bdDst.Scan0.ToPointer();

                    for (int y = 0; y < pxHeight; y++)
                    {
                        byte[] buffer = new byte[stride];
                        tiff.ReadScanline(buffer, y);

                        for (int x = 0; x < stride; x += 3)
                        {
                            pDst[y * bdDst.Stride + x]     = buffer[x + 2];
                            pDst[y * bdDst.Stride + x + 1] = buffer[x + 1];
                            pDst[y * bdDst.Stride + x + 2] = buffer[x];
                        }
                    }
                    pDst = null;
                    bmp.UnlockBits(bdDst);
                }
                else
                {
                    throw new Exception("File format not supported.");
                }
            }
            return(bmp);
        }
Exemple #11
0
        /// <summary>
        /// Write byte images, support single channel 8 bit grayscale image and 24 bit RGB image
        /// </summary>
        /// <param name="data"></param>
        /// <param name="width">Number of pixels in one row</param>
        /// <param name="samplesPerPixel">1 for grayscale image, 3 for RGB image</param>
        /// <param name="photo">
        ///     <see cref="Photometric.MINISBLACK"/> or <see cref="Photometric.MINISWHITE"/> for grayscale image
        ///     <see cref="Photometric.RGB"/> for RGB image
        /// </param>
        /// <param name="path"></param>
        /// <param name="xRes"></param>
        /// <param name="yRes"></param>
        /// <param name="resUnit"></param>
        public static void SaveTiff(byte[] data, int width, int samplesPerPixel, string path, Photometric photo = Photometric.MINISBLACK,
                                    float xRes = 100, float yRes = 100, ResUnit resUnit = ResUnit.CENTIMETER)
        {
            var optimalSizePerStrip       = 8000.0;
            var optimalRowsPerStripDouble = optimalSizePerStrip / sizeof(byte) / width / samplesPerPixel;
            var optimalRowsPerStrip       = optimalRowsPerStripDouble < 1 ? 1 : (int)optimalRowsPerStripDouble;
            var height = data.Length / width / samplesPerPixel;

            using (var output = Tiff.Open(path, "w"))
            {
                output.SetField(TiffTag.IMAGEWIDTH, width);
                output.SetField(TiffTag.IMAGELENGTH, height);
                output.SetField(TiffTag.SAMPLESPERPIXEL, samplesPerPixel);
                output.SetField(TiffTag.BITSPERSAMPLE, 8);
                output.SetField(TiffTag.ROWSPERSTRIP, optimalRowsPerStrip);
                output.SetField(TiffTag.PHOTOMETRIC, (int)photo);
                output.SetField(TiffTag.PLANARCONFIG, PlanarConfig.CONTIG);
                output.SetField(TiffTag.RESOLUTIONUNIT, resUnit);
                output.SetField(TiffTag.XRESOLUTION, xRes);
                output.SetField(TiffTag.YRESOLUTION, yRes);

                var stripCount = Math.Ceiling((float)height / optimalRowsPerStrip);

                var stripSize = optimalRowsPerStrip * width * samplesPerPixel;
                for (int stripIndex = 0; stripIndex < stripCount; stripIndex++)
                {
                    var start        = stripIndex * stripSize;
                    var bytesToWrite = (stripIndex == stripCount - 1) && (height % optimalRowsPerStrip != 0)
                        ? (height * width * samplesPerPixel - start)
                        : stripSize;
                    output.WriteEncodedStrip(stripIndex, data, start, bytesToWrite);
                }

                output.Close();
            }
        }
Exemple #12
0
        /// <summary>
        /// 读取16bittiff并转换为灰度图。bitmap的16位灰度图显示有问题,因此转换为24rgb格式,用于显示
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static Bitmap ReadDoubleByteTiffAsBmp(string path)
        {
            if (string.IsNullOrWhiteSpace(path))
            {
                throw new ArgumentNullException("path");
            }

            Bitmap result;

            using (var tif = BitMiracle.LibTiff.Classic.Tiff.Open(path, ReadMode))
            {
                FieldValue[] res    = tif.GetField(TiffTag.IMAGELENGTH);
                int          height = res[0].ToInt();

                res = tif.GetField(TiffTag.IMAGEWIDTH);
                int width = res[0].ToInt();

                res = tif.GetField(TiffTag.BITSPERSAMPLE);
                short bpp = res[0].ToShort();
                if (bpp != 16)
                {
                    return(null);
                }

                res = tif.GetField(TiffTag.SAMPLESPERPIXEL);
                short spp = res[0].ToShort();
                if (spp != 1)
                {
                    return(null);
                }

                res = tif.GetField(TiffTag.PHOTOMETRIC);
                Photometric photo = (Photometric)res[0].ToInt();
                if (photo != Photometric.MINISBLACK && photo != Photometric.MINISWHITE)
                {
                    return(null);
                }

                int    stride = tif.ScanlineSize();
                byte[] buffer = new byte[stride];

                result = new Bitmap(width, height, PixelFormat.Format24bppRgb);
                byte[] buffer8Bit = null;

                for (int i = 0; i < height; i++)
                {
                    Rectangle  imgRect = new Rectangle(0, i, width, 1);
                    BitmapData imgData = result.LockBits(imgRect, ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);

                    if (buffer8Bit == null)
                    {
                        buffer8Bit = new byte[imgData.Stride];
                    }
                    else
                    {
                        Array.Clear(buffer8Bit, 0, buffer8Bit.Length);
                    }

                    tif.ReadScanline(buffer, i);
                    ConvertBuffer(buffer, buffer8Bit);

                    Marshal.Copy(buffer8Bit, 0, imgData.Scan0, buffer8Bit.Length);
                    result.UnlockBits(imgData);
                }
            }

            return(result);
        }
Exemple #13
0
 private static DoubleByteTiffInfo CreateDoubleByteTiffInfo(byte[] buffer, List <ushort[]> ushortBuffer, int width,
                                                            int height, string filePath,
                                                            int rowsPerStrip,
                                                            int xResolution, int yResolution, ResUnit resUnit = ResUnit.INCH,
                                                            PlanarConfig planarConfig = PlanarConfig.CONTIG,
                                                            int bytePerSample         = 16, Photometric photometric = Photometric.MINISBLACK,
                                                            Compression compression   = Compression.NONE,
                                                            int samplePerPixel        = 1, Orientation orientation = Orientation.TOPLEFT,
                                                            FillOrder fillOrder       = FillOrder.MSB2LSB)
 {
     return(new DoubleByteTiffInfo()
     {
         FilePath = filePath,
         Buffer = buffer,
         UshortBuffer = ushortBuffer,
         Width = width,
         Height = height,
         RowsPerStrip = rowsPerStrip,
         XResolution = xResolution,
         YResolution = yResolution,
         ResolutionUnit = resUnit,
         PlanarConfig = planarConfig,
         BitsPerSample = bytePerSample,
         Photometric = photometric,
         Compression = compression,
         SamplesPerPixel = samplePerPixel,
         Orientation = orientation,
         FillOrder = fillOrder
     });
 }
Exemple #14
0
        public override bool Init()
        {
            Debug.Assert(m_scheme == Compression.JPEG);

            /*
            * Merge codec-specific tag information and override parent get/set
            * field methods.
            */
            m_tif.MergeFieldInfo(jpegFieldInfo, jpegFieldInfo.Length);

            /*
             * Allocate state block so tag methods have storage to record values.
             */
            m_compression = null;
            m_decompression = null;
            m_photometric = 0;
            m_h_sampling = 0;
            m_v_sampling = 0;
            m_bytesperline = 0;
            m_scancount = 0;
            m_samplesperclump = 0;
            m_recvtime = 0;

            m_parentTagMethods = m_tif.m_tagmethods;
            m_tif.m_tagmethods = m_tagMethods;

            /* Default values for codec-specific fields */
            m_jpegtables = null;
            m_jpegtables_length = 0;
            m_jpegquality = 75; /* Default IJG quality */
            m_jpegcolormode = JpegColorMode.RGB;
            m_jpegtablesmode = JpegTablesMode.Quant | JpegTablesMode.Huff;

            m_recvparams = 0;
            m_subaddress = null;
            m_faxdcs = null;

            m_ycbcrsampling_fetched = false;

            m_rawDecode = false;
            m_rawEncode = false;
            m_tif.m_flags |= TiffFlags.NoBitRev; // no bit reversal, please

            m_cinfo_initialized = false;

            /*
             ** Create a JPEGTables field if no directory has yet been created. 
             ** We do this just to ensure that sufficient space is reserved for
             ** the JPEGTables field.  It will be properly created the right
             ** size later. 
             */
            if (m_tif.m_diroff == 0)
            {
                const int SIZE_OF_JPEGTABLES = 2000;

                // The following line assumes incorrectly that all JPEG-in-TIFF
                // files will have a JpegTables tag generated and causes
                // null-filled JpegTables tags to be written when the JPEG data
                // is placed with WriteRawStrip. The field bit should be 
                // set, anyway, later when actual JpegTables header is
                // generated, so removing it here hopefully is harmless.
                //
                //       m_tif.setFieldBit(FIELD_JPEGTABLES);
                //

                m_jpegtables_length = SIZE_OF_JPEGTABLES;
                m_jpegtables = new byte[m_jpegtables_length];
            }

            /*
             * Mark the YCBCRSAMPLES as present even if it is not
             * see: JPEGFixupTestSubsampling().
             */
            m_tif.setFieldBit(FieldBit.YCbCrSubsampling);
            return true;
        }
Exemple #15
0
        private void cleanState()
        {
            m_compression = null;
            m_decompression = null;
            m_common = null;

            m_h_sampling = 0;
            m_v_sampling = 0;

            m_jpegtables = null;
            m_jpegtables_length = 0;
            m_jpegquality = 0;
            m_jpegcolormode = 0;
            m_jpegtablesmode = 0;

            m_ycbcrsampling_fetched = false;

            m_recvparams = 0;
            m_subaddress = null;
            m_recvtime = 0;
            m_faxdcs = null;
            m_rawDecode = false;
            m_rawEncode = false;

            m_cinfo_initialized = false;

            m_err = null;
            m_photometric = 0;

            m_bytesperline = 0;
            m_ds_buffer = new byte[JpegConstants.MAX_COMPONENTS][][];
            m_scancount = 0;
            m_samplesperclump = 0;
        }
Exemple #16
0
        private bool JPEGSetupEncode()
        {
            const string module = "JPEGSetupEncode";

            InitializeLibJPEG(true, false);

            Debug.Assert(!m_common.IsDecompressor);

            /*
             * Initialize all JPEG parameters to default values.
             * Note that jpeg_set_defaults needs legal values for
             * in_color_space and input_components.
             */
            m_compression.In_color_space = ColorSpace.Unknown;
            m_compression.Input_components = 1;
            if (!TIFFjpeg_set_defaults())
                return false;

            /* Set per-file parameters */
            m_photometric = m_tif.m_dir.td_photometric;
            switch (m_photometric)
            {
                case Photometric.YCBCR:
                    m_h_sampling = m_tif.m_dir.td_ycbcrsubsampling[0];
                    m_v_sampling = m_tif.m_dir.td_ycbcrsubsampling[1];
                    /*
                     * A ReferenceBlackWhite field *must* be present since the
                     * default value is inappropriate for YCbCr.  Fill in the
                     * proper value if application didn't set it.
                     */
                    FieldValue[] result = m_tif.GetField(TiffTag.REFERENCEBLACKWHITE);
                    if (result == null)
                    {
                        float[] refbw = new float[6];
                        int top = 1 << m_tif.m_dir.td_bitspersample;
                        refbw[0] = 0;
                        refbw[1] = (float)(top - 1L);
                        refbw[2] = (float)(top >> 1);
                        refbw[3] = refbw[1];
                        refbw[4] = refbw[2];
                        refbw[5] = refbw[1];
                        m_tif.SetField(TiffTag.REFERENCEBLACKWHITE, refbw);
                    }
                    break;

                /* disallowed by Tech Note */
                case Photometric.Palette:
                case Photometric.Mask:
                    Tiff.ErrorExt(m_tif, m_tif.m_clientdata, module,
                        "PhotometricInterpretation {0} not allowed for JPEG", m_photometric);
                    return false;

                default:
                    /* TIFF 6.0 forbids subsampling of all other color spaces */
                    m_h_sampling = 1;
                    m_v_sampling = 1;
                    break;
            }

            /* Verify miscellaneous parameters */

            // This would need work if LibTiff.Net ever supports different
            // depths for different components, or if LibJpeg.Net ever supports
            // run-time selection of depth.  Neither is imminent.
            if (m_tif.m_dir.td_bitspersample != JpegConstants.BitsInSample)
            {
                Tiff.ErrorExt(m_tif, m_tif.m_clientdata, module,
                    "BitsPerSample {0} not allowed for JPEG", m_tif.m_dir.td_bitspersample);
                return false;
            }

            m_compression.Data_precision = m_tif.m_dir.td_bitspersample;
            if (m_tif.IsTiled())
            {
                if ((m_tif.m_dir.td_tilelength % (m_v_sampling * JpegConstants.DCTSize)) != 0)
                {
                    Tiff.ErrorExt(m_tif, m_tif.m_clientdata, module,
                        "JPEG tile height must be multiple of {0}", m_v_sampling * JpegConstants.DCTSize);
                    return false;
                }

                if ((m_tif.m_dir.td_tilewidth % (m_h_sampling * JpegConstants.DCTSize)) != 0)
                {
                    Tiff.ErrorExt(m_tif, m_tif.m_clientdata, module,
                        "JPEG tile width must be multiple of {0}", m_h_sampling * JpegConstants.DCTSize);
                    return false;
                }
            }
            else
            {
                if (m_tif.m_dir.td_rowsperstrip < m_tif.m_dir.td_imagelength &&
                    (m_tif.m_dir.td_rowsperstrip % (m_v_sampling * JpegConstants.DCTSize)) != 0)
                {
                    Tiff.ErrorExt(m_tif, m_tif.m_clientdata, module,
                        "RowsPerStrip must be multiple of {0} for JPEG", m_v_sampling * JpegConstants.DCTSize);
                    return false;
                }
            }

            /* Create a JPEGTables field if appropriate */
            if ((m_jpegtablesmode & (JpegTablesMode.Quant | JpegTablesMode.Huff)) != 0)
            {
                bool startsWithZeroes = true;
                if (m_jpegtables != null)
                {
                    for (int i = 0; i < 8; i++)
                    {
                        if (m_jpegtables[i] != 0)
                        {
                            startsWithZeroes = false;
                            break;
                        }
                    }
                }
                else
                {
                    startsWithZeroes = false;
                }

                if (m_jpegtables == null || startsWithZeroes)
                {
                    if (!prepare_JPEGTables())
                        return false;

                    /* Mark the field present */
                    /* Can't use TIFFSetField since BeenWriting is already set! */
                    m_tif.m_flags |= TiffFlags.DirtyDirect;
                    m_tif.setFieldBit(FIELD_JPEGTABLES);
                }
            }
            else
            {
                /* We do not support application-supplied JPEGTables, */
                /* so mark the field not present */
                m_tif.clearFieldBit(FIELD_JPEGTABLES);
            }

            /* Direct LibJpeg.Net output to LibTiff.Net's output buffer */
            TIFFjpeg_data_dest();

            return true;
        }
        public TiffDirectory()
        {
            td_subfiletype = 0;
            td_compression = 0;
            td_photometric = 0;
            td_planarconfig = 0;

            td_fillorder = FillOrder.MSB2LSB;
            td_bitspersample = 1;
            td_threshholding = Threshold.BILEVEL;
            td_orientation = Orientation.TOPLEFT;
            td_samplesperpixel = 1;
            td_rowsperstrip = -1;
            td_tiledepth = 1;
            td_stripbytecountsorted = true; // Our own arrays always sorted.
            td_resolutionunit = ResUnit.INCH;
            td_sampleformat = SampleFormat.UINT;
            td_imagedepth = 1;
            td_ycbcrsubsampling[0] = 2;
            td_ycbcrsubsampling[1] = 2;
            td_ycbcrpositioning = YCbCrPosition.CENTERED;
        }
Exemple #18
0
        public TiffDirectory()
        {
            td_subfiletype = 0;
            td_compression = 0;
            td_photometric = 0;
            td_planarconfig = 0;

            td_fillorder = BitOrder.BigEndian;
            td_bitspersample = 1;
            td_threshholding = Threshold.BILevel;
            td_orientation = Orientation.TopLeft;
            td_samplesperpixel = 1;
            td_rowsperstrip = -1;
            td_tiledepth = 1;
            td_stripbytecountsorted = true; // Our own arrays always sorted.
            td_resolutionunit = ResolutionUnit.Inch;
            td_sampleformat = SampleFormat.UInt;
            td_imagedepth = 1;
            td_ycbcrsubsampling[0] = 2;
            td_ycbcrsubsampling[1] = 2;
            td_ycbcrpositioning = YCbCrPosition.Centered;
        }
        private bool _CheckStackImages(string stackFolder, string formatFile, Boolean create = false)
        {
            try
            {
                string   getFileFormat = formatFile.Replace("[x]", "*").Replace("[nm]", "*").Replace("[t]", "*");
                string[] files         = Directory.GetFiles(stackFolder, getFileFormat, System.IO.SearchOption.TopDirectoryOnly);

                string regex_str_473  = formatFile.Replace("[x]", @"([\d]{1})").Replace("[nm]", "473").Replace("[t]", @"([\d]+)").Replace(".", @"\.");
                Regex  regex_file_473 = new Regex(@"" + regex_str_473 + "$", RegexOptions.IgnoreCase);

                string regex_str_561  = formatFile.Replace("[x]", @"([\d]{1})").Replace("[nm]", "561").Replace("[t]", @"([\d]+)").Replace(".", @"\.");
                Regex  regex_file_561 = new Regex(@"" + regex_str_561 + "$", RegexOptions.IgnoreCase);

                int tcount_473 = 0;
                int tcount_561 = 0;
                int fd_count   = 0;
                int width      = 0;
                int height     = 0;

                foreach (string stackFile in files)
                {
                    string filename = Path.GetFileName(stackFile);

                    Match match_file_473 = regex_file_473.Match(filename);
                    Match match_file_561 = regex_file_561.Match(filename);
                    if (match_file_473.Success)
                    {
                        tcount_473++;
                    }
                    if (match_file_561.Success)
                    {
                        tcount_561++;
                    }
                    if ((match_file_473.Success || match_file_561.Success) && (fd_count == 0 || width == 0 || height == 0))
                    {
                        using (Tiff tif = Tiff.Open(stackFile, "r"))
                        {
                            FieldValue[] value = tif.GetField(TiffTag.IMAGEWIDTH);
                            width = value[0].ToInt();

                            value = tif.GetField(TiffTag.BITSPERSAMPLE);
                            short bpp = value[0].ToShort();
                            if (bpp != 16)
                            {
                                this.SetError("ファイルの種類が16bitではありません。");
                                return(false);
                            }
                            value = tif.GetField(TiffTag.SAMPLESPERPIXEL);
                            short spp = value[0].ToShort();
                            if (spp != 1)
                            {
                                this.SetError("ファイルが解析できませんでした。");
                                return(false);
                            }

                            value = tif.GetField(TiffTag.PHOTOMETRIC);
                            Photometric photo = (Photometric)value[0].ToInt();
                            if (photo != Photometric.MINISBLACK && photo != Photometric.MINISWHITE)
                            {
                                this.SetError("ファイルが解析できませんでした。");
                                return(false);
                            }

                            value  = tif.GetField(TiffTag.IMAGELENGTH);
                            height = value[0].ToInt();

                            fd_count = 1;
                            while (tif.ReadDirectory())
                            {
                                fd_count += 1;
                            }
                        }
                        //Image img = Image.FromFile(stackFile);

                        //FrameDimension fd = new FrameDimension(img.FrameDimensionsList[0]);
                        //fd_count = img.GetFrameCount(fd);
                        //width = img.Width;
                        //height = img.Height;

                        //img.Dispose();
                    }
                }

                if (tcount_473 == 0)
                {
                    this.SetError("473のファイルがみつかりませんでした。");
                    return(false);
                }

                if (tcount_561 == 0)
                {
                    this.SetError("561のファイルがみつかりませんでした。");
                    return(false);
                }

                if (fd_count == 0)
                {
                    this.SetError("Stackファイルが見つかりませんでした。");
                    return(false);
                }

                if (create == false)
                {
                    this.T = (tcount_473 < tcount_561) ? tcount_473 : tcount_561;
                    this.Z = (int)(System.Math.Floor((double)(fd_count)));
                    this.C = 1;
                    this.X = width;
                    this.Y = height;
                }

                return(true);
            }
            catch (Exception e)
            {
                this.SetError(e.Message);
                return(false);
            }
        }