/// <summary>
        /// Xors the matrix.
        /// </summary>
        /// <param name="first">The first.</param>
        /// <param name="second">The second.</param>
        /// <returns></returns>
        /// <remarks></remarks>
        private static TriStateMatrix XorMatrix(TriStateMatrix first, BitMatrix second)
        {
            int width = first.Width;
            var maskedMatrix = new TriStateMatrix(width);
            for (int x = 0; x < width; x++)
            {
                for (int y = 0; y < width; y++)
                {
                    MatrixStatus states = first.MStatus(x, y);
                    switch (states)
                    {
                        case MatrixStatus.NoMask:
                            maskedMatrix[x, y, MatrixStatus.NoMask] = first[x, y];
                            break;
                        case MatrixStatus.Data:
                            maskedMatrix[x, y, MatrixStatus.Data] = first[x, y] ^ second[x, y];
                            break;
                        default:
                            throw new ArgumentException("TristateMatrix has None value cell.", "first");
                    }
                }
            }

            return maskedMatrix;
        }
      public void testRectangularMatrix()
      {
         BitMatrix matrix = new BitMatrix(75, 20);
         Assert.AreEqual(75, matrix.Width);
         Assert.AreEqual(20, matrix.Height);
         matrix[10, 0] = true;
         matrix[11, 1] = true;
         matrix[50, 2] = true;
         matrix[51, 3] = true;
         matrix.flip(74, 4);
         matrix.flip(0, 5);

         // Should all be on
         Assert.IsTrue(matrix[10, 0]);
         Assert.IsTrue(matrix[11, 1]);
         Assert.IsTrue(matrix[50, 2]);
         Assert.IsTrue(matrix[51, 3]);
         Assert.IsTrue(matrix[74, 4]);
         Assert.IsTrue(matrix[0, 5]);

         // Flip a couple back off
         matrix.flip(50, 2);
         matrix.flip(51, 3);
         Assert.IsFalse(matrix[50, 2]);
         Assert.IsFalse(matrix[51, 3]);
      }
		public override BitMatrix sampleGrid(BitMatrix image, int dimension, float p1ToX, float p1ToY, float p2ToX, float p2ToY, float p3ToX, float p3ToY, float p4ToX, float p4ToY, float p1FromX, float p1FromY, float p2FromX, float p2FromY, float p3FromX, float p3FromY, float p4FromX, float p4FromY)
		{
			
			PerspectiveTransform transform = PerspectiveTransform.quadrilateralToQuadrilateral(p1ToX, p1ToY, p2ToX, p2ToY, p3ToX, p3ToY, p4ToX, p4ToY, p1FromX, p1FromY, p2FromX, p2FromY, p3FromX, p3FromY, p4FromX, p4FromY);
			
			return sampleGrid(image, dimension, transform);
		}
        /// <summary>
        /// Renders the matrix in an Encapsuled PostScript format.
        /// </summary>
        /// <param name="matrix">The matrix to be rendered</param>
        /// <param name="stream">Output stream that must be writable</param>
        /// <remarks></remarks>
        public void WriteToStream(BitMatrix matrix, Stream stream)
        {
            using (var writer = new StreamWriter(stream))
            {
                int width = matrix == null ? 21 : matrix.Width;

                DrawingSize drawingSize = m_iSize.GetSize(width);

                OutputHeader(drawingSize, writer);
                OutputBackground(writer);

                if (matrix != null)
                {
                    switch (m_DrawingTechnique)
                    {
                        case EpsModuleDrawingTechnique.Squares:
                            DrawSquares(matrix, writer);
                            break;
                        case EpsModuleDrawingTechnique.Image:
                            DrawImage(matrix, writer);
                            break;
                        default:
                            throw new ArgumentOutOfRangeException("DrawingTechnique");
                    }
                }

                OutputFooter(writer);
            }
        }
Exemple #5
0
		private void TestPenaltyRule(BitMatrix input, PenaltyRules penaltyRule, int expected)
		{
			Penalty penalty = new PenaltyFactory().CreateByRule(penaltyRule);
			
			int result = penalty.PenaltyCalculate(input);
			
			AssertIntEquals(expected, result, input, penaltyRule);
		}
Exemple #6
0
        public void Test_against_DataSet(TriStateMatrix input, MaskPatternType patternType, BitMatrix expected)
        {
            Pattern pattern = new PatternFactory().CreateByType(patternType);

            BitMatrix result = input.Apply(pattern, ErrorCorrectionLevel.H);

            expected.AssertEquals(result);
        }
 internal static TriStateMatrix Embed(this TriStateMatrix matrix, BitMatrix stencil, IEnumerable<MatrixPoint> locations)
 {
     foreach (MatrixPoint location in locations)
     {
         Embed(matrix, stencil, location);
     }
     return matrix;
 }
