public FillOrder CreateFillOrder(FillOrder createdFillOrder)
        {
            int newFillOrderId;

            try
            {
                newFillOrderId = _db.ExecuteScalar <int>(@"
                INSERT INTO fillorders (productId, stock, processed, createdDate, processDate)
                VALUES (@ProductId, @Stock, @Processed, @CreatedDate, @ProcessDate);
                SELECT LAST_INSERT_ID();
                ", createdFillOrder);
            }
            catch (Exception exception)
            {
                throw exception;
            }

            createdFillOrder.Id = newFillOrderId;
            return(createdFillOrder);
            //return new FillOrder()
            //{
            //    ProcessDate = null,
            //    Id = 1,
            //    Processed = false,
            //    ProductId = 1,
            //    Stock = 1,
            //    CreatedDate = DateTimeOffset.Now
            //};
        }
Exemple #2
0
 public static void ValidateFillOrderUnprocessed(FillOrder fillOrder)
 {
     if (fillOrder.Processed || fillOrder.ProcessDate != null)
     {
         throw new Exception("Fill Order has already been processed!");
     }
 }
        public void Resolved_FillOrders_Can_Not_Be_Processed()
        {
            // Arrange
            var fillOrderToBeProcessed = new FillOrder()
            {
                Id = 1121,
                ProcessedTimestamp = DateTimeOffset.Now
            };

            _mockFillOrderRepo.GetFillOrderById(fillOrderToBeProcessed.Id).Returns(new FillOrder()
            {
                Id = 1121,
                ProcessedTimestamp = DateTimeOffset.Now.AddDays(-1)
            });

            // Act
            try
            {
                var result = _fillOrderService.ProcessFillOrder(fillOrderToBeProcessed);
            }
            catch (Exception ex)
            {
                // Assert
                Assert.Equal("Fill Order has already been processed", ex.Message);
            }
        }
Exemple #4
0
 private static DoubleByteTiffInfo CreateDoubleByteTiffInfo(byte[] buffer, List <ushort[]> ushortBuffer, int width,
                                                            int height, string filePath,
                                                            int rowsPerStrip,
                                                            int xResolution, int yResolution, ResUnit resUnit = ResUnit.INCH,
                                                            PlanarConfig planarConfig = PlanarConfig.CONTIG,
                                                            int bytePerSample         = 16, Photometric photometric = Photometric.MINISBLACK,
                                                            Compression compression   = Compression.NONE,
                                                            int samplePerPixel        = 1, Orientation orientation = Orientation.TOPLEFT,
                                                            FillOrder fillOrder       = FillOrder.MSB2LSB)
 {
     return(new DoubleByteTiffInfo()
     {
         FilePath = filePath,
         Buffer = buffer,
         UshortBuffer = ushortBuffer,
         Width = width,
         Height = height,
         RowsPerStrip = rowsPerStrip,
         XResolution = xResolution,
         YResolution = yResolution,
         ResolutionUnit = resUnit,
         PlanarConfig = planarConfig,
         BitsPerSample = bytePerSample,
         Photometric = photometric,
         Compression = compression,
         SamplesPerPixel = samplePerPixel,
         Orientation = orientation,
         FillOrder = fillOrder
     });
 }
Exemple #5
0
 public static void ValidateProductId(FillOrder fillOrder)
 {
     if (fillOrder.ProductId < 0)
     {
         throw new Exception("Fill Order must have valid Product Id");
     }
 }
        /// <summary>
        /// Calculates the areas for individual buttons which will fill the button area
        /// </summary>
        private void CalculateSpaces(int rows, int cols, int pad, FillOrder fillOrder)
        {
            // initialize space dimensions and arrays
            int spaceWidth = (area.Width - (cols - 1) * pad - 2 * pad) / cols;
            int spaceHeight = (area.Height - (rows - 1) * pad - 2 * pad) / rows;
            spaces = new Rectangle[cols * rows];

            if (fillOrder == FillOrder.RowsFirst)
            {
                for (int row = 0; row < rows; row++)
                {
                    for (int col = 0; col < cols; col++)
                    {
                        int x = area.X + col * (pad + spaceWidth) + pad;
                        int y = area.Y + row * (pad + spaceHeight) + pad;
                        spaces[row * cols + col] = new Rectangle(x, y, spaceWidth, spaceHeight);
                    }
                }
            }
            else
            {
                for (int col = 0; col < cols; col++)
                {
                    for (int row = 0; row < rows; row++)
                    {
                        int x = area.X + col * (pad + spaceWidth) + pad;
                        int y = area.Y + row * (pad + spaceHeight) + pad;
                        spaces[col * rows + row] = new Rectangle(x, y, spaceWidth, spaceHeight);
                    }
                }
            }
        }
        /// <summary>
        /// Calculates the areas for individual buttons which will fill the button area
        /// </summary>
        private void CalculateSpaces(int rows, int cols, int pad, FillOrder fillOrder)
        {
            // initialize space dimensions and arrays
            int spaceWidth  = (area.Width - (cols - 1) * pad - 2 * pad) / cols;
            int spaceHeight = (area.Height - (rows - 1) * pad - 2 * pad) / rows;

            spaces = new Rectangle[cols * rows];

            if (fillOrder == FillOrder.RowsFirst)
            {
                for (int row = 0; row < rows; row++)
                {
                    for (int col = 0; col < cols; col++)
                    {
                        int x = area.X + col * (pad + spaceWidth) + pad;
                        int y = area.Y + row * (pad + spaceHeight) + pad;
                        spaces[row * cols + col] = new Rectangle(x, y, spaceWidth, spaceHeight);
                    }
                }
            }
            else
            {
                for (int col = 0; col < cols; col++)
                {
                    for (int row = 0; row < rows; row++)
                    {
                        int x = area.X + col * (pad + spaceWidth) + pad;
                        int y = area.Y + row * (pad + spaceHeight) + pad;
                        spaces[col * rows + row] = new Rectangle(x, y, spaceWidth, spaceHeight);
                    }
                }
            }
        }
Exemple #8
0
 public static void ValidateStock(FillOrder fillOrder)
 {
     if (fillOrder.Stock == 0)
     {
         throw new Exception("Fill Order can not have a stock value of 0.");
     }
 }
        public IActionResult ProcessFillOrder([FromBody] FillOrder fillOrder)
        {
            if (!ModelState.IsValid)
            {
                throw new Exception();
            }

            return(Ok(_fillOrderService.ProcessFillOrder(fillOrder)));
        }
Exemple #10
0
        public void FillOrderTest1()
        {
            Page      target   = new Page();
            FillOrder expected = FillOrder.LowBitsFirst;
            FillOrder actual;

            actual = target.FillOrder;
            Assert.Equal(expected, actual);
        }
Exemple #11
0
        public FillOrder ProcessFillOrder(string id)
        {
            FillOrder order = FakeDbConnect.Db.Find(o => o.Id == id);

            order.OrderClosed    = true;
            order.OrderProcessed = DateTime.Now;

            return(order);
        }
Exemple #12
0
 public IActionResult CreateFillOrder([FromBody] FillOrder createdFillOrder)
 {
     try
     {
         return(Created("", _fillOrderService.CreateFillOrder(createdFillOrder)));
     }
     catch (Exception exception)
     {
         return(NotFound(exception.Message));
     }
 }
Exemple #13
0
        public FillOrder ProcessFillOrder(string id)
        {
            FillOrder currentOrder = _fillOrderRepo.GetOrderById(id);

            if (currentOrder.OrderClosed)
            {
                //not graceful but was running low on time.
                throw new Exception("Order Already closed");
            }
            return(_fillOrderRepo.ProcessFillOrder(id));
        }
Exemple #14
0
        public void FillOrderTest()
        {
            var       tif      = Tif.Load(testFilePath);
            Page      target   = tif[0];
            FillOrder expected = FillOrder.LowBitsFirst;
            FillOrder actual;

            target.FillOrder = expected;
            actual           = target.FillOrder;
            Assert.Equal(expected, actual);
        }
 public void UpdateFillOrder(FillOrder editedFillOrder)
 {
     _db.Execute(@"
         UPDATE fillorders SET
             productId = @ProductId,
             stock = @Stock,
             processed = @Processed,
             processDate = @processDate
         WHERE id = @Id;
     ", editedFillOrder);
 }
Exemple #16
0
 public IActionResult ProcessFillOrder([FromBody] FillOrder submittedFillOrder)
 {
     try
     {
         _fillOrderService.ProcessFillOrder(submittedFillOrder);
         return(Ok());
     }
     catch (Exception exception)
     {
         return(NotFound(exception.Message));
     }
 }
Exemple #17
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="buffer">字节数组</param>
        /// <param name="width">图像的宽</param>
        /// <param name="height">图像的高</param>
        /// <param name="filePath"></param>
        /// <param name="rowsPerStrip">图像的实际高度</param>
        /// <param name="xResolution">x分辨率</param>
        /// <param name="yResolution">y分辨率</param>
        /// <param name="resUnit">分辨率单位,默认选inch</param>
        /// <param name="planarConfig">数据平面存储方式</param>
        /// <param name="bytePerSample">单个像素是多少位</param>
        /// <param name="photometric">图像模式</param>
        /// <param name="compression">压缩方式</param>
        /// <param name="samplePerPixel">一个像素几个采样</param>
        /// <param name="orientation">方向</param>
        /// <param name="fillOrder">大小端</param>
        public static void CreateGrayScaleTiff(byte[] buffer, int width, int height, string filePath, int rowsPerStrip,
                                               int xResolution, int yResolution, ResUnit resUnit = ResUnit.INCH,
                                               PlanarConfig planarConfig = PlanarConfig.CONTIG,
                                               int bytePerSample         = 16, Photometric photometric = Photometric.MINISBLACK,
                                               Compression compression   = Compression.NONE,
                                               int samplePerPixel        = 1, Orientation orientation = Orientation.TOPLEFT,
                                               FillOrder fillOrder       = FillOrder.MSB2LSB)
        {
            var info = CreateDoubleByteTiffInfo(buffer, null, width, height, filePath, height, width, height);

            Create16BitGrayScaleTiff(info);
        }
        public void UpdateFillOrder(FillOrder fillOrder)
        {
            var fillOrderToUpdate = GetFillOrderById(fillOrder.Id);

            if (fillOrderToUpdate == null)
            {
                throw new Exception("Fill order does not exist");
            }

            _fillOrders.Remove(fillOrderToUpdate);
            _fillOrders.Add(fillOrder);
        }
Exemple #19
0
        //I know this is not how you deal with a database, but I am faking it due to lack of time.
        //private readonly IDbConnection _db;

        public FillOrder CreateFillOrder()
        {
            FillOrder newOrder = new FillOrder
            {
                Id           = Guid.NewGuid().ToString(),
                OrderCreated = DateTime.Now,
                OrderClosed  = false,
            };

            FakeDbConnect.Db.Add(newOrder);
            return(newOrder);
        }
 public FillOrder CreateFillOrder(FillOrder newFillOrder)
 {
     newFillOrder.CreatedDate = DateTime.Now;
     newFillOrder.ProcessDate = null;
     newFillOrder.Processed   = false;
     try
     {
         FillOrderValidator.ValidateProductId(newFillOrder);
         FillOrderValidator.ValidateStock(newFillOrder);
         return(_fillOrderRepo.CreateFillOrder(newFillOrder));
     }
     catch (Exception exception)
     {
         throw exception;
     }
 }
        private void BuildFillOrders()
        {
            Random randomGen = new Random();

            for (int i = 5; i > 0; i--)
            {
                var fillOrder = new FillOrder()
                {
                    Id        = i,
                    OrderType = i % 2 == 0 ? OrderTypeEnum.AddStock : OrderTypeEnum.RemoveStock,
                    ProductId = randomGen.Next(100, 500),
                    Quantity  = i * randomGen.Next(5, 100)
                };
                _fillOrders.Add(fillOrder);
            }
        }
        public void ProcessFillOrder(FillOrder submittedFillOrder)
        {
            FillOrder actualFillOrder = _fillOrderRepo.GetFillOrderById(submittedFillOrder.Id);

            try
            {
                FillOrderValidator.ValidateFillOrderUnprocessed(actualFillOrder);
                actualFillOrder.Processed   = true;
                actualFillOrder.ProcessDate = DateTime.Now;
                _fillOrderRepo.UpdateFillOrder(actualFillOrder);
            }
            catch (Exception)
            {
                throw new Exception("FillOrder cannot be processed. Try again later.");
            }
        }
        public FillOrderServiceTests()
        {
            _mockFillOrderRepo   = Substitute.For <IFillOrderRepo>();
            _fillOrderService    = new FillOrderService(_mockFillOrderRepo);
            unresolvedFillOrders = new List <FillOrder>();

            Random randomGen = new Random();

            for (int i = 5; i > 0; i--)
            {
                var fillOrder = new FillOrder()
                {
                    Id        = i,
                    OrderType = i % 2 == 0 ? OrderTypeEnum.AddStock : OrderTypeEnum.RemoveStock,
                    ProductId = randomGen.Next(100, 500),
                    Quantity  = i * randomGen.Next(5, 100)
                };
                unresolvedFillOrders.Add(fillOrder);
            }
        }
        public FillOrder ProcessFillOrder(FillOrder fillOrder)
        {
            var currentFillOrder = GetFillOrderById(fillOrder.Id);

            if (currentFillOrder == null)
            {
                throw new Exception("Fill Order not found");
            }

            if (currentFillOrder.ProcessedTimestamp != null)
            {
                throw new Exception("Fill Order has already been processed");
            }

            currentFillOrder.ProcessedTimestamp = DateTimeOffset.Now;

            _fillOrderRepo.UpdateFillOrder(currentFillOrder);

            return(currentFillOrder);
        }
        public void Unresolved_FillOrders_Can_Be_Processed()
        {
            // Arrange
            var fillOrderToBeProcessed = new FillOrder()
            {
                Id = 1121,
            };

            _mockFillOrderRepo.GetFillOrderById(fillOrderToBeProcessed.Id).Returns(new FillOrder()
            {
                Id = 1121,
                ProcessedTimestamp = null
            });

            // Act
            var processedFillOrder = _fillOrderService.ProcessFillOrder(fillOrderToBeProcessed);

            // Assert
            Assert.NotNull(processedFillOrder.ProcessedTimestamp);
            _mockFillOrderRepo.Received(1).GetFillOrderById(fillOrderToBeProcessed.Id);
            _mockFillOrderRepo.ReceivedWithAnyArgs(1).UpdateFillOrder(processedFillOrder);
        }
Exemple #26
0
        public TiffDirectory()
        {
            td_subfiletype  = 0;
            td_compression  = 0;
            td_photometric  = 0;
            td_planarconfig = 0;

            td_fillorder            = FillOrder.MSB2LSB;
            td_bitspersample        = 1;
            td_threshholding        = Threshold.BILEVEL;
            td_orientation          = Orientation.TOPLEFT;
            td_samplesperpixel      = 1;
            td_rowsperstrip         = -1;
            td_tiledepth            = 1;
            td_stripbytecountsorted = true; // Our own arrays always sorted.
            td_resolutionunit       = ResUnit.INCH;
            td_sampleformat         = SampleFormat.UINT;
            td_imagedepth           = 1;
            td_ycbcrsubsampling[0]  = 2;
            td_ycbcrsubsampling[1]  = 2;
            td_ycbcrpositioning     = YCbCrPosition.CENTERED;
        }
Exemple #27
0
        public void Processed_FillOrder_CannontBe_Modified()
        {
            int       fillOrderId   = 1;
            FillOrder testFillOrder = new FillOrder()
            {
                Id = fillOrderId, ProductId = 1, Processed = true, CreatedDate = DateTime.Now, ProcessDate = DateTime.Now, Stock = 1
            };
            var mockFillOrderRepo = Substitute.For <IFillOrderRepo>();

            mockFillOrderRepo.GetFillOrderById(fillOrderId).Returns(testFillOrder);
            FillOrderService fillOrderService = new FillOrderService(mockFillOrderRepo);

            try
            {
                fillOrderService.ProcessFillOrder(testFillOrder);
                Assert.Fail("FillOrder was processed!");
            }
            catch (Exception exception)
            {
                Assert.AreEqual("FillOrder cannot be processed. Try again later.", exception.Message);
                return;
            }
        }
Exemple #28
0
        public void Unresolved_FillOrder_CanBe_Processed()
        {
            int       fillOrderId   = 1;
            FillOrder testFillOrder = new FillOrder()
            {
                Id = fillOrderId, ProductId = 1, Processed = false, CreatedDate = DateTime.Now, ProcessDate = null, Stock = 1
            };
            var mockFillOrderRepo = Substitute.For <IFillOrderRepo>();

            mockFillOrderRepo.GetFillOrderById(fillOrderId).Returns(testFillOrder);
            FillOrderService fillOrderService = new FillOrderService(mockFillOrderRepo);

            try
            {
                fillOrderService.ProcessFillOrder(testFillOrder);
                Assert.IsTrue(true);
            }
            catch (Exception exception)
            {
                Assert.Fail(exception.Message);
                return;
            }
        }
 public ControlMat(Rectangle area, int rows, int cols, int pad, FillOrder fillOrder)
 {
     this.area = area;
     CalculateSpaces(rows, cols, pad, fillOrder);
 }
Exemple #30
0
        private bool isFillOrder(FillOrder o)
        {
            TiffFlags order = (TiffFlags)o;

            return((m_flags & order) == order);
        }
Exemple #31
0
        public static void Main(string[] args)
        {
            Copier c = new Copier();

            StringBuilder mode = new StringBuilder();

            mode.Append('w');

            char         imageNumberSeparator   = ','; // (default) comma separator character
            FillOrder    defaultFillOrder       = 0;
            int          defaultTileLength      = -1;
            int          initialDirectoryOffset = 0;
            PlanarConfig defaultPlanarConfig    = PlanarConfig.UNKNOWN;
            int          defaultRowsPerStrip    = 0;
            int          defaultTileWidth       = -1;

            int argn = 0;

            for (; argn < args.Length; argn++)
            {
                string option = args[argn];
                if (option[0] == '-')
                {
                    option = option.Substring(1);
                }
                else
                {
                    break;
                }

                string optionArg = null;
                if (argn < (args.Length - 1))
                {
                    optionArg = args[argn + 1];
                }

                switch (option[0])
                {
                case ',':
                    if (option[1] != '=')
                    {
                        usage();
                        return;
                    }

                    imageNumberSeparator = option[2];
                    break;

                case 'b':
                    // this file is bias image subtracted from others
                    if (c.m_bias != null)
                    {
                        Console.Error.Write("Only 1 bias image may be specified\n");
                        return;
                    }

                    string biasName = args[argn + 1];
                    c.m_bias = Tiff.Open(biasName, "r");
                    if (c.m_bias == null)
                    {
                        Console.Error.WriteLine("Failed to open '{0}' as input.", biasName);
                        return;
                    }

                    if (c.m_bias.IsTiled())
                    {
                        Console.Error.Write("Bias image must be organized in strips\n");
                        return;
                    }

                    FieldValue[] result  = c.m_bias.GetField(TiffTag.SAMPLESPERPIXEL);
                    short        samples = result[0].ToShort();
                    if (samples != 1)
                    {
                        Console.Error.Write("Bias image must be monochrome\n");
                        return;
                    }

                    argn++;
                    break;

                case 'a':
                    // append to output
                    mode[0] = 'a';
                    break;

                case 'c':
                    // compression scheme
                    if (!c.ProcessCompressOptions(optionArg))
                    {
                        usage();
                        return;
                    }

                    argn++;
                    break;

                case 'f':
                    // fill order
                    if (optionArg == "lsb2msb")
                    {
                        defaultFillOrder = FillOrder.LSB2MSB;
                    }
                    else if (optionArg == "msb2lsb")
                    {
                        defaultFillOrder = FillOrder.MSB2LSB;
                    }
                    else
                    {
                        usage();
                        return;
                    }

                    argn++;
                    break;

                case 'i':
                    // ignore errors
                    c.m_ignore = true;
                    break;

                case 'l':
                    // tile length
                    c.m_outtiled      = 1;
                    defaultTileLength = int.Parse(optionArg, CultureInfo.InvariantCulture);
                    argn++;
                    break;

                case 'o':
                    // initial directory offset
                    initialDirectoryOffset = int.Parse(optionArg, CultureInfo.InvariantCulture);
                    break;

                case 'p':
                    // planar configuration
                    if (optionArg == "separate")
                    {
                        defaultPlanarConfig = PlanarConfig.SEPARATE;
                    }
                    else if (optionArg == "contig")
                    {
                        defaultPlanarConfig = PlanarConfig.CONTIG;
                    }
                    else
                    {
                        usage();
                        return;
                    }

                    argn++;
                    break;

                case 'r':
                    // rows/strip
                    defaultRowsPerStrip = int.Parse(optionArg, CultureInfo.InvariantCulture);
                    argn++;
                    break;

                case 's':
                    // generate stripped output
                    c.m_outtiled = 0;
                    break;

                case 't':
                    // generate tiled output
                    c.m_outtiled = 1;
                    break;

                case 'w':
                    // tile width
                    c.m_outtiled     = 1;
                    defaultTileWidth = int.Parse(optionArg, CultureInfo.InvariantCulture);
                    argn++;
                    break;

                case 'B':
                    mode.Append('b');
                    break;

                case 'L':
                    mode.Append('l');
                    break;

                case 'M':
                    mode.Append('m');
                    break;

                case 'C':
                    mode.Append('c');
                    break;

                case 'x':
                    c.m_pageInSeq = 1;
                    break;

                case '?':
                    usage();
                    return;
                }
            }

            if (args.Length - argn < 2)
            {
                // there must be at least one input and one output image names after options
                usage();
                return;
            }

            using (Tiff outImage = Tiff.Open(args[args.Length - 1], mode.ToString()))
            {
                if (outImage == null)
                {
                    Console.Error.WriteLine("Failed to open '{0}' as output.", args[args.Length - 1]);
                    return;
                }

                if ((args.Length - argn) == 2)
                {
                    c.m_pageNum = -1;
                }

                for (; argn < args.Length - 1; argn++)
                {
                    string[] fileAndPageNums = args[argn].Split(new char[] { imageNumberSeparator });

                    using (Tiff inImage = Tiff.Open(fileAndPageNums[0], "r"))
                    {
                        if (inImage == null)
                        {
                            return;
                        }

                        if (initialDirectoryOffset != 0 && !inImage.SetSubDirectory(initialDirectoryOffset))
                        {
                            Tiff.Error(inImage.FileName(), "Error, setting subdirectory at 0x{0:x}", initialDirectoryOffset);
                            break;
                        }

                        int initialPage = 0;
                        int pageNumPos  = 1;

                        if (pageNumPos < fileAndPageNums.Length && !string.IsNullOrEmpty(fileAndPageNums[pageNumPos]))
                        {
                            initialPage = int.Parse(fileAndPageNums[pageNumPos]);
                        }

                        int totalPages = inImage.NumberOfDirectories();
                        for (int i = initialPage; i < totalPages;)
                        {
                            c.m_config       = defaultPlanarConfig;
                            c.m_compression  = c.m_defcompression;
                            c.m_predictor    = c.m_defpredictor;
                            c.m_fillorder    = defaultFillOrder;
                            c.m_rowsperstrip = defaultRowsPerStrip;
                            c.m_tilewidth    = defaultTileWidth;
                            c.m_tilelength   = defaultTileLength;
                            c.m_g3opts       = c.m_defg3opts;

                            if (!inImage.SetDirectory((short)i))
                            {
                                Console.Error.Write("{0}{1}{2} not found!\n",
                                                    inImage.FileName(), imageNumberSeparator, i);
                                return;
                            }

                            if (!c.Copy(inImage, outImage) || !outImage.WriteDirectory())
                            {
                                return;
                            }

                            // if we have at least one page specifier and current specifier is not empty.
                            // specifier is empty when trailing separator used like this: "file,num,"
                            if (pageNumPos < fileAndPageNums.Length && !string.IsNullOrEmpty(fileAndPageNums[pageNumPos]))
                            {
                                // move to next page specifier
                                pageNumPos++;

                                if (pageNumPos < fileAndPageNums.Length)
                                {
                                    // new page specifier position is valid

                                    if (!string.IsNullOrEmpty(fileAndPageNums[pageNumPos]))
                                    {
                                        // new page specifier is not empty. use specified page number
                                        i = int.Parse(fileAndPageNums[pageNumPos]);
                                    }
                                    else
                                    {
                                        // new page specifier is empty. just move to the next page
                                        i++;
                                    }
                                }
                                else
                                {
                                    // new page specifier position is invalid. done all pages.
                                    break;
                                }
                            }
                            else
                            {
                                // we have no page specifiers or current page specifier is empty
                                // just move to the next page
                                i++;
                            }
                        }
                    }
                }
            }
        }
Exemple #32
0
 private bool isFillOrder(FillOrder o)
 {
     TiffFlags order = (TiffFlags)o;
     return ((m_flags & order) == order);
 }
Exemple #33
0
        /*
        This function sets the input directory to the directory of a given
        page and determines information about the image.  It checks
        the image characteristics to determine if it is possible to convert
        the image data into a page of PDF output, setting values of the T2P
        struct for this page.  It determines what color space is used in
        the output PDF to represent the image.

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

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

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

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

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

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

            }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                        m_pdf_palettesize *= 3;
                    }
                    break;

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

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

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

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

                    break;

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

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

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

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

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

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

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

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

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

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

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

            compose_pdf_page();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            if (m_tiff_bitspersample == 1 && m_tiff_samplesperpixel == 1)
                m_pdf_compression = t2p_compress_t.T2P_COMPRESS_G4;
        }
Exemple #34
0
        public byte[] buffernull = null;   // return null array

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

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

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

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

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

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

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

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

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

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

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

                    for (int count = 0; count < row * col; count++)
                    {
                        byte tempbyte = 0;
                        if ((buffer[count] & 128) != 0)
                        {
                            tempbyte += 1;
                        }
                        if ((buffer[count] & 64) != 0)
                        {
                            tempbyte += 2;
                        }
                        if ((buffer[count] & 32) != 0)
                        {
                            tempbyte += 4;
                        }
                        if ((buffer[count] & 16) != 0)
                        {
                            tempbyte += 8;
                        }
                        if ((buffer[count] & 8) != 0)
                        {
                            tempbyte += 16;
                        }
                        if ((buffer[count] & 4) != 0)
                        {
                            tempbyte += 32;
                        }
                        if ((buffer[count] & 2) != 0)
                        {
                            tempbyte += 64;
                        }
                        if ((buffer[count] & 1) != 0)
                        {
                            tempbyte += 128;
                        }
                        buffer[count] = tempbyte;
                    }
                }
                image.Close();
            }
            return(buffer);
        }
        public TiffDirectory()
        {
            td_subfiletype = 0;
            td_compression = 0;
            td_photometric = 0;
            td_planarconfig = 0;

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