GetField() public method

Gets the value(s) of a tag in an open TIFF file.

GetField returns the value(s) of a tag or pseudo-tag associated with the current directory of the opened TIFF file. The tag is identified by tag. The type and number of values returned is dependent on the tag being requested. You may want to consult "Well-known tags and their value(s) data types" to become familiar with exact data types and calling conventions required for each tag supported by the library.

A pseudo-tag is a parameter that is used to control the operation of the library but whose value is not read or written to the underlying file.

public GetField ( TiffTag tag ) : BitMiracle.LibTiff.Classic.FieldValue[]
tag TiffTag The tag.
return BitMiracle.LibTiff.Classic.FieldValue[]
コード例 #1
0
ファイル: Converter.cs プロジェクト: XiBeichuan/hydronumerics
        public bool tiffcvt(Tiff inImage, Tiff outImage)
        {
            FieldValue[] result = inImage.GetField(TiffTag.IMAGEWIDTH);
            if (result == null)
                return false;
            int width = result[0].ToInt();

            result = inImage.GetField(TiffTag.IMAGELENGTH);
            if (result == null)
                return false;
            int height = result[0].ToInt();

            copyField(inImage, outImage, TiffTag.SUBFILETYPE);
            outImage.SetField(TiffTag.IMAGEWIDTH, width);
            outImage.SetField(TiffTag.IMAGELENGTH, height);
            outImage.SetField(TiffTag.BITSPERSAMPLE, 8);
            outImage.SetField(TiffTag.COMPRESSION, m_compression);
            outImage.SetField(TiffTag.PHOTOMETRIC, Photometric.RGB);

            copyField(inImage, outImage, TiffTag.FILLORDER);
            outImage.SetField(TiffTag.ORIENTATION, Orientation.TOPLEFT);

            if (m_noAlpha)
                outImage.SetField(TiffTag.SAMPLESPERPIXEL, 3);
            else
                outImage.SetField(TiffTag.SAMPLESPERPIXEL, 4);

            if (!m_noAlpha)
            {
                short[] v = new short[1];
                v[0] = (short)ExtraSample.ASSOCALPHA;
                outImage.SetField(TiffTag.EXTRASAMPLES, 1, v);
            }

            copyField(inImage, outImage, TiffTag.XRESOLUTION);
            copyField(inImage, outImage, TiffTag.YRESOLUTION);
            copyField(inImage, outImage, TiffTag.RESOLUTIONUNIT);
            outImage.SetField(TiffTag.PLANARCONFIG, PlanarConfig.CONTIG);

            if (!m_testFriendly)
                outImage.SetField(TiffTag.SOFTWARE, Tiff.GetVersion());

            copyField(inImage, outImage, TiffTag.DOCUMENTNAME);
            
            if (m_processByBlock && inImage.IsTiled())
                return cvt_by_tile(inImage, outImage, width, height);
            else if (m_processByBlock)
                return cvt_by_strip(inImage, outImage, width, height);

            return cvt_whole_image(inImage, outImage, width, height);
        }
コード例 #2
0
        private static Metadata ReadMetadata(T.Tiff tiff, int defaultTileWidth)
        {
            var x      = tiff.GetField(T.TiffTag.IMAGEWIDTH);
            int width  = tiff.GetField(T.TiffTag.IMAGEWIDTH)[0].ToInt();
            int height = tiff.GetField(T.TiffTag.IMAGELENGTH)[0].ToInt();
            var twtag  = tiff.GetField(T.TiffTag.TILEWIDTH);

            var tileWidth = twtag == null ? defaultTileWidth : twtag[0].ToInt();

            return(new Metadata
            {
                Width = width,
                Height = height,
                TileWidth = tileWidth,
                ScalingLevels = (int)(Math.Floor(Math.Log(Math.Max(width, height), 2)) - 3)
            });
        }
コード例 #3
0
        private static (ProcessState state, SKImage image) ReadFullImage(T.Tiff tiff, ImageRequest request, bool allowSizeAboveFull)
        {
            int width  = tiff.GetField(T.TiffTag.IMAGEWIDTH)[0].ToInt();
            int height = tiff.GetField(T.TiffTag.IMAGELENGTH)[0].ToInt();

            var restag  = tiff.GetField(T.TiffTag.RESOLUTIONUNIT);
            var xrestag = tiff.GetField(T.TiffTag.XRESOLUTION);
            var yrestag = tiff.GetField(T.TiffTag.YRESOLUTION);

            var resunit = restag == null ? 2 : restag[0].ToShort();
            var xres    = xrestag == null ? 96 : xrestag[0].ToDouble();
            var yres    = yrestag == null ? 96 : yrestag[0].ToDouble();

            // pixels per metre
            if (resunit == 3)
            {
                xres = xres / 0.0254;
                yres = yres / 0.0254;
            }

            var isTileable = tiff.IsTiled();
            var state      = ImageRequestInterpreter.GetInterpretedValues(request, width, height, allowSizeAboveFull);

            state.HorizontalResolution = Convert.ToUInt16(xres);
            state.VerticalResolution   = Convert.ToUInt16(yres);
            var raster = new int[width * height];

            if (!tiff.ReadRGBAImageOriented(width, height, raster, T.Orientation.TOPLEFT))
            {
                throw new IOException("Unable to decode TIFF file");
            }
            using (var bmp = CreateBitmapFromPixels(raster, width, height))
            {
                var desiredWidth  = Math.Max(1, (int)Math.Round(state.RegionWidth * state.ImageScale));
                var desiredHeight = Math.Max(1, (int)Math.Round(state.RegionHeight * state.ImageScale));
                Log.Debug("Desired size {@DesiredWidth}, {@DesiredHeight}", desiredWidth, desiredHeight);

                var regionWidth  = state.RegionWidth;
                var regionHeight = state.RegionHeight;

                var srcRegion = SKRectI.Create(state.StartX, state.StartY, regionWidth, regionHeight);
                return(state, CopyImageRegion2(bmp, desiredWidth, desiredHeight, srcRegion));
            }
        }
コード例 #4
0
ファイル: TiffGrid.cs プロジェクト: XiBeichuan/hydronumerics
    public TiffGrid(string FileName)
    {

      string fname = Path.GetFullPath(FileName);

      tiff = Tiff.Open(FileName, "r");
      var val = tiff.GetField((TiffTag)33922)[1].ToDoubleArray();
      XOrigin = val[3];
      YOrigin = val[4]; //Upper basegrid assumes Lower
      val = tiff.GetField((TiffTag)33550)[1].ToDoubleArray();
      GridSize = val[0];
      GridSize = val[1];
      NumberOfColumns = tiff.GetField(TiffTag.IMAGEWIDTH)[0].ToInt();
      NumberOfRows = tiff.GetField(TiffTag.IMAGELENGTH)[0].ToInt();
      scanline = new byte[tiff.ScanlineSize()];
      bits = tiff.ScanlineSize() / NumberOfColumns;
      ScanLineCache = new Dictionary<int, byte[]>();

      
    }
コード例 #5
0
        public TiffGrid(string FileName)
    {

      string fname = Path.GetFullPath(FileName);
      if (!File.Exists(fname))
        return;
        tiff = BitMiracle.LibTiff.Classic.Tiff.Open(FileName, "r");
      
      var val = tiff.GetField((TiffTag)33922)[1].ToDoubleArray();
      XOrigin = val[3];
      YOrigin = val[4]; //Upper basegrid assumes Lower
      val = tiff.GetField((TiffTag)33550)[1].ToDoubleArray();
      GridSize = val[0];
      GridSize = val[1];
      NumberOfColumns = tiff.GetField(TiffTag.IMAGEWIDTH)[0].ToInt();
      NumberOfRows = tiff.GetField(TiffTag.IMAGELENGTH)[0].ToInt();

      //Shift YOrigin to lower left
      YOrigin -= GridSize * NumberOfRows;
      scanline = new byte[tiff.ScanlineSize()];
      bits = scanline.Count() / NumberOfColumns;
      ScanLineCache = new Dictionary<int, byte[]>();
      
    }