Exemple #8
0
		/// <summary>
		/// Calculate penalty value for first rule.
		/// </summary>
        internal override int PenaltyCalculate(BitMatrix matrix)
        {
            MatrixSize size = matrix.Size;
            int penaltyValue = 0;

            penaltyValue = PenaltyCalculation(matrix, true) + PenaltyCalculation(matrix, false);
            return penaltyValue;
        }
Exemple #9
0
		protected static void AssertIntEquals(int expected, int actual, BitMatrix matrix, PenaltyRules penaltyRule)
        {
			if(expected != actual)
			{
				GenerateFaultyRecord(matrix, penaltyRule, expected, actual);
				Assert.Fail("Penalty scores are different.\nExpected:{0}Actual:{1}.", expected.ToString(), actual.ToString());
				
			}
		}
 /// <summary>
 /// Initializes a new instance of the <see cref="WhiteRectangleDetector"/> class.
 /// </summary>
 /// <param name="image">The image.</param>
 /// <exception cref="ArgumentException">if image is too small</exception>
 internal WhiteRectangleDetector(BitMatrix image)
 {
    this.image = image;
    height = image.Height;
    width = image.Width;
    leftInit = (width - INIT_SIZE) >> 1;
    rightInit = (width + INIT_SIZE) >> 1;
    upInit = (height - INIT_SIZE) >> 1;
    downInit = (height + INIT_SIZE) >> 1;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="WhiteRectangleDetector"/> class.
 /// </summary>
 /// <param name="image">The image.</param>
 /// <param name="initSize">Size of the init.</param>
 /// <param name="x">The x.</param>
 /// <param name="y">The y.</param>
 internal WhiteRectangleDetector(BitMatrix image, int initSize, int x, int y)
 {
     this.image = image;
      height = image.Height;
      width = image.Width;
      int halfsize = initSize >> 1;
      leftInit = x - halfsize;
      rightInit = x + halfsize;
      upInit = y - halfsize;
      downInit = y + halfsize;
 }
      /// <summary>
      /// Creates a WhiteRectangleDetector instance
      /// </summary>
      /// <param name="image">The image.</param>
      /// <param name="initSize">Size of the init.</param>
      /// <param name="x">The x.</param>
      /// <param name="y">The y.</param>
      /// <returns>
      /// null, if image is too small, otherwise a WhiteRectangleDetector instance
      /// </returns>
      public static WhiteRectangleDetector Create(BitMatrix image, int initSize, int x, int y)
      {
         var instance = new WhiteRectangleDetector(image, initSize, x, y);

         if (instance.upInit < 0 || instance.leftInit < 0 || instance.downInit >= instance.height || instance.rightInit >= instance.width)
         {
            return null;
         }

         return instance;
      }
Exemple #13
0
        /// <summary>
        /// Patterns the check.
        /// </summary>
        /// <param name="matrix">The matrix.</param>
        /// <param name="i">The i.</param>
        /// <param name="j">The j.</param>
        /// <param name="isHorizontal">if set to <c>true</c> [is horizontal].</param>
        /// <returns></returns>
        /// <remarks></remarks>
        private int PatternCheck(BitMatrix matrix, int i, int j, bool isHorizontal)
        {
            bool bit;
            for (int num = 3; num >= 1; num--)
            {
                bit = isHorizontal
                          ? matrix[j + num, i]
                          : matrix[i, j + num];
                if (!bit)
                    return 0;
            }
            //Check for left side and right side x ( xoxxxox ).
            if ((j - 1) < 0 || (j + 1) >= matrix.Width)
                return 0;
            bit = isHorizontal
                      ? matrix[j + 5, i]
                      : matrix[i, j + 5];
            if (!bit)
                return 0;
            bit = isHorizontal
                      ? matrix[j - 1, i]
                      : matrix[i, j - 1];
            if (!bit)
                return 0;

            if ((j - 5) >= 0)
            {
                for (int num = -2; num >= -5; num--)
                {
                    bit = isHorizontal
                              ? matrix[j + num, i]
                              : matrix[i, j + num];
                    if (bit)
                        break;
                    if (num == -5)
                        return 40;
                }
            }

            if ((j + 9) < matrix.Width)
            {
                for (int num = 6; num <= 9; num++)
                {
                    bit = isHorizontal
                              ? matrix[j + num, i]
                              : matrix[i, j + num];
                    if (bit)
                        return 0;
                }
                return 40;
            }
            else
                return 0;
        }
        /// <summary>
        /// Draw qrCode dark modules at given position. (It will also include quiet zone area. Set it to zero to exclude quiet zone)
        /// </summary>
        /// <exception cref="ArgumentNullException">Bitmatrix, wBitmap should not equal to null</exception>
        /// <exception cref="ArgumentOutOfRangeException">wBitmap's pixel width or height should not equal to zero</exception>
        public void DrawDarkModule(WriteableBitmap wBitmap, BitMatrix matrix, int offsetX, int offsetY)
        {
            if (matrix == null)
                throw new ArgumentNullException("Bitmatrix");

            DrawingSize size = ISize.GetSize(matrix.Width);

            if (wBitmap == null)
                throw new ArgumentNullException("wBitmap");
            else if (wBitmap.PixelHeight == 0 || wBitmap.PixelWidth == 0)
                throw new ArgumentOutOfRangeException("wBitmap", "WriteableBitmap's pixelHeight or PixelWidth are equal to zero");

            int padding = (size.CodeWidth - size.ModuleSize * matrix.Width) / 2;

            int preX = -1;
            int moduleSize = size.ModuleSize;

            if (moduleSize == 0)
                return;

            for (int y = 0; y < matrix.Width; y++)
            {
                for (int x = 0; x < matrix.Width; x++)
                {
                    if (matrix[x, y])
                    {
                        if (preX == -1)
                            preX = x;
                        if (x == matrix.Width - 1)
                        {
                            Int32Rect moduleArea =
                                new Int32Rect(preX * moduleSize + padding + offsetX,
                                    y * moduleSize + padding + offsetY,
                                    (x - preX + 1) * moduleSize,
                                    moduleSize);
                            wBitmap.FillRectangle(moduleArea, DarkColor);
                            preX = -1;
                        }
                    }
                    else if (preX != -1)
                    {
                        Int32Rect moduleArea =
                            new Int32Rect(preX * moduleSize + padding + offsetX,
                                y * moduleSize + padding + offsetY,
                                (x - preX) * moduleSize,
                                moduleSize);
                        wBitmap.FillRectangle(moduleArea, DarkColor);
                        preX = -1;
                    }
                }
            }


        }
        /// <summary>
        /// Draw QrCode to DrawingBrush
        /// </summary>
        /// <returns>DrawingBrush, Stretch = uniform</returns>
        /// <remarks>LightBrush will not use by this method, DrawingBrush will only contain DarkBrush part.
        /// Use LightBrush to fill background of main uielement for more flexible placement</remarks>
        public DrawingBrush DrawBrush(BitMatrix QrMatrix)
        {
            if (QrMatrix == null)
            {
                return ConstructDrawingBrush(null);
            }

            GeometryDrawing qrCodeDrawing = ConstructQrDrawing(QrMatrix, 0, 0);

            return ConstructDrawingBrush(qrCodeDrawing);
        }
 public void testSetRegion()
 {
    BitMatrix matrix = new BitMatrix(5);
    matrix.setRegion(1, 1, 3, 3);
    for (int y = 0; y < 5; y++)
    {
       for (int x = 0; x < 5; x++)
       {
          Assert.AreEqual(y >= 1 && y <= 3 && x >= 1 && x <= 3, matrix[x, y]);
       }
    }
 }
Exemple #17
0
		public void PerformanceTest(int rules, ByteMatrix bMatrix, BitMatrix bitMatrix)
		{
			Stopwatch sw = new Stopwatch();
			int timesofTest = 1000;
			
			Penalty penalty = new PenaltyFactory().CreateByRule((PenaltyRules)rules);
			
			
			string[] timeElapsed = new string[2];
			
			sw.Start();
			
			for(int i = 0; i < timesofTest; i++)
			{
				penalty.PenaltyCalculate(bitMatrix);
			}
			
			sw.Stop();
			
			timeElapsed[0] = sw.ElapsedMilliseconds.ToString();
			
			sw.Reset();
			
			sw.Start();
			
			for(int i = 0; i < timesofTest; i++)
			{
				switch(rules)
				{
					case 1:
						MaskUtil.applyMaskPenaltyRule1(bMatrix);
						break;
					case 2:
						MaskUtil.applyMaskPenaltyRule2(bMatrix);
						break;
					case 3:
						MaskUtil.applyMaskPenaltyRule3(bMatrix);
						break;
					case 4:
						MaskUtil.applyMaskPenaltyRule4(bMatrix);
						break;
					default:
						throw new InvalidOperationException(string.Format("Unsupport Rules {0}", rules.ToString()));
				}
			}
			sw.Stop();
			
			timeElapsed[1] = sw.ElapsedMilliseconds.ToString();
			
			
			Assert.Pass("Terminator performance {0} Tests~ QrCode.Net: {1} ZXing: {2}", timesofTest, timeElapsed[0], timeElapsed[1]);
			
		}
        /// <summary>
        /// Draw QrCode at given writeable bitmap at offset location
        /// </summary>
        public void Draw(WriteableBitmap wBitmap, BitMatrix matrix, int offsetX, int offsetY)
        {
            DrawingSize size = matrix == null ? ISize.GetSize(21) : ISize.GetSize(matrix.Width);
            if (wBitmap == null)
                wBitmap = new WriteableBitmap(size.CodeWidth + offsetX, size.CodeWidth + offsetY, 96, 96, PixelFormats.Gray8, null);
            else if (wBitmap.PixelHeight == 0 || wBitmap.PixelWidth == 0)
                return; //writeablebitmap contains no pixel.
            this.DrawQuietZone(wBitmap, size.CodeWidth, offsetX, offsetY);
            if (matrix == null)
                return;

            this.DrawDarkModule(wBitmap, matrix, offsetX, offsetY);
        }
      /// <summary>
      /// Creates a WhiteRectangleDetector instance
      /// </summary>
      /// <param name="image">The image.</param>
      /// <returns>null, if image is too small, otherwise a WhiteRectangleDetector instance</returns>
      public static WhiteRectangleDetector Create(BitMatrix image)
      {
         if (image == null)
            return null;

         var instance = new WhiteRectangleDetector(image);

         if (instance.upInit < 0 || instance.leftInit < 0 || instance.downInit >= instance.height || instance.rightInit >= instance.width)
         {
            return null;
         }

         return instance;
      }
Exemple #20
0
 /// <summary>
 /// Penalties the calculation.
 /// </summary>
 /// <param name="matrix">The matrix.</param>
 /// <param name="isHorizontal">if set to <c>true</c> [is horizontal].</param>
 /// <returns></returns>
 /// <remarks></remarks>
 private int PenaltyCalculation(BitMatrix matrix, bool isHorizontal)
 {
     int i = 0;
     int j = 1;
     int penalty = 0;
     int width = matrix.Width;
     bool bit;
     while (i < width)
     {
         while (j < width - 5)
         {
             bit = isHorizontal
                       ? matrix[j + 4, i]
                       : matrix[i, j + 4];
             if (!bit)
             {
                 bit = isHorizontal
                           ? matrix[j, i]
                           : matrix[i, j];
                 if (!bit)
                 {
                     penalty += PatternCheck(matrix, i, j, isHorizontal);
                     j += 4;
                 }
                 else
                     j += 4;
             }
             else
             {
                 for (int num = 4; num > 0; num--)
                 {
                     bit = bit = isHorizontal
                                     ? matrix[j + num, i]
                                     : matrix[i, j + num];
                     if (!bit)
                     {
                         j += num;
                         break;
                     }
                     if (num == 1)
                         j += 5;
                 }
             }
         }
         j = 0;
         i++;
     }
     return penalty;
 }
Exemple #21
0
        /// <summary>
        /// Drawing Bitmatrix to winform graphics.
        /// </summary>
        /// <param name="QrMatrix">Draw background only for null matrix</param>
        /// <exception cref="ArgumentNullException">DarkBrush or LightBrush is null</exception>
        public void Draw(Graphics graphics, BitMatrix QrMatrix, Point offset)
        {
            int width = QrMatrix == null ? 21 : QrMatrix.Width;

            DrawingSize size = m_iSize.GetSize(width);

            graphics.FillRectangle(m_LightBrush, offset.X, offset.Y, size.CodeWidth, size.CodeWidth);

            if(QrMatrix == null || size.ModuleSize == 0)
                return;

            int padding = (size.CodeWidth - (size.ModuleSize * width)) / 2;

            int preX = -1;

            for (int y = 0; y < width; y++)
            {
                for (int x = 0; x < width; x++)
                {
                    if (QrMatrix[x, y])
                    {
                        //Set start point if preX == -1
                        if (preX == -1)
                            preX = x;
                        //If this is last module in that row. Draw rectangle
                        if (x == width - 1)
                        {
                            Point modulePosition = new Point(preX * size.ModuleSize + padding + offset.X,
                                y * size.ModuleSize + padding + offset.Y);
                            Size rectSize = new Size((x - preX + 1) * size.ModuleSize, size.ModuleSize);
                            graphics.FillRectangle(m_DarkBrush, modulePosition.X, modulePosition.Y, rectSize.Width, rectSize.Height);
                            preX = -1;
                        }
                    }
                    else if (!QrMatrix[x, y] && preX != -1)
                    {
                        //Here will be first light module after sequence of dark module.
                        //Draw previews sequence of dark Module
                        Point modulePosition = new Point(preX * size.ModuleSize + padding + offset.X,
                            y * size.ModuleSize + padding + offset.Y);
                        Size rectSize = new Size((x - preX) * size.ModuleSize, size.ModuleSize);
                        graphics.FillRectangle(m_DarkBrush, modulePosition.X, modulePosition.Y, rectSize.Width, rectSize.Height);
                        preX = -1;
                    }
                }
            }

        }
		public override BitMatrix sampleGrid(BitMatrix image, int dimension, PerspectiveTransform transform)
		{
			BitMatrix bits = new BitMatrix(dimension);
			float[] points = new float[dimension << 1];
			for (int y = 0; y < dimension; y++)
			{
				int max = points.Length;
				//UPGRADE_WARNING: Data types in Visual C# might be different.  Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
				float iValue = (float) y + 0.5f;
				for (int x = 0; x < max; x += 2)
				{
					//UPGRADE_WARNING: Data types in Visual C# might be different.  Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
					points[x] = (float) (x >> 1) + 0.5f;
					points[x + 1] = iValue;
				}
				transform.transformPoints(points);
				// Quick check to see if points transformed to something inside the image;
				// sufficient to check the endpoints
				checkAndNudgePoints(image, points);
				try
				{
					for (int x = 0; x < max; x += 2)
					{
						//UPGRADE_WARNING: Data types in Visual C# might be different.  Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
						if (image.get_Renamed((int) points[x], (int) points[x + 1]))
						{
							// Black(-ish) pixel
							bits.set_Renamed(x >> 1, y);
						}
					}
				}
				catch (System.IndexOutOfRangeException)
				{
					// This feels wrong, but, sometimes if the finder patterns are misidentified, the resulting
					// transform gets "twisted" such that it maps a straight line of points to a set of points
					// whose endpoints are in bounds, but others are not. There is probably some mathematical
					// way to detect this about the transformation that I don't know yet.
					// This results in an ugly runtime exception despite our clever checks above -- can't have
					// that. We could check each point's coordinates but that feels duplicative. We settle for
					// catching and wrapping ArrayIndexOutOfBoundsException.
					throw ReaderException.Instance;
				}
			}
			return bits;
		}
        /// <summary>
        /// Construct QrCode geometry. It will only include geometry for Dark colour module
        /// </summary>
        /// <returns>QrCode dark colour module geometry. Size = QrMatrix width x width</returns>
        public StreamGeometry DrawGeometry(BitMatrix QrMatrix, int offsetX, int offSetY)
        {
            int width = QrMatrix == null ? 21 : QrMatrix.Width;

            StreamGeometry qrCodeStream = new StreamGeometry();
            qrCodeStream.FillRule = FillRule.EvenOdd;

            if (QrMatrix == null)
                return qrCodeStream;

            using (StreamGeometryContext qrCodeCtx = qrCodeStream.Open())
            {
                int preX = -1;

                for (int y = 0; y < width; y++)
                {
                    for (int x = 0; x < width; x++)
                    {
                        if (QrMatrix[x, y])
                        {
                            //Set start point if preX == -1
                            if (preX == -1)
                                preX = x;
                            //If this is last module in that row. Draw rectangle
                            if (x == width - 1)
                            {
                                qrCodeCtx.DrawRectGeometry(new Int32Rect(preX + offsetX, y + offSetY, x - preX + 1, 1));
                                preX = -1;
                            }
                        }
                        else if (!QrMatrix[x, y] && preX != -1)
                        {
                            //Here will be first light module after sequence of dark module.
                            //Draw previews sequence of dark Module
                            qrCodeCtx.DrawRectGeometry(new Int32Rect(preX + offsetX, y + offSetY, x - preX, 1));
                            preX = -1;
                        }
                    }
                }
            }
            qrCodeStream.Freeze();

            return qrCodeStream;
        }
Exemple #24
0
        internal override int PenaltyCalculate(BitMatrix matrix)
        {
            int width = matrix.Width;
            bool topR = false;

            int x = 0;
            int y = 0;
            int penalty = 0;

            while( y < (width - 1))
            {
                while( x < (width - 1))
                {
                    topR = matrix[x + 1, y];

                    if(topR == matrix[x + 1, y + 1])	//Bottom Right
                    {
                        if(topR == matrix[x, y + 1])	//Bottom Left
                        {
                            if(topR == matrix[x, y])	//Top Left
                            {
                                penalty += 3;
                                x += 1;
                            }
                            else
                                x += 1;

                        }
                        else
                            x += 1;
                    }
                    else
                    {
                        x += 2;
                    }
                }

                x = 0;
                y ++;
            }
            return penalty;
        }
        public static void AssertEquals(this BitMatrix expected, BitMatrix actual)
        {
            if (expected == null) throw new ArgumentNullException("expected");
            if (actual == null) throw new ArgumentNullException("actual");

            if (expected.Width != actual.Width)
            {
                Assert.Fail("Mtrix must have same size. Expected {0}, Actual {1}", expected.Width, actual.Width);
            }

            
            for (int i = 0; i < expected.Width; i++)
                for (int j = 0; j < expected.Width; j++)
                {
                    if (expected[i, j] != actual[i, j])
                    {
                        Assert.Fail("Matrces are different.\nExpected:{0}Actual:{1}.", expected.ToGraphicString(), actual.ToGraphicString());
                    }
                }
        }
Exemple #26
0
        /// <summary>
        /// Calculate penalty value for Fourth rule.
        /// Perform O(n) search for available x modules
        /// </summary>
        internal override int PenaltyCalculate(BitMatrix matrix)
        {
            int width = matrix.Width;
            int DarkBitCount = 0;

            for(int j = 0; j < width; j++)
            {
                for(int i = 0; i < width; i++)
                {
                    if(matrix[i, j])
                        DarkBitCount++;
                }
            }

            int MatrixCount = width * width;

            double ratio = (double)DarkBitCount / MatrixCount;

            return System.Math.Abs((int)(ratio*100 -50)) / 5 * 10;
        }
        public static GeometryGroup DarkModuleGeometry(BitMatrix matrix)
        {
            GeometryCollection gCollection = new GeometryCollection();
            GeometryGroup gGroup = new GeometryGroup();
            if (matrix == null)
            {
                gGroup.Children = gCollection;
                return gGroup;
            }

            int preX = -1;
            int width = matrix.Width;
            for (int y = 0; y < width; y++)
            {
                for (int x = 0; x < width; x++)
                {
                    if (matrix[x, y])
                    {
                        //Set start point if preX == -1
                        if (preX == -1)
                            preX = x;
                        //If this is last module in that row. Draw rectangle
                        if (x == width - 1)
                        {
                            gCollection.Add(CreateRectGeometry(new Rect(preX, y, x - preX + 1, 1)));
                            preX = -1;
                        }
                    }
                    else if (!matrix[x, y] && preX != -1)
                    {
                        //Here will be first light module after sequence of dark module.
                        //Draw previews sequence of dark Module
                        gCollection.Add(CreateRectGeometry(new Rect(preX, y, x - preX, 1)));
                        preX = -1;
                    }
                }
            }

            gGroup.Children = gCollection;
            return gGroup;
        }
 public void testGetSet()
 {
    BitMatrix matrix = new BitMatrix(33);
    Assert.AreEqual(33, matrix.Height);
    for (int y = 0; y < 33; y++)
    {
       for (int x = 0; x < 33; x++)
       {
          if (y * x % 3 == 0)
          {
             matrix[x, y] = true;
          }
       }
    }
    for (int y = 0; y < 33; y++)
    {
       for (int x = 0; x < 33; x++)
       {
          Assert.AreEqual(y * x % 3 == 0, matrix[x, y]);
       }
    }
 }
Exemple #29
0
 public static void GenerateFaultyRecord(BitMatrix matrix, PenaltyRules penaltyRule, int expected, int actual)
 {
     string path = Path.Combine(Path.GetTempPath(), s_TxtFileName);
     
     if(!File.Exists(path))
     {
     	using (StreamWriter file = File.CreateText(path)) 
       	{
     		file.WriteLine();
     	}
     }
     
     using (var file = File.AppendText(path))
     {
     	file.Write(penaltyRule.ToString());
     	file.Write(string.Format(" Expected: {0}, Actual: {0}", expected.ToString(), actual.ToString()));
         matrix.ToGraphic(file);
         file.WriteLine("=====");
         file.Close();
         
     }
 }
        // Calculates the final BitMatrix once for all requests. This could be called once from the
        // constructor instead, but there are some advantages to doing it lazily, such as making
        // profiling easier, and not doing heavy lifting when callers don't expect it.
        private void binarizeEntireImage()
        {
            if (matrix == null)
            {
                LuminanceSource source = LuminanceSource;
                if (source.Width >= MINIMUM_DIMENSION && source.Height >= MINIMUM_DIMENSION)
                {
                    sbyte[] luminances = source.Matrix;
                    int width = source.Width;
                    int height = source.Height;
                    int subWidth = width >> 3;
                    int subHeight = height >> 3;
                    int[][] blackPoints = calculateBlackPoints(luminances, subWidth, subHeight, width);

                    matrix = new BitMatrix(width, height);
                    calculateThresholdForBlock(luminances, subWidth, subHeight, width, blackPoints, matrix);
                }
                else
                {
                    // If the image is too small, fall back to the global histogram approach.
                    matrix = base.BlackMatrix;
                }
            }
        }
 /// <summary>
 /// Calculate penalty value for Third rule.
 /// </summary>
 internal override int PenaltyCalculate(BitMatrix matrix)
 {
     return(PenaltyCalculation(matrix, true) + PenaltyCalculation(matrix, false));
 }
 /// <summary>
 /// renders the BitMatrix as MagickImage
 /// </summary>
 /// <param name="matrix"></param>
 /// <param name="format"></param>
 /// <param name="content"></param>
 /// <returns></returns>
 public IMagickImage <Byte> Render(BitMatrix matrix, BarcodeFormat format, String content)
 {
     return(Render(matrix, format, content, new EncodingOptions()));
 }
Exemple #33
0
        //UPGRADE_NOTE: Final was removed from the declaration of 'bits '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
        //UPGRADE_NOTE: Final was removed from the declaration of 'points '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"

        public DetectorResult(BitMatrix bits, ResultPoint[] points)
        {
            Bits   = bits;
            Points = points;
        }
 /// <summary>
 /// <p>Creates a finder that will search the image for three finder patterns.</p>
 /// </summary>
 /// <param name="image">image to search</param>
 public FinderPatternFinder(BitMatrix image)
     : this(image, null)
 {
 }
Exemple #35
0
        /// <summary>
        /// Renders the specified matrix.
        /// </summary>
        /// <param name="matrix">The matrix.</param>
        /// <param name="format">The format.</param>
        /// <param name="content">The content.</param>
        /// <param name="options">The options.</param>
        /// <returns></returns>
        virtual public Bitmap Render(BitMatrix matrix, BarcodeFormat format, string content, EncodingOptions options)
        {
            int  width         = matrix.Width;
            int  height        = matrix.Height;
            bool outputContent = (options == null || !options.PureBarcode) &&
                                 !String.IsNullOrEmpty(content) && (format == BarcodeFormat.CODE_39 ||
                                                                    format == BarcodeFormat.CODE_128 ||
                                                                    format == BarcodeFormat.EAN_13 ||
                                                                    format == BarcodeFormat.EAN_8 ||
                                                                    format == BarcodeFormat.CODABAR ||
                                                                    format == BarcodeFormat.ITF ||
                                                                    format == BarcodeFormat.UPC_A ||
                                                                    format == BarcodeFormat.MSI ||
                                                                    format == BarcodeFormat.PLESSEY);
            int emptyArea = outputContent ? 16 : 0;
            int pixelsize = 1;

            if (options != null)
            {
                if (options.Width > width)
                {
                    width = options.Width;
                }
                if (options.Height > height)
                {
                    height = options.Height;
                }
                // calculating the scaling factor
                pixelsize = width / matrix.Width;
                if (pixelsize > height / matrix.Height)
                {
                    pixelsize = height / matrix.Height;
                }
            }

            // create the bitmap and lock the bits because we need the stride
            // which is the width of the image and possible padding bytes
            var bmp     = new Bitmap(width, height, PixelFormat.Format24bppRgb);
            var bmpData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);

            try
            {
                var pixels  = new byte[bmpData.Stride * height];
                var padding = bmpData.Stride - (3 * width);
                var index   = 0;
                var color   = Background;

                for (int y = 0; y < matrix.Height - emptyArea; y++)
                {
                    for (var pixelsizeHeight = 0; pixelsizeHeight < pixelsize; pixelsizeHeight++)
                    {
                        for (var x = 0; x < matrix.Width; x++)
                        {
                            color = matrix[x, y] ? Foreground : Background;
                            for (var pixelsizeWidth = 0; pixelsizeWidth < pixelsize; pixelsizeWidth++)
                            {
                                pixels[index++] = color.B;
                                pixels[index++] = color.G;
                                pixels[index++] = color.R;
                            }
                        }
                        for (var x = pixelsize * matrix.Width; x < width; x++)
                        {
                            pixels[index++] = Background.B;
                            pixels[index++] = Background.G;
                            pixels[index++] = Background.R;
                        }
                        index += padding;
                    }
                }
                for (int y = matrix.Height * pixelsize - emptyArea; y < height; y++)
                {
                    for (var x = 0; x < width; x++)
                    {
                        pixels[index++] = Background.B;
                        pixels[index++] = Background.G;
                        pixels[index++] = Background.R;
                    }
                    index += padding;
                }

                //Copy the data from the byte array into BitmapData.Scan0
                Marshal.Copy(pixels, 0, bmpData.Scan0, pixels.Length);
            }
            finally
            {
                //Unlock the pixels
                bmp.UnlockBits(bmpData);
            }

            if (outputContent)
            {
                switch (format)
                {
                case BarcodeFormat.EAN_8:
                    if (content.Length < 8)
                    {
                        content = OneDimensionalCodeWriter.CalculateChecksumDigitModulo10(content);
                    }
                    content = content.Insert(4, "   ");
                    break;

                case BarcodeFormat.EAN_13:
                    if (content.Length < 13)
                    {
                        content = OneDimensionalCodeWriter.CalculateChecksumDigitModulo10(content);
                    }
                    content = content.Insert(7, "   ");
                    content = content.Insert(1, "   ");
                    break;
                }
                var font = TextFont ?? DefaultTextFont;
                using (var g = Graphics.FromImage(bmp))
                {
                    var drawFormat = new StringFormat {
                        Alignment = StringAlignment.Center
                    };
#if WindowsCE
                    g.DrawString(content, font, Black, width / 2, height - 14, drawFormat);
#else
                    g.DrawString(content, font, Brushes.Black, width / 2, height - 14, drawFormat);
#endif
                }
            }

            return(bmp);
        }
        /// <summary>
        /// 生成二维码图片带ICON
        /// </summary>
        /// <param name="content"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <param name="icon"></param>
        /// <returns></returns>
        public static Texture2D EncodeToImage(string content, int width, int height, Texture2D icon)
        {
            Texture2D texture2D = null;
            BitMatrix bitMatrix = null;

            try
            {
                MultiFormatWriter multiFormatWriter       = new MultiFormatWriter();
                Dictionary <EncodeHintType, object> hints = new Dictionary <EncodeHintType, object>();
                hints.Add(EncodeHintType.CHARACTER_SET, "UTF-8");
                hints.Add(EncodeHintType.MARGIN, 1);
                hints.Add(EncodeHintType.ERROR_CORRECTION, ZXing.QrCode.Internal.ErrorCorrectionLevel.H);
                bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hints);
            }
            catch (Exception e)
            {
                Debuger.LogError("生成二维码图片失败 " + e.Message);
                return(null);
            }
            int w = bitMatrix.Width;
            int h = bitMatrix.Height;

            texture2D = new Texture2D(width, height);
            for (int i = 0; i < h; i++)
            {
                for (int j = 0; j < w; j++)
                {
                    int px = i;
                    int py = j;
                    if (bitMatrix[i, j])
                    {
                        texture2D.SetPixel(px, py, Color.black);
                    }
                    else
                    {
                        texture2D.SetPixel(px, py, Color.white);
                    }
                }
            }
            // add icon
            int halfWidth        = texture2D.width / 2;
            int halfHeight       = texture2D.height / 2;
            int halfWidthOfIcon  = icon.width / 2;
            int halfHeightOfIcon = icon.height / 2;

            for (int x = 0; x < h; x++)
            {
                for (int y = 0; y < w; y++)
                {
                    var centerOffsetX = x - halfWidth;
                    var centerOffsetY = y - halfHeight;
                    if (Mathf.Abs(centerOffsetX) <= halfWidthOfIcon && Mathf.Abs(centerOffsetY) <= halfHeightOfIcon)
                    {
                        texture2D.SetPixel(x, y, icon.GetPixel(centerOffsetX + halfWidthOfIcon, centerOffsetY + halfHeightOfIcon));
                    }
                }
            }

            texture2D.Apply();
            return(texture2D);
        }
Exemple #37
0
        private int PenaltyCalculation(BitMatrix matrix, bool isHorizontal)
        {
            int penalty        = 0;
            int numSameBitCell = 0;

            int width = matrix.Width;

            int i = 0;
            int j = 0;

            while (i < width)
            {
                while (j < width - 4)
                {
                    bool preBit = isHorizontal ? matrix[j + 4, i]
                                                : matrix[i, j + 4];
                    numSameBitCell = 1;

                    for (int x = 1; x <= 4; x++)
                    {
                        bool bit = isHorizontal ? matrix[j + 4 - x, i]
                                                        : matrix[i, j + 4 - x];
                        if (bit == preBit)
                        {
                            numSameBitCell++;
                        }
                        else
                        {
                            break;
                        }
                    }

                    if (numSameBitCell == 1)
                    {
                        j += 4;
                    }
                    else
                    {
                        int x = 5;
                        while ((j + x) < width)
                        {
                            bool bit = isHorizontal ? matrix[j + x, i]
                                                                : matrix[i, j + x];
                            if (bit == preBit)
                            {
                                numSameBitCell++;
                            }
                            else
                            {
                                break;
                            }
                            x++;
                        }
                        if (numSameBitCell >= 5)
                        {
                            penalty += (3 + (numSameBitCell - 5));
                        }

                        j += x;
                    }
                }
                j = 0;
                i++;
            }

            return(penalty);
        }
 protected override void Initialise(BitMatrix originals)
 {
     base.Initialise(originals);
     _currentDisplay = CurrentDisplay.Blank;
 }