コード例 #6
0
        private static void PrintTagInfo(Tiff tiff, TiffTag tiffTag)
        {
            try
            {
                var field = tiff.GetField(tiffTag);
                if (field != null)
                {
                    Console.WriteLine($"{tiffTag}");
                    for (int i = 0; i < field.Length; i++)
                    {
                        Console.WriteLine($"  [{i}] {field[i].Value}");
                        byte[] bytes = field[i].Value as byte[];
                        if (bytes != null)
                        {
                            Console.WriteLine($"    Length: {bytes.Length}");
                            if (bytes.Length % 8 == 0)
                            {
                                for (int k = 0; k < bytes.Length / 8; k++)
                                {
                                    Console.WriteLine($"      [{k}] {BitConverter.ToDouble(bytes, k * 8)}");
                                }
                            }

                            try
                            {
                                Console.WriteLine($"   > {System.Text.Encoding.ASCII.GetString(bytes).Trim()} < ");
                            }
                            catch (Exception ex)
                            {

                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"ERROR: {tiffTag}");
            }
        }
コード例 #7
0
    public TiffGrid(string filename, string NewFileName)
    {
      ValuesToWrite = new Dictionary<int, Dictionary<int, double>>();

      tiff_org = BitMiracle.LibTiff.Classic.Tiff.Open(Path.GetFullPath(filename), "r");

      tiff = BitMiracle.LibTiff.Classic.Tiff.Open(Path.GetFullPath(NewFileName), "w");
      foreach (TiffTag enu in Enum.GetValues(typeof(TiffTag)))
      {
        var val = tiff_org.GetField(enu);
        if (val != null & enu != TiffTag.EXTRASAMPLES)
          tiff.SetField(enu, val[0]);
      }

      for (int i = 0; i < tiff_org.GetTagListCount(); i++)
      {
        int k = tiff_org.GetTagListEntry(i);
        var ff = tiff_org.FindFieldInfo((TiffTag)k, TiffType.ANY);
        tiff.MergeFieldInfo(new TiffFieldInfo[] { ff }, 1);
        var val = tiff_org.GetField((TiffTag)tiff_org.GetTagListEntry(i));
        tiff.SetField((TiffTag)k, val[0], val[1]);
      }

      var val2 = tiff_org.GetField((TiffTag)33922)[1].ToDoubleArray();
      XOrigin = val2[3];
      YOrigin = val2[4]; //Upper basegrid assumes Lower
      val2 = tiff_org.GetField((TiffTag)33550)[1].ToDoubleArray();
      GridSize = val2[0];
      GridSize = val2[1];
      NumberOfColumns = tiff_org.GetField(TiffTag.IMAGEWIDTH)[0].ToInt();
      NumberOfRows = tiff_org.GetField(TiffTag.IMAGELENGTH)[0].ToInt();

      //Shift YOrigin to lower left
      YOrigin -= GridSize * NumberOfRows;
      scanline = new byte[tiff_org.ScanlineSize()];
      bits = scanline.Count() / NumberOfColumns;
      ScanLineCache = new Dictionary<int, byte[]>();




    }
コード例 #8
0
ファイル: T2P.cs プロジェクト: dronab/libtiff.net
        /*
        This function returns the necessary size of a data buffer to contain the raw or 
        uncompressed image data from the input TIFF for a page.
        */
        private void read_tiff_size(Tiff input)
        {
            if (m_pdf_transcode == t2p_transcode_t.T2P_TRANSCODE_RAW)
            {
                FieldValue[] result = null;
                if (m_pdf_compression == t2p_compress_t.T2P_COMPRESS_G4)
                {
                    result = input.GetField(TiffTag.STRIPBYTECOUNTS);
                    int[] sbc = result[0].ToIntArray();
                    m_tiff_datasize = sbc[0];
                    return;
                }

                if (m_pdf_compression == t2p_compress_t.T2P_COMPRESS_ZIP)
                {
                    result = input.GetField(TiffTag.STRIPBYTECOUNTS);
                    int[] sbc = result[0].ToIntArray();
                    m_tiff_datasize = sbc[0];
                    return;
                }
                
                if (m_tiff_compression == Compression.JPEG)
                {
                    result = input.GetField(TiffTag.JPEGTABLES);
                    if (result != null)
                    {
                        int count = result[0].ToInt();
                        if (count > 4)
                        {
                            m_tiff_datasize += count;
                            m_tiff_datasize -= 2; /* don't use EOI of header */
                        }
                    }
                    else
                    {
                        m_tiff_datasize = 2; /* SOI for first strip */
                    }

                    int stripcount = input.NumberOfStrips();
                    int[] sbc = null;
                    result = input.GetField(TiffTag.STRIPBYTECOUNTS);
                    if (result == null)
                    {
                        Tiff.Error(Tiff2PdfConstants.TIFF2PDF_MODULE,
                            "Input file {0} missing field: STRIPBYTECOUNTS",
                            input.FileName());
                        m_error = true;
                        return;
                    }
                    else
                        sbc = result[0].ToIntArray();

                    for (int i = 0; i < stripcount; i++)
                    {
                        m_tiff_datasize += sbc[i];
                        m_tiff_datasize -= 4; /* don't use SOI or EOI of strip */
                    }
                    
                    m_tiff_datasize += 2; /* use EOI of last strip */
                    return;
                }
            }

            m_tiff_datasize = input.ScanlineSize() * m_tiff_length;
            if (m_tiff_planar == PlanarConfig.SEPARATE)
                m_tiff_datasize *= m_tiff_samplesperpixel;
        }
コード例 #9
0
        //Load tiff to display for the first time
        private bool LoadTiff(string tiffname)
        {
            int[] xyOffsets;
            using (image = Tiff.Open(tiffname, "r"))
            {
                if (image == null)
                {
                    MessageBox.Show("Could not open incoming image");
                    return false;
                }

                // Find the width and height of the image
                FieldValue[] value = image.GetField(TiffTag.TILEWIDTH);
                tileWidth = value[0].ToInt();

                value = image.GetField(TiffTag.TILELENGTH);
                tileHeight = value[0].ToInt();

                tileSize = tileHeight * tileWidth;

                // For the column and row calculations we round up
                // because .21 or .55 of a column/row is still another
                // tile even if it isn't a complete tile.

                //find the number of tile columns
                value = image.GetField(TiffTag.IMAGEWIDTH);
                imageWidth = value[0].ToInt();
                numOfColumns = imageWidth / tileWidth + 1;

                //find the number of tile rows
                value = image.GetField(TiffTag.IMAGELENGTH);
                imageHeight = value[0].ToInt();
                numOfRows = imageHeight / tileHeight + 1;

                //find the number of bands
                value = image.GetField(TiffTag.SAMPLESPERPIXEL);
                numOfBands = value[0].ToInt();
                MainParent.RadianceNumBandsTB.Text = numOfBands.ToString();

                xyOffsets = AnalyzeTiff();
                createBase(xyOffsets[0], xyOffsets[1]);
                checkPreviewState();
                this.Text = tiffname;
                return true;
            }
        }
コード例 #10
0
ファイル: T2P.cs プロジェクト: dronab/libtiff.net
        /*
        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;
        }
コード例 #11
0
ファイル: T2P.cs プロジェクト: dronab/libtiff.net
        /*
        This function scans the input TIFF file for pages.  It attempts
        to determine which IFD's of the TIFF file contain image document
        pages.  For each, it gathers some information that has to do
        with the output of the PDF document as a whole.  
        */
        private void read_tiff_init(Tiff input)
        {
            short directorycount = input.NumberOfDirectories();
            m_tiff_pages = new T2P_PAGE [directorycount];
            for (int p = 0; p < directorycount; p++)
                m_tiff_pages[p] = new T2P_PAGE();

            FieldValue[] result = null;

            for (short i = 0; i < directorycount; i++)
            {
                int subfiletype = 0;

                if (!input.SetDirectory(i))
                {
                    Tiff.Error(Tiff2PdfConstants.TIFF2PDF_MODULE, 
                        "Can't set directory {0} of input file {1}", i, input.FileName());
                    return;
                }

                result = input.GetField(TiffTag.PAGENUMBER);
                if (result != null)
                {
                    short pagen = result[0].ToShort();
                    short paged = result[1].ToShort();

                    if ((pagen > paged) && (paged != 0))
                        m_tiff_pages[m_tiff_pagecount].page_number = paged;
                    else
                        m_tiff_pages[m_tiff_pagecount].page_number = pagen;
                }
                else
                {
                    result = input.GetField(TiffTag.SUBFILETYPE);
                    if (result != null)
                    {
                        subfiletype = result[0].ToInt();
                        if ((((FileType)subfiletype & FileType.PAGE) == 0) && (subfiletype != 0))
                            continue;
                    }
                    else
                    {
                        result = input.GetField(TiffTag.OSUBFILETYPE);
                        if (result != null)
                        {
                            subfiletype = result[0].ToInt();
                            if (((OFileType)subfiletype != OFileType.IMAGE) && ((OFileType)subfiletype != OFileType.PAGE) && (subfiletype != 0))
                                continue;
                        }
                    }

                    m_tiff_pages[m_tiff_pagecount].page_number = m_tiff_pagecount;
                }

                m_tiff_pages[m_tiff_pagecount].page_directory = i;

                if (input.IsTiled())
                    m_tiff_pages[m_tiff_pagecount].page_tilecount = input.NumberOfTiles();
                
                m_tiff_pagecount++;
            }

            IComparer myComparer = new cmp_t2p_page();
            Array.Sort(m_tiff_pages, myComparer);

            for (short i = 0; i < m_tiff_pagecount; i++)
            {
                m_pdf_xrefcount += 5;
                input.SetDirectory(m_tiff_pages[i].page_directory);

                result = input.GetField(TiffTag.PHOTOMETRIC);
                if ((result != null && ((Photometric)result[0].ToInt() == Photometric.PALETTE)) || input.GetField(TiffTag.INDEXED) != null)
                {
                    m_tiff_pages[i].page_extra++;
                    m_pdf_xrefcount++;
                }

                result = input.GetField(TiffTag.COMPRESSION);
                if (result != null)
                {
                    Compression xuint16 = (Compression)result[0].ToInt();
                    if ((xuint16 == Compression.DEFLATE || xuint16 == Compression.ADOBE_DEFLATE) 
                        && ((m_tiff_pages[i].page_tilecount != 0) || input.NumberOfStrips() == 1) 
                        && !m_pdf_nopassthrough)
                    {
                        if (m_pdf_minorversion < 2)
                            m_pdf_minorversion = 2;
                    }
                }

                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;
                        m_tiff_pages[i].page_extra += 4;
                        m_pdf_xrefcount += 4;
                    }
                    else
                    {
                        m_tiff_transferfunctioncount = 1;
                        m_tiff_pages[i].page_extra += 2;
                        m_pdf_xrefcount += 2;
                    }

                    if (m_pdf_minorversion < 2)
                        m_pdf_minorversion = 2;
                }
                else
                {
                    m_tiff_transferfunctioncount = 0;
                }

                result = input.GetField(TiffTag.ICCPROFILE);
                if (result != null)
                {
                    m_tiff_iccprofilelength = result[0].ToInt();
                    m_tiff_iccprofile = result[1].ToByteArray();

                    m_tiff_pages[i].page_extra++;
                    m_pdf_xrefcount++;
                    if (m_pdf_minorversion < 3)
                        m_pdf_minorversion = 3;
                }

                //m_tiff_tiles[i].tiles_tilecount = m_tiff_pages[i].page_tilecount;

                result = input.GetField(TiffTag.PLANARCONFIG);
                if (result != null && ((PlanarConfig)result[0].ToShort() == PlanarConfig.SEPARATE))
                {
                    result = input.GetField(TiffTag.SAMPLESPERPIXEL);
                    int xuint16 = result[0].ToInt();
                    m_tiff_pages[i].page_tilecount /= xuint16;
                }

                if (m_tiff_pages[i].page_tilecount > 0)
                {
                    m_pdf_xrefcount += (m_tiff_pages[i].page_tilecount - 1) * 2;
                    result = input.GetField(TiffTag.TILEWIDTH);
                    m_tiff_pages[i].tiles_tilewidth = result[0].ToInt();

                    input.GetField(TiffTag.TILELENGTH);
                    m_tiff_pages[i].tiles_tilelength = result[0].ToInt();

                    m_tiff_pages[i].tiles_tiles = new T2P_TILE[m_tiff_pages[i].page_tilecount];
                    for (int idx = 0; idx < m_tiff_pages[i].page_tilecount; idx++)
                        m_tiff_pages[i].tiles_tiles[idx] = new T2P_TILE();
                }
            }
        }
コード例 #12
0
ファイル: T2P.cs プロジェクト: dronab/libtiff.net
        /*
        * This function fills a string of a T2P struct with the date and time of a
        * TIFF file if it exists or the current time as a PDF date string.
        */
        private void pdf_tifftime(Tiff input)
        {
            FieldValue[] result = input.GetField(TiffTag.DATETIME);
            if (result != null && (result[0].ToString()).Length >= 19)
            {
                string datetime = result[0].ToString();

                m_pdf_datetime = new byte[16];
                m_pdf_datetime[0] = (byte)'D';
                m_pdf_datetime[1] = (byte)':';
                m_pdf_datetime[2] = (byte)datetime[0];
                m_pdf_datetime[3] = (byte)datetime[1];
                m_pdf_datetime[4] = (byte)datetime[2];
                m_pdf_datetime[5] = (byte)datetime[3];
                m_pdf_datetime[6] = (byte)datetime[5];
                m_pdf_datetime[7] = (byte)datetime[6];
                m_pdf_datetime[8] = (byte)datetime[8];
                m_pdf_datetime[9] = (byte)datetime[9];
                m_pdf_datetime[10] = (byte)datetime[11];
                m_pdf_datetime[11] = (byte)datetime[12];
                m_pdf_datetime[12] = (byte)datetime[14];
                m_pdf_datetime[13] = (byte)datetime[15];
                m_pdf_datetime[14] = (byte)datetime[17];
                m_pdf_datetime[15] = (byte)datetime[18];
            }
            else
            {
                pdf_currenttime();
            }
        }
コード例 #13
0
        /// <summary>
        /// Creates new instance of the <see cref="TiffRgbaImage"/> class.
        /// </summary>
        /// <param name="tif">
        /// The instance of the <see cref="BitMiracle.LibTiff.Classic"/> class used to retrieve
        /// image data.
        /// </param>
        /// <param name="stopOnError">
        /// if set to <c>true</c> then an error will terminate the conversion; otherwise "get"
        /// methods will continue processing data until all the possible data in the image have
        /// been requested.
        /// </param>
        /// <param name="errorMsg">The error message (if any) gets placed here.</param>
        /// <returns>
        /// New instance of the <see cref="TiffRgbaImage"/> class if the image specified
        /// by <paramref name="tif"/> can be converted to RGBA format; otherwise, <c>null</c> is
        /// returned and <paramref name="errorMsg"/> contains the reason why it is being
        /// rejected.
        /// </returns>
        public static TiffRgbaImage Create(Tiff tif, bool stopOnError, out string errorMsg)
        {
            errorMsg = null;

            // Initialize to normal values
            TiffRgbaImage img = new TiffRgbaImage();
            img.row_offset = 0;
            img.col_offset = 0;
            img.redcmap = null;
            img.greencmap = null;
            img.bluecmap = null;
            img.req_orientation = Orientation.BOTLEFT; // It is the default
            img.tif = tif;
            img.stoponerr = stopOnError;

            FieldValue[] result = tif.GetFieldDefaulted(TiffTag.BITSPERSAMPLE);
            img.bitspersample = result[0].ToShort();
            switch (img.bitspersample)
            {
                case 1:
                case 2:
                case 4:
                case 8:
                case 16:
                    break;

                default:
                    errorMsg = string.Format(CultureInfo.InvariantCulture,
                        "Sorry, can not handle images with {0}-bit samples", img.bitspersample);
                    return null;
            }

            img.alpha = 0;
            result = tif.GetFieldDefaulted(TiffTag.SAMPLESPERPIXEL);
            img.samplesperpixel = result[0].ToShort();

            result = tif.GetFieldDefaulted(TiffTag.EXTRASAMPLES);
            short extrasamples = result[0].ToShort();
            byte[] sampleinfo = result[1].ToByteArray();

            if (extrasamples >= 1)
            {
                switch ((ExtraSample)sampleinfo[0])
                {
                    case ExtraSample.UNSPECIFIED:
                        if (img.samplesperpixel > 3)
                        {
                            // Workaround for some images without correct info about alpha channel
                            img.alpha = ExtraSample.ASSOCALPHA;
                        }
                        break;

                    case ExtraSample.ASSOCALPHA:
                        // data is pre-multiplied
                    case ExtraSample.UNASSALPHA:
                        // data is not pre-multiplied
                        img.alpha = (ExtraSample)sampleinfo[0];
                        break;
                }
            }

            if (Tiff.DEFAULT_EXTRASAMPLE_AS_ALPHA)
            {
                result = tif.GetField(TiffTag.PHOTOMETRIC);
                if (result == null)
                    img.photometric = Photometric.MINISWHITE;

                if (extrasamples == 0 && img.samplesperpixel == 4 && img.photometric == Photometric.RGB)
                {
                    img.alpha = ExtraSample.ASSOCALPHA;
                    extrasamples = 1;
                }
            }

            int colorchannels = img.samplesperpixel - extrasamples;

            result = tif.GetFieldDefaulted(TiffTag.COMPRESSION);
            Compression compress = (Compression)result[0].ToInt();

            result = tif.GetFieldDefaulted(TiffTag.PLANARCONFIG);
            PlanarConfig planarconfig = (PlanarConfig)result[0].ToShort();

            result = tif.GetField(TiffTag.PHOTOMETRIC);
            if (result == null)
            {
                switch (colorchannels)
                {
                    case 1:
                        if (img.isCCITTCompression())
                            img.photometric = Photometric.MINISWHITE;
                        else
                            img.photometric = Photometric.MINISBLACK;
                        break;

                    case 3:
                        img.photometric = Photometric.RGB;
                        break;

                    default:
                        errorMsg = string.Format(CultureInfo.InvariantCulture, "Missing needed {0} tag", photoTag);
                        return null;
                }
            }
            else
                img.photometric = (Photometric)result[0].ToInt();

            switch (img.photometric)
            {
                case Photometric.PALETTE:
                    result = tif.GetField(TiffTag.COLORMAP);
                    if (result == null)
                    {
                        errorMsg = string.Format(CultureInfo.InvariantCulture, "Missing required \"Colormap\" tag");
                        return null;
                    }

                    short[] red_orig = result[0].ToShortArray();
                    short[] green_orig = result[1].ToShortArray();
                    short[] blue_orig = result[2].ToShortArray();

                    // copy the colormaps so we can modify them
                    int n_color = (1 << img.bitspersample);
                    img.redcmap = new ushort[n_color];
                    img.greencmap = new ushort[n_color];
                    img.bluecmap = new ushort[n_color];

                    Buffer.BlockCopy(red_orig, 0, img.redcmap, 0, n_color * sizeof(ushort));
                    Buffer.BlockCopy(green_orig, 0, img.greencmap, 0, n_color * sizeof(ushort));
                    Buffer.BlockCopy(blue_orig, 0, img.bluecmap, 0, n_color * sizeof(ushort));

                    if (planarconfig == PlanarConfig.CONTIG &&
                        img.samplesperpixel != 1 && img.bitspersample < 8)
                    {
                        errorMsg = string.Format(CultureInfo.InvariantCulture,
                            "Sorry, can not handle contiguous data with {0}={1}, and {2}={3} and Bits/Sample={4}",
                            photoTag, img.photometric, "Samples/pixel", img.samplesperpixel, img.bitspersample);
                        return null;
                    }
                    break;

                case Photometric.MINISWHITE:
                case Photometric.MINISBLACK:
                    if (planarconfig == PlanarConfig.CONTIG &&
                        img.samplesperpixel != 1 && img.bitspersample < 8)
                    {
                        errorMsg = string.Format(CultureInfo.InvariantCulture,
                            "Sorry, can not handle contiguous data with {0}={1}, and {2}={3} and Bits/Sample={4}",
                            photoTag, img.photometric, "Samples/pixel", img.samplesperpixel, img.bitspersample);
                        return null;
                    }
                    break;

                case Photometric.YCBCR:
                    // It would probably be nice to have a reality check here.
                    if (planarconfig == PlanarConfig.CONTIG)
                    {
                        // can rely on LibJpeg.Net to convert to RGB
                        // XXX should restore current state on exit
                        switch (compress)
                        {
                            case Compression.JPEG:
                                // TODO: when complete tests verify complete desubsampling and
                                // YCbCr handling, remove use of JPEGCOLORMODE in favor of native
                                // handling
                                tif.SetField(TiffTag.JPEGCOLORMODE, JpegColorMode.RGB);
                                img.photometric = Photometric.RGB;
                                break;

                            default:
                                // do nothing
                                break;
                        }
                    }

                    // TODO: if at all meaningful and useful, make more complete support check
                    // here, or better still, refactor to let supporting code decide whether there
                    // is support and what meaningfull error to return
                    break;

                case Photometric.RGB:
                    if (colorchannels < 3)
                    {
                        errorMsg = string.Format(CultureInfo.InvariantCulture,
                            "Sorry, can not handle RGB image with {0}={1}", "Color channels", colorchannels);
                        return null;
                    }
                    break;

                case Photometric.SEPARATED:
                    result = tif.GetFieldDefaulted(TiffTag.INKSET);
                    InkSet inkset = (InkSet)result[0].ToByte();

                    if (inkset != InkSet.CMYK)
                    {
                        errorMsg = string.Format(CultureInfo.InvariantCulture,
                            "Sorry, can not handle separated image with {0}={1}", "InkSet", inkset);
                        return null;
                    }

                    if (img.samplesperpixel < 4)
                    {
                        errorMsg = string.Format(CultureInfo.InvariantCulture,
                            "Sorry, can not handle separated image with {0}={1}", "Samples/pixel", img.samplesperpixel);
                        return null;
                    }
                    break;

                case Photometric.LOGL:
                    if (compress != Compression.SGILOG)
                    {
                        errorMsg = string.Format(CultureInfo.InvariantCulture,
                            "Sorry, LogL data must have {0}={1}", "Compression", Compression.SGILOG);
                        return null;
                    }

                    tif.SetField(TiffTag.SGILOGDATAFMT, 3); // 8-bit RGB monitor values. 
                    img.photometric = Photometric.MINISBLACK; // little white lie
                    img.bitspersample = 8;
                    break;

                case Photometric.LOGLUV:
                    if (compress != Compression.SGILOG && compress != Compression.SGILOG24)
                    {
                        errorMsg = string.Format(CultureInfo.InvariantCulture,
                            "Sorry, LogLuv data must have {0}={1} or {2}", "Compression", Compression.SGILOG, Compression.SGILOG24);
                        return null;
                    }

                    if (planarconfig != PlanarConfig.CONTIG)
                    {
                        errorMsg = string.Format(CultureInfo.InvariantCulture,
                            "Sorry, can not handle LogLuv images with {0}={1}", "Planarconfiguration", planarconfig);
                        return null;
                    }

                    tif.SetField(TiffTag.SGILOGDATAFMT, 3); // 8-bit RGB monitor values. 
                    img.photometric = Photometric.RGB; // little white lie
                    img.bitspersample = 8;
                    break;

                case Photometric.CIELAB:
                    break;

                default:
                    errorMsg = string.Format(CultureInfo.InvariantCulture,
                        "Sorry, can not handle image with {0}={1}", photoTag, img.photometric);
                    return null;
            }

            img.Map = null;
            img.BWmap = null;
            img.PALmap = null;
            img.ycbcr = null;
            img.cielab = null;

            result = tif.GetField(TiffTag.IMAGEWIDTH);
            img.width = result[0].ToInt();

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

            result = tif.GetFieldDefaulted(TiffTag.ORIENTATION);
            img.orientation = (Orientation)result[0].ToByte();

            img.isContig = !(planarconfig == PlanarConfig.SEPARATE && colorchannels > 1);
            if (img.isContig)
            {
                if (!img.pickContigCase())
                {
                    errorMsg = "Sorry, can not handle image";
                    return null;
                }
            }
            else
            {
                if (!img.pickSeparateCase())
                {
                    errorMsg = "Sorry, can not handle image";
                    return null;
                }
            }

            return img;
        }
コード例 #14
0
ファイル: Copier.cs プロジェクト: XiBeichuan/hydronumerics
        /*
         * Select the appropriate copy function to use.
         */
        bool pickFuncAndCopy(Tiff inImage, Tiff outImage, short bitspersample, short samplesperpixel, int length, int width)
        {
            using (TextWriter stderr = Console.Error)
            {
                FieldValue[] result = inImage.GetField(TiffTag.PLANARCONFIG);
                PlanarConfig shortv = (PlanarConfig)result[0].ToShort();

                if (shortv != m_config && bitspersample != 8 && samplesperpixel > 1)
                {
                    stderr.Write("{0}: Cannot handle different planar configuration w/ bits/sample != 8\n", inImage.FileName());
                    return false;
                }

                result = inImage.GetField(TiffTag.IMAGEWIDTH);
                int w = result[0].ToInt();

                result = inImage.GetField(TiffTag.IMAGELENGTH);
                int l = result[0].ToInt();

                bool bychunk;
                if (!(outImage.IsTiled() || inImage.IsTiled()))
                {
                    result = inImage.GetField(TiffTag.ROWSPERSTRIP);
                    if (result != null)
                    {
                        int irps = result[0].ToInt();

                        /* if biased, force decoded copying to allow image subtraction */
                        bychunk = (m_bias == null) && (m_rowsperstrip == irps);
                    }
                    else
                        bychunk = false;
                }
                else
                {
                    /* either inImage or outImage is tiled */
                    if (m_bias != null)
                    {
                        stderr.Write("{0}: Cannot handle tiled configuration w/bias image\n", inImage.FileName());
                        return false;
                    }

                    if (outImage.IsTiled())
                    {
                        int tw;
                        result = inImage.GetField(TiffTag.TILEWIDTH);
                        if (result == null)
                            tw = w;
                        else
                            tw = result[0].ToInt();

                        int tl;
                        result = inImage.GetField(TiffTag.TILELENGTH);
                        if (result == null)
                            tl = l;
                        else
                            tl = result[0].ToInt();

                        bychunk = (tw == m_tilewidth && tl == m_tilelength);
                    }
                    else
                    {
                        /* outImage's not, so inImage must be tiled */
                        result = inImage.GetField(TiffTag.TILEWIDTH);
                        int tw = result[0].ToInt();

                        result = inImage.GetField(TiffTag.TILELENGTH);
                        int tl = result[0].ToInt();

                        bychunk = (tw == w && tl == m_rowsperstrip);
                    }
                }

                if (inImage.IsTiled())
                {
                    if (outImage.IsTiled())
                    {
                        /* Tiles -> Tiles */
                        if (shortv == PlanarConfig.CONTIG && m_config == PlanarConfig.CONTIG)
                            return cpContigTiles2ContigTiles(inImage, outImage, length, width, samplesperpixel);
                        else if (shortv == PlanarConfig.CONTIG && m_config == PlanarConfig.SEPARATE)
                            return cpContigTiles2SeparateTiles(inImage, outImage, length, width, samplesperpixel);
                        else if (shortv == PlanarConfig.SEPARATE && m_config == PlanarConfig.CONTIG)
                            return cpSeparateTiles2ContigTiles(inImage, outImage, length, width, samplesperpixel);
                        else if (shortv == PlanarConfig.SEPARATE && m_config == PlanarConfig.SEPARATE)
                            return cpSeparateTiles2SeparateTiles(inImage, outImage, length, width, samplesperpixel);
                    }
                    else
                    {
                        /* Tiles -> Strips */
                        if (shortv == PlanarConfig.CONTIG && m_config == PlanarConfig.CONTIG)
                            return cpContigTiles2ContigStrips(inImage, outImage, length, width, samplesperpixel);
                        else if (shortv == PlanarConfig.CONTIG && m_config == PlanarConfig.SEPARATE)
                            return cpContigTiles2SeparateStrips(inImage, outImage, length, width, samplesperpixel);
                        else if (shortv == PlanarConfig.SEPARATE && m_config == PlanarConfig.CONTIG)
                            return cpSeparateTiles2ContigStrips(inImage, outImage, length, width, samplesperpixel);
                        else if (shortv == PlanarConfig.SEPARATE && m_config == PlanarConfig.SEPARATE)
                            return cpSeparateTiles2SeparateStrips(inImage, outImage, length, width, samplesperpixel);
                    }
                }
                else
                {
                    if (outImage.IsTiled())
                    {
                        /* Strips -> Tiles */
                        if (shortv == PlanarConfig.CONTIG && m_config == PlanarConfig.CONTIG)
                            return cpContigStrips2ContigTiles(inImage, outImage, length, width, samplesperpixel);
                        else if (shortv == PlanarConfig.CONTIG && m_config == PlanarConfig.SEPARATE)
                            return cpContigStrips2SeparateTiles(inImage, outImage, length, width, samplesperpixel);
                        else if (shortv == PlanarConfig.SEPARATE && m_config == PlanarConfig.CONTIG)
                            return cpSeparateStrips2ContigTiles(inImage, outImage, length, width, samplesperpixel);
                        else if (shortv == PlanarConfig.SEPARATE && m_config == PlanarConfig.SEPARATE)
                            return cpSeparateStrips2SeparateTiles(inImage, outImage, length, width, samplesperpixel);
                    }
                    else
                    {
                        /* Strips -> Strips */
                        if (shortv == PlanarConfig.CONTIG && m_config == PlanarConfig.CONTIG && !bychunk)
                        {
                            if (m_bias != null)
                                return cpBiasedContig2Contig(inImage, outImage, length, width, samplesperpixel);

                            return cpContig2ContigByRow(inImage, outImage, length, width, samplesperpixel);
                        }
                        else if (shortv == PlanarConfig.CONTIG && m_config == PlanarConfig.CONTIG && bychunk)
                            return cpDecodedStrips(inImage, outImage, length, width, samplesperpixel);
                        else if (shortv == PlanarConfig.CONTIG && m_config == PlanarConfig.SEPARATE)
                            return cpContig2SeparateByRow(inImage, outImage, length, width, samplesperpixel);
                        else if (shortv == PlanarConfig.SEPARATE && m_config == PlanarConfig.CONTIG)
                            return cpSeparate2ContigByRow(inImage, outImage, length, width, samplesperpixel);
                        else if (shortv == PlanarConfig.SEPARATE && m_config == PlanarConfig.SEPARATE)
                            return cpSeparate2SeparateByRow(inImage, outImage, length, width, samplesperpixel);
                    }
                }

                stderr.Write("tiffcp: {0}: Don't know how to copy/convert image.\n", inImage.FileName());
            }

            return false;
        }
コード例 #15
0
ファイル: Copier.cs プロジェクト: XiBeichuan/hydronumerics
 private static void copyTag(Tiff inImage, Tiff outImage, TiffTag tag, short count, TiffType type)
 {
     FieldValue[] result = null;
     switch (type)
     {
         case TiffType.SHORT:
             result = inImage.GetField(tag);
             if (result != null)
             {
                 if (count == 1)
                     outImage.SetField(tag, result[0]);
                 else if (count == 2)
                     outImage.SetField(tag, result[0], result[1]);
                 else if (count == 4)
                     outImage.SetField(tag, result[0], result[1], result[2]);
                 else if (count == -1)
                     outImage.SetField(tag, result[0], result[1]);
             }
             break;
         case TiffType.LONG:
             result = inImage.GetField(tag);
             if (result != null)
                 outImage.SetField(tag, result[0]);
             break;
         case TiffType.RATIONAL:
             result = inImage.GetField(tag);
             if (result != null)
                 outImage.SetField(tag, result[0]);
             break;
         case TiffType.ASCII:
             result = inImage.GetField(tag);
             if (result != null)
                 outImage.SetField(tag, result[0]);
             break;
         case TiffType.DOUBLE:
             result = inImage.GetField(tag);
             if (result != null)
                 outImage.SetField(tag, result[0]);
             break;
         default:
             Tiff.Error(inImage.FileName(),
                 "Data type {0} is not supported, tag {1} skipped.", tag, type);
             break;
     }
 }
コード例 #16
0
ファイル: Copier.cs プロジェクト: XiBeichuan/hydronumerics
        bool writeBufferToContigTiles(Tiff outImage, byte[] buf, int imagelength, int imagewidth, short spp)
        {
            byte[] obuf = new byte[outImage.TileSize()];

            FieldValue[] result = outImage.GetField(TiffTag.TILELENGTH);
            int tl = result[0].ToInt();

            result = outImage.GetField(TiffTag.TILEWIDTH);
            int tw = result[0].ToInt();

            int imagew = outImage.ScanlineSize();
            int tilew = outImage.TileRowSize();
            int iskew = imagew - tilew;

            int bufp = 0;

            for (int row = 0; row < imagelength; row += m_tilelength)
            {
                int nrow = (row + tl > imagelength) ? imagelength - row : tl;
                int colb = 0;

                for (int col = 0; col < imagewidth; col += tw)
                {
                    /*
                     * Tile is clipped horizontally.  Calculate
                     * visible portion and skewing factors.
                     */
                    if (colb + tilew > imagew)
                    {
                        int width = imagew - colb;
                        int oskew = tilew - width;
                        cpStripToTile(obuf, 0, buf, bufp + colb, nrow, width, oskew, oskew + iskew);
                    }
                    else
                        cpStripToTile(obuf, 0, buf, bufp + colb, nrow, tilew, 0, iskew);

                    if (outImage.WriteTile(obuf, col, row, 0, 0) < 0)
                    {
                        Tiff.Error(outImage.FileName(), "Error, can't write tile at {0} {1}", col, row);
                        return false;
                    }

                    colb += tilew;
                }

                bufp += nrow * imagew;
            }

            return true;
        }
コード例 #17
0
ファイル: Copier.cs プロジェクト: XiBeichuan/hydronumerics
        bool readContigTilesIntoBuffer(Tiff inImage, byte[] buf, int imagelength, int imagewidth, short spp)
        {
            byte[] tilebuf = new byte[inImage.TileSize()];

            FieldValue[] result = inImage.GetField(TiffTag.TILEWIDTH);
            int tw = result[0].ToInt();

            result = inImage.GetField(TiffTag.TILELENGTH);
            int tl = result[0].ToInt();

            int imagew = inImage.ScanlineSize();
            int tilew = inImage.TileRowSize();
            int iskew = imagew - tilew;

            int bufp = 0;

            for (int row = 0; row < imagelength; row += tl)
            {
                int nrow = (row + tl > imagelength) ? imagelength - row : tl;
                int colb = 0;

                for (int col = 0; col < imagewidth; col += tw)
                {
                    if (inImage.ReadTile(tilebuf, 0, col, row, 0, 0) < 0 && !m_ignore)
                    {
                        Tiff.Error(inImage.FileName(), "Error, can't read tile at {0} {1}", col, row);
                        return false;
                    }

                    if (colb + tilew > imagew)
                    {
                        int width = imagew - colb;
                        int oskew = tilew - width;
                        cpStripToTile(buf, bufp + colb, tilebuf, 0, nrow, width, oskew + iskew, oskew);
                    }
                    else
                        cpStripToTile(buf, bufp + colb, tilebuf, 0, nrow, tilew, iskew, 0);

                    colb += tilew;
                }

                bufp += imagew * nrow;
            }

            return true;
        }
コード例 #18
0
ファイル: Converter.cs プロジェクト: XiBeichuan/hydronumerics
        static bool cvt_by_tile(Tiff inImage, Tiff outImage, int width, int height)
        {
            int tile_width = 0;
            int tile_height = 0;

            FieldValue[] result = inImage.GetField(TiffTag.TILEWIDTH);
            if (result != null)
            {
                tile_width = result[0].ToInt();

                result = inImage.GetField(TiffTag.TILELENGTH);
                if (result != null)
                    tile_height = result[0].ToInt();
            }

            if (result == null)
            {
                Tiff.Error(inImage.FileName(), "Source image not tiled");
                return false;
            }

            outImage.SetField(TiffTag.TILEWIDTH, tile_width);
            outImage.SetField(TiffTag.TILELENGTH, tile_height);

            // Allocate tile buffer
            int raster_size = multiply(tile_width, tile_height);
            int rasterByteSize = multiply(raster_size, sizeof(int));
            if (raster_size == 0 || rasterByteSize == 0)
            {
                Tiff.Error(inImage.FileName(),
                    "Can't allocate buffer for raster of size {0}x{1}", tile_width, tile_height);
                return false;
            }

            int[] raster = new int[raster_size];
            byte[] rasterBytes = new byte[rasterByteSize];

            // Allocate a scanline buffer for swapping during the vertical mirroring pass.
            // (Request can't overflow given prior checks.)
            int[] wrk_line = new int[tile_width];

            // Loop over the tiles.
            for (int row = 0; row < height; row += tile_height)
            {
                for (int col = 0; col < width; col += tile_width)
                {
                    // Read the tile into an RGBA array
                    if (!inImage.ReadRGBATile(col, row, raster))
                        return false;

                    // For some reason the ReadRGBATile() function chooses the lower left corner
                    // as the origin. Vertically mirror scanlines.
                    for (int i_row = 0; i_row < tile_height / 2; i_row++)
                    {
                        int topIndex = tile_width * i_row * sizeof(int);
                        int bottomIndex = tile_width * (tile_height - i_row - 1) * sizeof(int);

                        Buffer.BlockCopy(raster, topIndex, wrk_line, 0, tile_width * sizeof(int));
                        Buffer.BlockCopy(raster, bottomIndex, raster, topIndex, tile_width * sizeof(int));
                        Buffer.BlockCopy(wrk_line, 0, raster, bottomIndex, tile_width * sizeof(int));
                    }

                    // Write out the result in a tile.
                    int tile = outImage.ComputeTile(col, row, 0, 0);
                    Buffer.BlockCopy(raster, 0, rasterBytes, 0, rasterByteSize);
                    if (outImage.WriteEncodedTile(tile, rasterBytes, rasterByteSize) == -1)
                        return false;
                }
            }

            return true;
        }
コード例 #19
0
ファイル: Converter.cs プロジェクト: XiBeichuan/hydronumerics
 private static void copyField(Tiff inImage, Tiff outImage, TiffTag tag)
 {
     FieldValue[] result = inImage.GetField(tag);
     if (result != null)
         outImage.SetField(tag, result[0]);
 }
コード例 #20
0
        private FileMetadata ParseMetadata(string filename)
        {
            FileMetadata metadata = new FileMetadata();
            _tiff = Tiff.Open(filename, "r");

            metadata.Height = _tiff.GetField(TiffTag.IMAGELENGTH)[0].ToInt();
            metadata.Width = _tiff.GetField(TiffTag.IMAGEWIDTH)[0].ToInt();

            FieldValue[] modelPixelScaleTag = _tiff.GetField((TiffTag)33550);
            FieldValue[] modelTiepointTag = _tiff.GetField((TiffTag)33922);

            byte[] modelPixelScale = modelPixelScaleTag[1].GetBytes();
            metadata.PixelScaleX = BitConverter.ToDouble(modelPixelScale, 0);
            metadata.PixelScaleY = BitConverter.ToDouble(modelPixelScale, 8);

            // Ignores first set of model points (3 bytes) and assumes they are 0's...
            byte[] modelTransformation = modelTiepointTag[1].GetBytes();
            metadata.OriginLongitude = BitConverter.ToDouble(modelTransformation, 24);
            metadata.OriginLatitude = BitConverter.ToDouble(modelTransformation, 32);

            // Grab some raster metadata
            metadata.BitsPerSample = _tiff.GetField(TiffTag.BITSPERSAMPLE)[0].ToInt();

            // Add other information about the data
            metadata.SampleFormat = "Single";
            // TODO: Read this from tiff metadata or determine after parsing
            metadata.NoDataValue = "-10000";

            metadata.WorldUnits = "meter";

            return metadata;
        }
コード例 #21
0
ファイル: Converter.cs プロジェクト: XiBeichuan/hydronumerics
        private bool cvt_by_strip(Tiff inImage, Tiff outImage, int width, int height)
        {
            FieldValue[] result = inImage.GetField(TiffTag.ROWSPERSTRIP);
            if (result == null)
            {
                Tiff.Error(inImage.FileName(), "Source image not in strips");
                return false;
            }

            m_rowsPerStrip = result[0].ToInt();
            outImage.SetField(TiffTag.ROWSPERSTRIP, m_rowsPerStrip);

            // Allocate strip buffer
            int raster_size = multiply(width, m_rowsPerStrip);
            int rasterByteSize = multiply(raster_size, sizeof(int));
            if (raster_size == 0 || rasterByteSize == 0)
            {
                Tiff.Error(inImage.FileName(),
                    "Can't allocate buffer for raster of size {0}x{1}", width, m_rowsPerStrip);
                return false;
            }

            int[] raster = new int[raster_size];
            byte[] rasterBytes = new byte[rasterByteSize];

            // Allocate a scanline buffer for swapping during the vertical mirroring pass.
            // (Request can't overflow given prior checks.)
            int[] wrk_line = new int[width];

            // Loop over the strips.
            for (int row = 0; row < height; row += m_rowsPerStrip)
            {
                // Read the strip into an RGBA array
                if (!inImage.ReadRGBAStrip(row, raster))
                    return false;

                // Figure out the number of scanlines actually in this strip.
                int rows_to_write;
                if (row + m_rowsPerStrip > height)
                    rows_to_write = height - row;
                else
                    rows_to_write = m_rowsPerStrip;

                // For some reason the TIFFReadRGBAStrip() function chooses the lower left corner
                // as the origin. Vertically mirror scanlines.
                for (int i_row = 0; i_row < rows_to_write / 2; i_row++)
                {
                    int topIndex = width * i_row * sizeof(int);
                    int bottomIndex = width * (rows_to_write - i_row - 1) * sizeof(int);

                    Buffer.BlockCopy(raster, topIndex, wrk_line, 0, width * sizeof(int));
                    Buffer.BlockCopy(raster, bottomIndex, raster, topIndex, width * sizeof(int));
                    Buffer.BlockCopy(wrk_line, 0, raster, bottomIndex, width * sizeof(int));
                }

                // Write out the result in a strip
                int bytesToWrite = rows_to_write * width * sizeof(int);
                Buffer.BlockCopy(raster, 0, rasterBytes, 0, bytesToWrite);
                if (outImage.WriteEncodedStrip(row / m_rowsPerStrip, rasterBytes, bytesToWrite) == -1)
                    return false;
            }

            return true;
        }
コード例 #22
0
ファイル: Copier.cs プロジェクト: XiBeichuan/hydronumerics
        bool readSeparateTilesIntoBuffer(Tiff inImage, byte[] buf, int imagelength, int imagewidth, short spp)
        {
            byte[] tilebuf = new byte[inImage.TileSize()];

            FieldValue[] result = inImage.GetField(TiffTag.TILEWIDTH);
            int tw = result[0].ToInt();

            result = inImage.GetField(TiffTag.TILELENGTH);
            int tl = result[0].ToInt();

            result = inImage.GetField(TiffTag.BITSPERSAMPLE);
            short bps = result[0].ToShort();

            Debug.Assert(bps % 8 == 0);

            short bytes_per_sample = (short)(bps / 8);

            int imagew = inImage.RasterScanlineSize();
            int tilew = inImage.TileRowSize();
            int iskew = imagew - tilew * spp;

            int bufp = 0;

            for (int row = 0; row < imagelength; row += tl)
            {
                int nrow = (row + tl > imagelength) ? imagelength - row : tl;
                int colb = 0;

                for (int col = 0; col < imagewidth; col += tw)
                {
                    for (short s = 0; s < spp; s++)
                    {
                        if (inImage.ReadTile(tilebuf, 0, col, row, 0, s) < 0 && !m_ignore)
                        {
                            Tiff.Error(inImage.FileName(), "Error, can't read tile at {0} {1}, sample {2}", col, row, s);
                            return false;
                        }

                        /*
                         * Tile is clipped horizontally.  Calculate
                         * visible portion and skewing factors.
                         */
                        if (colb + tilew * spp > imagew)
                        {
                            int width = imagew - colb;
                            int oskew = tilew * spp - width;
                            cpSeparateBufToContigBuf(buf, bufp + colb + s * bytes_per_sample, tilebuf, nrow, width / (spp * bytes_per_sample), oskew + iskew, oskew / spp, spp, bytes_per_sample);
                        }
                        else
                            cpSeparateBufToContigBuf(buf, bufp + colb + s * bytes_per_sample, tilebuf, nrow, tw, iskew, 0, spp, bytes_per_sample);
                    }

                    colb += tilew * spp;
                }

                bufp += imagew * nrow;
            }

            return true;
        }
コード例 #23
0
ファイル: T2P.cs プロジェクト: dronab/libtiff.net
        /*
        This function returns the necessary size of a data buffer to contain the raw or 
        uncompressed image data from the input TIFF for a tile of a page.
        */
        private void read_tiff_size_tile(Tiff input, int tile)
        {
            bool edge = false;
            edge |= tile_is_right_edge(m_tiff_pages[m_pdf_page], tile);
            edge |= tile_is_bottom_edge(m_tiff_pages[m_pdf_page], tile);

            if (m_pdf_transcode == t2p_transcode_t.T2P_TRANSCODE_RAW)
            {
                if (edge && m_pdf_compression != t2p_compress_t.T2P_COMPRESS_JPEG)
                {
                    m_tiff_datasize = input.TileSize();
                    return;
                }
                else
                {
                    FieldValue[] result = input.GetField(TiffTag.TILEBYTECOUNTS);
                    int[] tbc = result[0].ToIntArray();
                    m_tiff_datasize = tbc[tile];
                    if (m_tiff_compression == Compression.JPEG)
                    {
                        result = input.GetField(TiffTag.JPEGTABLES);
                        if (result != null)
                        {
                            int count = result[0].ToInt();
                            if (count > 4)
                            {
                                m_tiff_datasize += count;
                                m_tiff_datasize -= 4; /* don't use EOI of header or SOI of tile */
                            }
                        }
                    }
                    return;
                }
            }

            m_tiff_datasize = input.TileSize();
            if (m_tiff_planar == PlanarConfig.SEPARATE)
                m_tiff_datasize *= m_tiff_samplesperpixel;
        }
コード例 #24
0
ファイル: Copier.cs プロジェクト: XiBeichuan/hydronumerics
        bool writeBufferToSeparateTiles(Tiff outImage, byte[] buf, int imagelength, int imagewidth, short spp)
        {
            byte[] obuf = new byte[outImage.TileSize()];

            FieldValue[] result = outImage.GetField(TiffTag.TILELENGTH);
            int tl = result[0].ToInt();

            result = outImage.GetField(TiffTag.TILEWIDTH);
            int tw = result[0].ToInt();

            result = outImage.GetField(TiffTag.BITSPERSAMPLE);
            short bps = result[0].ToShort();

            Debug.Assert(bps % 8 == 0);

            short bytes_per_sample = (short)(bps / 8);

            int imagew = outImage.ScanlineSize();
            int tilew = outImage.TileRowSize();
            int iimagew = outImage.RasterScanlineSize();
            int iskew = iimagew - tilew * spp;

            int bufp = 0;

            for (int row = 0; row < imagelength; row += tl)
            {
                int nrow = (row + tl > imagelength) ? imagelength - row : tl;
                int colb = 0;

                for (int col = 0; col < imagewidth; col += tw)
                {
                    for (short s = 0; s < spp; s++)
                    {
                        /*
                         * Tile is clipped horizontally.  Calculate
                         * visible portion and skewing factors.
                         */
                        if (colb + tilew > imagew)
                        {
                            int width = imagew - colb;
                            int oskew = tilew - width;

                            cpContigBufToSeparateBuf(obuf, buf, bufp + (colb * spp) + s, nrow, width / bytes_per_sample, oskew, (oskew * spp) + iskew, spp, bytes_per_sample);
                        }
                        else
                            cpContigBufToSeparateBuf(obuf, buf, bufp + (colb * spp) + s, nrow, m_tilewidth, 0, iskew, spp, bytes_per_sample);

                        if (outImage.WriteTile(obuf, col, row, 0, s) < 0)
                        {
                            Tiff.Error(outImage.FileName(), "Error, can't write tile at {0} {1} sample {2}", col, row, s);
                            return false;
                        }
                    }

                    colb += tilew;
                }

                bufp += nrow * iimagew;
            }

            return true;
        }
コード例 #25
0
ファイル: T2P.cs プロジェクト: dronab/libtiff.net
        /*
        This function reads the raster image data from the input TIFF for an image and writes 
        the data to the output PDF XObject image dictionary stream.  It returns the amount written 
        or zero on error.
        */
        private int readwrite_pdf_image(Tiff input)
        {
            byte[] buffer = null;
            int bufferoffset = 0;
            int stripcount = 0;
            int max_striplength = 0;
            FieldValue[] result = null;

            if (m_pdf_transcode == t2p_transcode_t.T2P_TRANSCODE_RAW)
            {
                if (m_pdf_compression == t2p_compress_t.T2P_COMPRESS_G4)
                {
                    buffer = new byte [m_tiff_datasize];
                    input.ReadRawStrip(0, buffer, 0, m_tiff_datasize);
                    if (m_tiff_fillorder == FillOrder.LSB2MSB)
                    {
                        /*
                        * make sure is lsb-to-msb
                        * bit-endianness fill order
                        */
                        Tiff.ReverseBits(buffer, m_tiff_datasize);
                    }
                    
                    writeToFile(buffer, m_tiff_datasize);
                    return m_tiff_datasize;
                }

                if (m_pdf_compression == t2p_compress_t.T2P_COMPRESS_ZIP)
                {
                    buffer = new byte [m_tiff_datasize];
                    input.ReadRawStrip(0, buffer, 0, m_tiff_datasize);
                    if (m_tiff_fillorder == FillOrder.LSB2MSB)
                        Tiff.ReverseBits(buffer, m_tiff_datasize);

                    writeToFile(buffer, m_tiff_datasize);
                    return m_tiff_datasize;
                }
                
                if (m_tiff_compression == Compression.JPEG)
                {
                    buffer = new byte [m_tiff_datasize];
                    result = input.GetField(TiffTag.JPEGTABLES);
                    if (result != null)
                    {
                        int count = result[0].ToInt();
                        byte[] jpt = result[1].ToByteArray();
                        if (count > 4)
                        {
                            Buffer.BlockCopy(jpt, 0, buffer, 0, count);
                            bufferoffset += count - 2;
                        }
                    }

                    stripcount = input.NumberOfStrips();
                    result = input.GetField(TiffTag.STRIPBYTECOUNTS);
                    int[] sbc = result[0].ToIntArray();
                    for (int i = 0; i < stripcount; i++)
                    {
                        if (sbc[i] > max_striplength)
                            max_striplength = sbc[i];
                    }
                    
                    byte[] stripbuffer = new byte [max_striplength];
                    for (int i = 0; i < stripcount; i++)
                    {
                        int striplength = input.ReadRawStrip(i, stripbuffer, 0, -1);
                        if (!process_jpeg_strip(stripbuffer, striplength, buffer, ref bufferoffset, stripcount, i, m_tiff_length))
                        {
                            Tiff.Error(Tiff2PdfConstants.TIFF2PDF_MODULE,
                                "Can't process JPEG data in input file {0}", input.FileName());
                            m_error = true;
                            return 0;
                        }
                    }

                    buffer[bufferoffset++] = 0xff;
                    buffer[bufferoffset++] = 0xd9;
                    writeToFile(buffer, bufferoffset);
                    return bufferoffset;
                }
            }

            int stripsize = 0;
            if (m_pdf_sample == t2p_sample_t.T2P_SAMPLE_NOTHING)
            {
                buffer = new byte [m_tiff_datasize];
                stripsize = input.StripSize();
                stripcount = input.NumberOfStrips();
                for (int i = 0; i < stripcount; i++)
                {
                    int read = input.ReadEncodedStrip(i, buffer, bufferoffset, stripsize);
                    if (read == -1)
                    {
                        Tiff.Error(Tiff2PdfConstants.TIFF2PDF_MODULE,
                            "Error on decoding strip {0} of {1}", i, input.FileName());
                        m_error = true;
                        return 0;
                    }

                    bufferoffset += read;
                }
            }
            else
            {
                byte[] samplebuffer = null;
                bool dataready = false;

                if ((m_pdf_sample & t2p_sample_t.T2P_SAMPLE_PLANAR_SEPARATE_TO_CONTIG) != 0)
                {
                    int sepstripsize = input.StripSize();
                    int sepstripcount = input.NumberOfStrips();

                    stripsize = sepstripsize * m_tiff_samplesperpixel;
                    stripcount = sepstripcount / m_tiff_samplesperpixel;

                    buffer = new byte [m_tiff_datasize];
                    samplebuffer = new byte [stripsize];
                    for (int i = 0; i < stripcount; i++)
                    {
                        int samplebufferoffset = 0;
                        for (int j = 0; j < m_tiff_samplesperpixel; j++)
                        {
                            int read = input.ReadEncodedStrip(i + j * stripcount, samplebuffer, samplebufferoffset, sepstripsize);
                            if (read == -1)
                            {
                                Tiff.Error(Tiff2PdfConstants.TIFF2PDF_MODULE,
                                    "Error on decoding strip {0} of {1}", 
                                    i + j * stripcount, input.FileName());
                                m_error = true;
                                return 0;
                            }
                            samplebufferoffset += read;
                        }

                        sample_planar_separate_to_contig(buffer, bufferoffset, samplebuffer, samplebufferoffset);
                        bufferoffset += samplebufferoffset;
                    }

                    dataready = true;
                }

                if (!dataready)
                {
                    buffer = new byte [m_tiff_datasize];
                    stripsize = input.StripSize();
                    stripcount = input.NumberOfStrips();
                    for (int i = 0; i < stripcount; i++)
                    {
                        int read = input.ReadEncodedStrip(i, buffer, bufferoffset, stripsize);
                        if (read == -1)
                        {
                            Tiff.Error(Tiff2PdfConstants.TIFF2PDF_MODULE,
                                "Error on decoding strip {0} of {1}", i, input.FileName());
                            m_error = true;
                            return 0;
                        }

                        bufferoffset += read;
                    }

                    if ((m_pdf_sample & t2p_sample_t.T2P_SAMPLE_REALIZE_PALETTE) != 0)
                    {
                        samplebuffer = Tiff.Realloc(buffer, m_tiff_datasize * m_tiff_samplesperpixel);
                        buffer = samplebuffer;
                        m_tiff_datasize *= m_tiff_samplesperpixel;
                        sample_realize_palette(buffer);
                    }

                    if ((m_pdf_sample & t2p_sample_t.T2P_SAMPLE_RGBA_TO_RGB) != 0)
                        m_tiff_datasize = sample_rgba_to_rgb(buffer, m_tiff_width * m_tiff_length);

                    if ((m_pdf_sample & t2p_sample_t.T2P_SAMPLE_RGBAA_TO_RGB) != 0)
                        m_tiff_datasize = sample_rgbaa_to_rgb(buffer, m_tiff_width * m_tiff_length);

                    if ((m_pdf_sample & t2p_sample_t.T2P_SAMPLE_YCBCR_TO_RGB) != 0)
                    {
                        samplebuffer = Tiff.Realloc(buffer, m_tiff_width * m_tiff_length * 4);
                        buffer = samplebuffer;

                        int[] buffer32 = Tiff.ByteArrayToInts(buffer, 0, m_tiff_width * m_tiff_length * 4);
                        if (!input.ReadRGBAImageOriented(m_tiff_width, m_tiff_length, buffer32, Orientation.TOPLEFT, false))
                        {
                            Tiff.Error(Tiff2PdfConstants.TIFF2PDF_MODULE,
                                "Can't use ReadRGBAImageOriented to extract RGB image from {0}",
                                input.FileName());
                            m_error = true;
                            return 0;
                        }

                        Tiff.IntsToByteArray(buffer32, 0, m_tiff_width * m_tiff_length, buffer, 0);

                        m_tiff_datasize = sample_abgr_to_rgb(buffer, m_tiff_width * m_tiff_length);
                    }

                    if ((m_pdf_sample & t2p_sample_t.T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED) != 0)
                        m_tiff_datasize = sample_lab_signed_to_unsigned(buffer, m_tiff_width * m_tiff_length);
                }
            }

            disable(m_output);
            m_output.SetField(TiffTag.PHOTOMETRIC, m_tiff_photometric);
            m_output.SetField(TiffTag.BITSPERSAMPLE, m_tiff_bitspersample);
            m_output.SetField(TiffTag.SAMPLESPERPIXEL, m_tiff_samplesperpixel);
            m_output.SetField(TiffTag.IMAGEWIDTH, m_tiff_width);
            m_output.SetField(TiffTag.IMAGELENGTH, m_tiff_length);
            m_output.SetField(TiffTag.ROWSPERSTRIP, m_tiff_length);
            m_output.SetField(TiffTag.PLANARCONFIG, PlanarConfig.CONTIG);
            m_output.SetField(TiffTag.FILLORDER, FillOrder.MSB2LSB);

            switch (m_pdf_compression)
            {
                case t2p_compress_t.T2P_COMPRESS_NONE:
                    m_output.SetField(TiffTag.COMPRESSION, Compression.NONE);
                    break;
                
                case t2p_compress_t.T2P_COMPRESS_G4:
                    m_output.SetField(TiffTag.COMPRESSION, Compression.CCITTFAX4);
                    break;
                
                case t2p_compress_t.T2P_COMPRESS_JPEG:
                    if (m_tiff_photometric == Photometric.YCBCR)
                    {
                        result = input.GetField(TiffTag.YCBCRSUBSAMPLING);
                        if (result != null)
                        {
                            short hor = result[0].ToShort();
                            short ver = result[1].ToShort();
                            if (hor != 0 && ver != 0)
                                m_output.SetField(TiffTag.YCBCRSUBSAMPLING, hor, ver);
                        }

                        result = input.GetField(TiffTag.REFERENCEBLACKWHITE);
                        if (result != null)
                        {
                            float[] xfloatp = result[0].ToFloatArray();
                            m_output.SetField(TiffTag.REFERENCEBLACKWHITE, xfloatp);
                        }
                    }

                    if (!m_output.SetField(TiffTag.COMPRESSION, Compression.JPEG))
                    {
                        Tiff.Error(Tiff2PdfConstants.TIFF2PDF_MODULE,
                            "Unable to use JPEG compression for input {0} and output {1}",
                            input.FileName(), m_output.FileName());
                        m_error = true;
                        return 0;
                    }

                    m_output.SetField(TiffTag.JPEGTABLESMODE, 0);

                    if ((m_pdf_colorspace & (t2p_cs_t.T2P_CS_RGB | t2p_cs_t.T2P_CS_LAB)) != 0)
                    {
                        m_output.SetField(TiffTag.PHOTOMETRIC, Photometric.YCBCR);

                        if (m_tiff_photometric != Photometric.YCBCR)
                            m_output.SetField(TiffTag.JPEGCOLORMODE, JpegColorMode.RGB);
                        else
                            m_output.SetField(TiffTag.JPEGCOLORMODE, JpegColorMode.RAW);
                    }

                    if (m_pdf_defaultcompressionquality != 0)
                        m_output.SetField(TiffTag.JPEGQUALITY, m_pdf_defaultcompressionquality);

                    break;
                
                case t2p_compress_t.T2P_COMPRESS_ZIP:
                    m_output.SetField(TiffTag.COMPRESSION, Compression.DEFLATE);
                    if (m_pdf_defaultcompressionquality % 100 != 0)
                        m_output.SetField(TiffTag.PREDICTOR, m_pdf_defaultcompressionquality % 100);
                    
                    if (m_pdf_defaultcompressionquality / 100 != 0)
                        m_output.SetField(TiffTag.ZIPQUALITY, (m_pdf_defaultcompressionquality / 100));

                    break;
                
                default:
                    break;
            }

            enable(m_output);
            m_outputwritten = 0;

            if (m_pdf_compression == t2p_compress_t.T2P_COMPRESS_JPEG && m_tiff_photometric == Photometric.YCBCR)
                bufferoffset = m_output.WriteEncodedStrip(0, buffer, stripsize * stripcount);
            else
                bufferoffset = m_output.WriteEncodedStrip(0, buffer, m_tiff_datasize);

            buffer = null;

            if (bufferoffset == -1)
            {
                Tiff.Error(Tiff2PdfConstants.TIFF2PDF_MODULE,
                    "Error writing encoded strip to output PDF {0}", m_output.FileName());
                m_error = true;
                return 0;
            }

            return m_outputwritten;
        }
コード例 #26
0
ファイル: Copier.cs プロジェクト: XiBeichuan/hydronumerics
        public bool Copy(Tiff inImage, Tiff outImage)
        {
            int width = 0;
            FieldValue[] result = inImage.GetField(TiffTag.IMAGEWIDTH);
            if (result != null)
            {
                width = result[0].ToInt();
                outImage.SetField(TiffTag.IMAGEWIDTH, width);
            }

            int length = 0;
            result = inImage.GetField(TiffTag.IMAGELENGTH);
            if (result != null)
            {
                length = result[0].ToInt();
                outImage.SetField(TiffTag.IMAGELENGTH, length);
            }

            short bitspersample = 1;
            result = inImage.GetField(TiffTag.BITSPERSAMPLE);
            if (result != null)
            {
                bitspersample = result[0].ToShort();
                outImage.SetField(TiffTag.BITSPERSAMPLE, bitspersample);
            }

            short samplesperpixel = 1;
            result = inImage.GetField(TiffTag.SAMPLESPERPIXEL);
            if (result != null)
            {
                samplesperpixel = result[0].ToShort();
                outImage.SetField(TiffTag.SAMPLESPERPIXEL, samplesperpixel);
            }

            if (m_compression != (Compression)(-1))
                outImage.SetField(TiffTag.COMPRESSION, m_compression);
            else
            {
                result = inImage.GetField(TiffTag.COMPRESSION);
                if (result != null)
                {
                    m_compression = (Compression)result[0].ToInt();
                    outImage.SetField(TiffTag.COMPRESSION, m_compression);
                }
            }

            result = inImage.GetFieldDefaulted(TiffTag.COMPRESSION);
            Compression input_compression = (Compression)result[0].ToInt();

            result = inImage.GetFieldDefaulted(TiffTag.PHOTOMETRIC);
            Photometric input_photometric = (Photometric)result[0].ToShort();
    
            if (input_compression == Compression.JPEG)
            {
                /* Force conversion to RGB */
                inImage.SetField(TiffTag.JPEGCOLORMODE, JpegColorMode.RGB);
            }
            else if (input_photometric == Photometric.YCBCR)
            {
                /* Otherwise, can't handle subsampled input */
                result = inImage.GetFieldDefaulted(TiffTag.YCBCRSUBSAMPLING);
                short subsamplinghor = result[0].ToShort();
                short subsamplingver = result[1].ToShort();

                if (subsamplinghor != 1 || subsamplingver != 1)
                {
                    Console.Error.WriteLine("tiffcp: {0}: Can't copy/convert subsampled image.", inImage.FileName());
                    return false;
                }
            }

            if (m_compression == Compression.JPEG)
            {
                if (input_photometric == Photometric.RGB && m_jpegcolormode == JpegColorMode.RGB)
                    outImage.SetField(TiffTag.PHOTOMETRIC, Photometric.YCBCR);
                else
                    outImage.SetField(TiffTag.PHOTOMETRIC, input_photometric);
            }
            else if (m_compression == Compression.SGILOG || m_compression == Compression.SGILOG24)
            {
                outImage.SetField(TiffTag.PHOTOMETRIC, samplesperpixel == 1 ? Photometric.LOGL : Photometric.LOGLUV);
            }
            else
            {
                if (input_compression != Compression.JPEG)
                    copyTag(inImage, outImage, TiffTag.PHOTOMETRIC, 1, TiffType.SHORT);
            }

            if (m_fillorder != 0)
                outImage.SetField(TiffTag.FILLORDER, m_fillorder);
            else
                copyTag(inImage, outImage, TiffTag.FILLORDER, 1, TiffType.SHORT);

            /*
             * Will copy `Orientation' tag from input image
             */
            result = inImage.GetFieldDefaulted(TiffTag.ORIENTATION);
            m_orientation = (Orientation)result[0].ToByte();
            switch (m_orientation)
            {
                case Orientation.BOTRIGHT:
                case Orientation.RIGHTBOT:
                    Tiff.Warning(inImage.FileName(), "using bottom-left orientation");
                    m_orientation = Orientation.BOTLEFT;
                    break;

                case Orientation.LEFTBOT:
                case Orientation.BOTLEFT:
                    break;

                case Orientation.TOPRIGHT:
                case Orientation.RIGHTTOP:
                default:
                    Tiff.Warning(inImage.FileName(), "using top-left orientation");
                    m_orientation = Orientation.TOPLEFT;
                    break;

                case Orientation.LEFTTOP:
                case Orientation.TOPLEFT:
                    break;
            }

            outImage.SetField(TiffTag.ORIENTATION, m_orientation);

            /*
             * Choose tiles/strip for the output image according to
             * the command line arguments (-tiles, -strips) and the
             * structure of the input image.
             */
            if (m_outtiled == -1)
            {
                if (inImage.IsTiled())
                    m_outtiled = 1;
                else
                    m_outtiled = 0;
            }

            if (m_outtiled != 0)
            {
                /*
                 * Setup output file's tile width&height.  If either
                 * is not specified, use either the value from the
                 * input image or, if nothing is defined, use the
                 * library default.
                 */
                if (m_tilewidth == -1)
                {
                    result = inImage.GetFieldDefaulted(TiffTag.TILEWIDTH);
                    if (result != null)
                        m_tilewidth = result[0].ToInt();
                }

                if (m_tilelength == -1)
                {
                    result = inImage.GetFieldDefaulted(TiffTag.TILELENGTH);
                    if (result != null)
                        m_tilelength = result[0].ToInt();
                }

                outImage.DefaultTileSize(ref m_tilewidth, ref m_tilelength);
                outImage.SetField(TiffTag.TILEWIDTH, m_tilewidth);
                outImage.SetField(TiffTag.TILELENGTH, m_tilelength);
            }
            else
            {
                /*
                 * RowsPerStrip is left unspecified: use either the
                 * value from the input image or, if nothing is defined,
                 * use the library default.
                 */
                if (m_rowsperstrip == 0)
                {
                    result = inImage.GetField(TiffTag.ROWSPERSTRIP);
                    if (result == null)
                        m_rowsperstrip = outImage.DefaultStripSize(m_rowsperstrip);
                    else
                        m_rowsperstrip = result[0].ToInt();

                    if (m_rowsperstrip > length && m_rowsperstrip != -1)
                        m_rowsperstrip = length;
                }
                else if (m_rowsperstrip == -1)
                    m_rowsperstrip = length;

                outImage.SetField(TiffTag.ROWSPERSTRIP, m_rowsperstrip);
            }

            if (m_config != PlanarConfig.UNKNOWN)
                outImage.SetField(TiffTag.PLANARCONFIG, m_config);
            else
            {
                result = inImage.GetField(TiffTag.PLANARCONFIG);
                if (result != null)
                {
                    m_config = (PlanarConfig)result[0].ToShort();
                    outImage.SetField(TiffTag.PLANARCONFIG, m_config);
                }
            }

            if (samplesperpixel <= 4)
                copyTag(inImage, outImage, TiffTag.TRANSFERFUNCTION, 4, TiffType.SHORT);

            copyTag(inImage, outImage, TiffTag.COLORMAP, 4, TiffType.SHORT);

            /* SMinSampleValue & SMaxSampleValue */
            switch (m_compression)
            {
                case Compression.JPEG:
                    outImage.SetField(TiffTag.JPEGQUALITY, m_quality);
                    outImage.SetField(TiffTag.JPEGCOLORMODE, m_jpegcolormode);
                    break;
                case Compression.LZW:
                case Compression.ADOBE_DEFLATE:
                case Compression.DEFLATE:
                    if (m_predictor != -1)
                        outImage.SetField(TiffTag.PREDICTOR, m_predictor);
                    else
                    {
                        result = inImage.GetField(TiffTag.PREDICTOR);
                        if (result != null)
                        {
                            m_predictor = result[0].ToShort();
                            outImage.SetField(TiffTag.PREDICTOR, m_predictor);
                        }
                    }
                    break;
                case Compression.CCITTFAX3:
                case Compression.CCITTFAX4:
                    if (m_compression == Compression.CCITTFAX3)
                    {
                        if (m_g3opts != Group3Opt.UNKNOWN)
                            outImage.SetField(TiffTag.GROUP3OPTIONS, m_g3opts);
                        else
                        {
                            result = inImage.GetField(TiffTag.GROUP3OPTIONS);
                            if (result != null)
                            {
                                m_g3opts = (Group3Opt)result[0].ToShort();
                                outImage.SetField(TiffTag.GROUP3OPTIONS, m_g3opts);
                            }
                        }
                    }
                    else
                        copyTag(inImage, outImage, TiffTag.GROUP4OPTIONS, 1, TiffType.LONG);

                    copyTag(inImage, outImage, TiffTag.BADFAXLINES, 1, TiffType.LONG);
                    copyTag(inImage, outImage, TiffTag.CLEANFAXDATA, 1, TiffType.LONG);
                    copyTag(inImage, outImage, TiffTag.CONSECUTIVEBADFAXLINES, 1, TiffType.LONG);
                    copyTag(inImage, outImage, TiffTag.FAXRECVPARAMS, 1, TiffType.LONG);
                    copyTag(inImage, outImage, TiffTag.FAXRECVTIME, 1, TiffType.LONG);
                    copyTag(inImage, outImage, TiffTag.FAXSUBADDRESS, 1, TiffType.ASCII);
                    break;
            }

            result = inImage.GetField(TiffTag.ICCPROFILE);
            if (result != null)
                outImage.SetField(TiffTag.ICCPROFILE, result[0], result[1]);

            result = inImage.GetField(TiffTag.NUMBEROFINKS);
            if (result != null)
            {
                short ninks = result[0].ToShort();
                outImage.SetField(TiffTag.NUMBEROFINKS, ninks);

                result = inImage.GetField(TiffTag.INKNAMES);
                if (result != null)
                {
                    string inknames = result[0].ToString();
                    string[] parts = inknames.Split(new char[] { '\0' });

                    int inknameslen = 0;
                    foreach (string part in parts)
                        inknameslen += part.Length + 1;

                    outImage.SetField(TiffTag.INKNAMES, inknameslen, inknames);
                }
            }

            result = inImage.GetField(TiffTag.PAGENUMBER);
            if (m_pageInSeq == 1)
            {
                if (m_pageNum < 0)
                {
                    /* only one input file */ 
                    if (result != null) 
                        outImage.SetField(TiffTag.PAGENUMBER, result[0], result[1]);
                }
                else
                {
                    outImage.SetField(TiffTag.PAGENUMBER, m_pageNum++, 0);
                }
            }
            else
            {
                if (result != null)
                {
                    if (m_pageNum < 0)
                    {
                        /* only one input file */
                        outImage.SetField(TiffTag.PAGENUMBER, result[0], result[1]);
                    }
                    else
                    {
                        outImage.SetField(TiffTag.PAGENUMBER, m_pageNum++, 0);
                    }
                }
            }

            int NTAGS = g_tags.Length;
            for (int i = 0; i < NTAGS; i++)
            {
                tagToCopy p = g_tags[i];
                copyTag(inImage, outImage, p.tag, p.count, p.type);
            }

            return pickFuncAndCopy(inImage, outImage, bitspersample, samplesperpixel, length, width);
        }
コード例 #27
0
ファイル: T2P.cs プロジェクト: dronab/libtiff.net
        /*
        * This function reads the raster image data from the input TIFF for an image
        * tile and writes the data to the output PDF XObject image dictionary stream
        * for the tile.  It returns the amount written or zero on error.
        */
        private int readwrite_pdf_image_tile(Tiff input, int tile)
        {
            bool edge = false;
            edge |= tile_is_right_edge(m_tiff_pages[m_pdf_page], tile);
            edge |= tile_is_bottom_edge(m_tiff_pages[m_pdf_page], tile);

            byte[] buffer = null;
            int bufferoffset = 0;
            FieldValue[] result = null;

            if ((m_pdf_transcode == t2p_transcode_t.T2P_TRANSCODE_RAW) && (!edge || (m_pdf_compression == t2p_compress_t.T2P_COMPRESS_JPEG)))
            {
                if (m_pdf_compression == t2p_compress_t.T2P_COMPRESS_G4)
                {
                    buffer = new byte [m_tiff_datasize];
                    input.ReadRawTile(tile, buffer, 0, m_tiff_datasize);
                    if (m_tiff_fillorder == FillOrder.LSB2MSB)
                        Tiff.ReverseBits(buffer, m_tiff_datasize);

                    writeToFile(buffer, m_tiff_datasize);
                    return m_tiff_datasize;
                }
                
                if (m_pdf_compression == t2p_compress_t.T2P_COMPRESS_ZIP)
                {
                    buffer = new byte [m_tiff_datasize];
                    input.ReadRawTile(tile, buffer, 0, m_tiff_datasize);
                    if (m_tiff_fillorder == FillOrder.LSB2MSB)
                        Tiff.ReverseBits(buffer, m_tiff_datasize);

                    writeToFile(buffer, m_tiff_datasize);
                    return m_tiff_datasize;
                }
                
                if (m_tiff_compression == Compression.JPEG)
                {
                    byte[] table_end = new byte[2];
                    buffer = new byte [m_tiff_datasize];
                    result = input.GetField(TiffTag.JPEGTABLES);
                    if (result != null)
                    {
                        int count = result[0].ToInt();
                        byte[] jpt = result[1].ToByteArray();
                        if (count > 0)
                        {
                            Buffer.BlockCopy(jpt, 0, buffer, 0, count);
                            bufferoffset += count - 2;
                            table_end[0] = buffer[bufferoffset - 2];
                            table_end[1] = buffer[bufferoffset - 1];
                        }

                        if (count > 0)
                        {
                            int xuint32 = bufferoffset;
                            bufferoffset += input.ReadRawTile(tile, buffer, bufferoffset - 2, -1);
                            buffer[xuint32 - 2] = table_end[0];
                            buffer[xuint32 - 1] = table_end[1];
                        }
                        else
                        {
                            bufferoffset += input.ReadRawTile(tile, buffer, bufferoffset, -1);
                        }
                    }

                    writeToFile(buffer, bufferoffset);
                    return bufferoffset;
                }
            }

            if (m_pdf_sample == t2p_sample_t.T2P_SAMPLE_NOTHING)
            {
                buffer = new byte [m_tiff_datasize];
                int read = input.ReadEncodedTile(tile, buffer, bufferoffset, m_tiff_datasize);
                if (read == -1)
                {
                    Tiff.Error(Tiff2PdfConstants.TIFF2PDF_MODULE,
                        "Error on decoding tile {0} of {1}", tile, input.FileName());
                    m_error = true;
                    return 0;
                }
            }
            else
            {
                if (m_pdf_sample == t2p_sample_t.T2P_SAMPLE_PLANAR_SEPARATE_TO_CONTIG)
                {
                    int septilesize = input.TileSize();
                    int septilecount = input.NumberOfTiles();
                    int tilecount = septilecount / m_tiff_samplesperpixel;
                    buffer = new byte [m_tiff_datasize];
                    byte[] samplebuffer = new byte [m_tiff_datasize];
                    int samplebufferoffset = 0;
                    for (short i = 0; i < m_tiff_samplesperpixel; i++)
                    {
                        int read = input.ReadEncodedTile(tile + i * tilecount, samplebuffer, samplebufferoffset, septilesize);
                        if (read == -1)
                        {
                            Tiff.Error(Tiff2PdfConstants.TIFF2PDF_MODULE,
                                "Error on decoding tile {0} of {1}", 
                                tile + i * tilecount, input.FileName());
                            m_error = true;
                            return 0;
                        }

                        samplebufferoffset += read;
                    }

                    sample_planar_separate_to_contig(buffer, bufferoffset, samplebuffer, samplebufferoffset);
                    bufferoffset += samplebufferoffset;
                }

                if (buffer == null)
                {
                    buffer = new byte [m_tiff_datasize];
                    int read = input.ReadEncodedTile(tile, buffer, bufferoffset, m_tiff_datasize);
                    if (read == -1)
                    {
                        Tiff.Error(Tiff2PdfConstants.TIFF2PDF_MODULE,
                            "Error on decoding tile {0} of {1}",
                            tile, input.FileName());
                        m_error = true;
                        return 0;
                    }
                }

                if ((m_pdf_sample & t2p_sample_t.T2P_SAMPLE_RGBA_TO_RGB) != 0)
                    m_tiff_datasize = sample_rgba_to_rgb(buffer, m_tiff_pages[m_pdf_page].tiles_tilewidth * m_tiff_pages[m_pdf_page].tiles_tilelength);

                if ((m_pdf_sample & t2p_sample_t.T2P_SAMPLE_RGBAA_TO_RGB) != 0)
                    m_tiff_datasize = sample_rgbaa_to_rgb(buffer, m_tiff_pages[m_pdf_page].tiles_tilewidth * m_tiff_pages[m_pdf_page].tiles_tilelength);

                if ((m_pdf_sample & t2p_sample_t.T2P_SAMPLE_YCBCR_TO_RGB) != 0)
                {
                    Tiff.Error(Tiff2PdfConstants.TIFF2PDF_MODULE,
                        "No support for YCbCr to RGB in tile for {0}", input.FileName());
                    m_error = true;
                    return 0;
                }

                if ((m_pdf_sample & t2p_sample_t.T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED) != 0)
                    m_tiff_datasize = sample_lab_signed_to_unsigned(buffer, m_tiff_pages[m_pdf_page].tiles_tilewidth * m_tiff_pages[m_pdf_page].tiles_tilelength);
            }

            if (tile_is_right_edge(m_tiff_pages[m_pdf_page], tile))
                tile_collapse_left(buffer, input.TileRowSize(), m_tiff_pages[m_pdf_page].tiles_tilewidth, m_tiff_pages[m_pdf_page].tiles_edgetilewidth, m_tiff_pages[m_pdf_page].tiles_tilelength);

            disable(m_output);
            m_output.SetField(TiffTag.PHOTOMETRIC, m_tiff_photometric);
            m_output.SetField(TiffTag.BITSPERSAMPLE, m_tiff_bitspersample);
            m_output.SetField(TiffTag.SAMPLESPERPIXEL, m_tiff_samplesperpixel);

            if (!tile_is_right_edge(m_tiff_pages[m_pdf_page], tile))
                m_output.SetField(TiffTag.IMAGEWIDTH, m_tiff_pages[m_pdf_page].tiles_tilewidth);
            else
                m_output.SetField(TiffTag.IMAGEWIDTH, m_tiff_pages[m_pdf_page].tiles_edgetilewidth);

            if (!tile_is_bottom_edge(m_tiff_pages[m_pdf_page], tile))
            {
                m_output.SetField(TiffTag.IMAGELENGTH, m_tiff_pages[m_pdf_page].tiles_tilelength);
                m_output.SetField(TiffTag.ROWSPERSTRIP, m_tiff_pages[m_pdf_page].tiles_tilelength);
            }
            else
            {
                m_output.SetField(TiffTag.IMAGELENGTH, m_tiff_pages[m_pdf_page].tiles_edgetilelength);
                m_output.SetField(TiffTag.ROWSPERSTRIP, m_tiff_pages[m_pdf_page].tiles_edgetilelength);
            }

            m_output.SetField(TiffTag.PLANARCONFIG, PlanarConfig.CONTIG);
            m_output.SetField(TiffTag.FILLORDER, FillOrder.MSB2LSB);

            switch (m_pdf_compression)
            {
                case t2p_compress_t.T2P_COMPRESS_NONE:
                    m_output.SetField(TiffTag.COMPRESSION, Compression.NONE);
                    break;

                case t2p_compress_t.T2P_COMPRESS_G4:
                    m_output.SetField(TiffTag.COMPRESSION, Compression.CCITTFAX4);
                    break;
                
                case t2p_compress_t.T2P_COMPRESS_JPEG:
                    if (m_tiff_photometric == Photometric.YCBCR)
                    {
                        result = input.GetField(TiffTag.YCBCRSUBSAMPLING);
                        if (result != null)
                        {
                            short hor = result[0].ToShort();
                            short ver = result[1].ToShort();
                            if (hor != 0 && ver != 0)
                                m_output.SetField(TiffTag.YCBCRSUBSAMPLING, hor, ver);
                        }

                        result = input.GetField(TiffTag.REFERENCEBLACKWHITE);
                        if (result != null)
                        {
                            float[] xfloatp = result[0].ToFloatArray();
                            m_output.SetField(TiffTag.REFERENCEBLACKWHITE, xfloatp);
                        }
                    }
                    
                    m_output.SetField(TiffTag.COMPRESSION, Compression.JPEG);
                    m_output.SetField(TiffTag.JPEGTABLESMODE, 0); /* JpegTablesMode.NONE */

                    if ((m_pdf_colorspace & (t2p_cs_t.T2P_CS_RGB | t2p_cs_t.T2P_CS_LAB)) != 0)
                    {
                        m_output.SetField(TiffTag.PHOTOMETRIC, Photometric.YCBCR);
                        if (m_tiff_photometric != Photometric.YCBCR)
                            m_output.SetField(TiffTag.JPEGCOLORMODE, JpegColorMode.RGB);
                        else
                            m_output.SetField(TiffTag.JPEGCOLORMODE, JpegColorMode.RAW);
                    }

                    if (m_pdf_defaultcompressionquality != 0)
                        m_output.SetField(TiffTag.JPEGQUALITY, m_pdf_defaultcompressionquality);

                    break;

                case t2p_compress_t.T2P_COMPRESS_ZIP:
                    m_output.SetField(TiffTag.COMPRESSION, Compression.DEFLATE);
                    if (m_pdf_defaultcompressionquality % 100 != 0)
                        m_output.SetField(TiffTag.PREDICTOR, m_pdf_defaultcompressionquality % 100);

                    if (m_pdf_defaultcompressionquality / 100 != 0)
                        m_output.SetField(TiffTag.ZIPQUALITY, (m_pdf_defaultcompressionquality / 100));

                    break;

                default:
                    break;
            }

            enable(m_output);
            m_outputwritten = 0;
            bufferoffset = m_output.WriteEncodedStrip(0, buffer, m_output.StripSize());
            buffer = null;

            if (bufferoffset == -1)
            {
                Tiff.Error(Tiff2PdfConstants.TIFF2PDF_MODULE,
                    "Error writing encoded tile to output PDF {0}", m_output.FileName());
                m_error = true;
                return 0;
            }

            return m_outputwritten;
        }
コード例 #28
0
ファイル: Copier.cs プロジェクト: XiBeichuan/hydronumerics
        /*
         * Contig -> contig by scanline while subtracting a bias image.
         */
        bool cpBiasedContig2Contig(Tiff inImage, Tiff outImage, int imagelength, int imagewidth, short spp)
        {
            if (spp == 1)
            {
                int biasSize = m_bias.ScanlineSize();
                int bufSize = inImage.ScanlineSize();

                FieldValue[] result = m_bias.GetField(TiffTag.IMAGEWIDTH);
                int biasWidth = result[0].ToInt();

                result = m_bias.GetField(TiffTag.IMAGELENGTH);
                int biasLength = result[0].ToInt();

                if (biasSize == bufSize && imagelength == biasLength && imagewidth == biasWidth)
                {
                    result = inImage.GetField(TiffTag.BITSPERSAMPLE);
                    short sampleBits = result[0].ToShort();

                    if (sampleBits == 8 || sampleBits == 16 || sampleBits == 32)
                    {
                        byte[] buf = new byte[bufSize];
                        byte[] biasBuf = new byte[bufSize];

                        for (int row = 0; row < imagelength; row++)
                        {
                            if (!inImage.ReadScanline(buf, row, 0) && !m_ignore)
                            {
                                Tiff.Error(inImage.FileName(), "Error, can't read scanline {0}", row);
                                return false;
                            }

                            if (!m_bias.ReadScanline(biasBuf, row, 0) && !m_ignore)
                            {
                                Tiff.Error(inImage.FileName(), "Error, can't read biased scanline {0}", row);
                                return false;
                            }

                            if (sampleBits == 8)
                                subtract8(buf, biasBuf, imagewidth);
                            else if (sampleBits == 16)
                                subtract16(buf, biasBuf, imagewidth);
                            else if (sampleBits == 32)
                                subtract32(buf, biasBuf, imagewidth);

                            if (!outImage.WriteScanline(buf, row, 0))
                            {
                                Tiff.Error(outImage.FileName(), "Error, can't write scanline {0}", row);
                                return false;
                            }
                        }

                        m_bias.SetDirectory(m_bias.CurrentDirectory()); /* rewind */
                        return true;
                    }
                    else
                    {
                        Tiff.Error(inImage.FileName(), "No support for biasing {0} bit pixels\n", sampleBits);
                        return false;
                    }
                }

                Tiff.Error(inImage.FileName(), "Bias image {0},{1}\nis not the same size as {2},{3}\n",
                    m_bias.FileName(), m_bias.CurrentDirectory(), inImage.FileName(), inImage.CurrentDirectory());
                return false;
            }
            else
            {
                Tiff.Error(inImage.FileName(), "Can't bias {0},{1} as it has >1 Sample/Pixel\n",
                    inImage.FileName(), inImage.CurrentDirectory());
                return false;
            }
        }
コード例 #29
0
ファイル: T2P.cs プロジェクト: dronab/libtiff.net
        /*
        This function writes the PDF Info structure to output.
        */
        private int write_pdf_info(Tiff input)
        {
            if (m_pdf_datetime == null)
                pdf_tifftime(input);

            int written = writeToFile("<< ");
            if (!m_testFriendly)
            {
                if (strlen(m_pdf_datetime) > 0)
                {
                    written += writeToFile("\n/CreationDate ");
                    written += write_pdf_string(m_pdf_datetime);
                    written += writeToFile("\n/ModDate ");
                    written += write_pdf_string(m_pdf_datetime);
                }

                written += writeToFile("\n/Producer ");
                string buffer = string.Format(CultureInfo.InvariantCulture,
                    "libtiff / tiff2pdf - {0}", Tiff.AssemblyVersion);
                written += write_pdf_string(Latin1Encoding.GetBytes(buffer));
            }

            written += writeToFile("\n");

            FieldValue[] result = null;
            if (m_pdf_creator != null)
            {
                if (strlen(m_pdf_creator) > 0)
                {
                    byte[] buf = m_pdf_creator;
                    if (strlen(m_pdf_creator) > 511)
                    {
                        buf = new byte[512];
                        Buffer.BlockCopy(m_pdf_creator, 0, buf, 0, 511);
                    }

                    written += writeToFile("/Creator ");
                    written += write_pdf_string(buf);
                    written += writeToFile("\n");
                }
            }
            else
            {
                result = input.GetField(TiffTag.SOFTWARE);
                if (result != null)
                {
                    byte[] info = result[0].ToByteArray();
                    byte[] buf = info;
                    if (strlen(info) > 511)
                    {
                        buf = new byte[512];
                        Buffer.BlockCopy(info, 0, buf, 0, 511);
                    }

                    written += writeToFile("/Creator ");
                    written += write_pdf_string(buf);
                    written += writeToFile("\n");
                }
            }

            if (m_pdf_author != null)
            {
                if (strlen(m_pdf_author) > 0)
                {
                    byte[] buf = m_pdf_author;
                    if (strlen(m_pdf_author) > 511)
                    {
                        buf = new byte[512];
                        Buffer.BlockCopy(m_pdf_author, 0, buf, 0, 511);
                    }

                    written += writeToFile("/Author ");
                    written += write_pdf_string(buf);
                    written += writeToFile("\n");
                }
            }
            else
            {
                result = input.GetField(TiffTag.ARTIST);
                if (result != null)
                {
                    byte[] info = result[0].ToByteArray();
                    byte[] buf = info;
                    if (strlen(info) > 511)
                    {
                        buf = new byte[512];
                        Buffer.BlockCopy(info, 0, buf, 0, 511);
                    }

                    written += writeToFile("/Author ");
                    written += write_pdf_string(buf);
                    written += writeToFile("\n");
                }
                else
                {
                    result = input.GetField(TiffTag.COPYRIGHT);
                    if (result != null)
                    {
                        byte[] info = result[0].ToByteArray();
                        byte[] buf = info;
                        if (strlen(info) > 511)
                        {
                            buf = new byte[512];
                            Buffer.BlockCopy(info, 0, buf, 0, 511);
                        }

                        written += writeToFile("/Author ");
                        written += write_pdf_string(buf);
                        written += writeToFile("\n");
                    }
                }
            }

            if (m_pdf_title != null)
            {
                if (strlen(m_pdf_title) > 0)
                {
                    byte[] buf = m_pdf_title;
                    if (strlen(m_pdf_title) > 511)
                    {
                        buf = new byte[512];
                        Buffer.BlockCopy(m_pdf_title, 0, buf, 0, 511);
                    }

                    written += writeToFile("/Title ");
                    written += write_pdf_string(buf);
                    written += writeToFile("\n");
                }
            }
            else
            {
                result = input.GetField(TiffTag.DOCUMENTNAME);
                if (result != null)
                {
                    byte[] info = result[0].ToByteArray();
                    byte[] buf = info;
                    if (strlen(info) > 511)
                    {
                        buf = new byte[512];
                        Buffer.BlockCopy(info, 0, buf, 0, 511);
                    }

                    written += writeToFile("/Title ");
                    written += write_pdf_string(buf);
                    written += writeToFile("\n");
                }
            }
            
            if (m_pdf_subject != null)
            {
                if (strlen(m_pdf_subject) > 0)
                {
                    byte[] buf = m_pdf_subject;
                    if (strlen(m_pdf_subject) > 511)
                    {
                        buf = new byte[512];
                        Buffer.BlockCopy(m_pdf_subject, 0, buf, 0, 511);
                    }

                    written += writeToFile("/Subject ");
                    written += write_pdf_string(buf);
                    written += writeToFile("\n");
                }
            }
            else
            {
                result = input.GetField(TiffTag.IMAGEDESCRIPTION);
                if (result != null)
                {
                    byte[] info = result[0].ToByteArray();
                    byte[] buf = info;
                    if (strlen(info) > 511)
                    {
                        buf = new byte[512];
                        Buffer.BlockCopy(info, 0, buf, 0, 511);
                    }

                    written += writeToFile("/Subject ");
                    written += write_pdf_string(buf);
                    written += writeToFile("\n");
                }
            }

            if (m_pdf_keywords != null)
            {
                if (strlen(m_pdf_keywords) > 0)
                {
                    byte[] buf = m_pdf_keywords;
                    if (strlen(m_pdf_keywords) > 511)
                    {
                        buf = new byte[512];
                        Buffer.BlockCopy(m_pdf_keywords, 0, buf, 0, 511);
                    }

                    written += writeToFile("/Keywords ");
                    written += write_pdf_string(buf);
                    written += writeToFile("\n");
                }
            }

            written += writeToFile(">> \n");
            return written;
        }