public void Luminance_Is_Within_Margin_Of_Error(string fileName)
        {
            byte[] controlLuminanceSourceMatrix;
            using (var control = LoadBitmapImage(fileName))
            {
                var bitmapLuminanceSource = new BitmapLuminanceSource(control);
                controlLuminanceSourceMatrix = bitmapLuminanceSource.Matrix;
            }

            byte[] testLuminanceSourceMatrix;
            using (var bitmap = LoadImageSharpBitmap(fileName))
            {
                var imagesharpBitmapLuminanceSource = new ImageSharpLuminanceSource <SelectedPixelFormat>(bitmap);
                testLuminanceSourceMatrix = imagesharpBitmapLuminanceSource.Matrix;
            }

            Assert.AreEqual(controlLuminanceSourceMatrix.Length, testLuminanceSourceMatrix.Length);

            for (int index = 0; index < controlLuminanceSourceMatrix.Length; index++)
            {
                var controlColor = controlLuminanceSourceMatrix[index];
                var testColor    = testLuminanceSourceMatrix[index];

                Assert.That(testColor, Is.EqualTo(controlColor).Within(3));
            }
        }
Esempio n. 2
0
        private bool ScanQRCodeStretch(Screen screen, Bitmap fullImage, Rectangle cropRect, double mul, out string url, out Rectangle rect)
        {
            Bitmap target = new Bitmap((int)(cropRect.Width * mul), (int)(cropRect.Height * mul));

            using (Graphics g = Graphics.FromImage(target))
            {
                g.DrawImage(fullImage, new Rectangle(0, 0, target.Width, target.Height),
                            cropRect,
                            GraphicsUnit.Pixel);
            }
            var          source = new BitmapLuminanceSource(target);
            var          bitmap = new BinaryBitmap(new HybridBinarizer(source));
            QRCodeReader reader = new QRCodeReader();
            var          result = reader.decode(bitmap);

            if (result != null)
            {
                url = result.Text;
                double minX = Int32.MaxValue, minY = Int32.MaxValue, maxX = 0, maxY = 0;
                foreach (ResultPoint point in result.ResultPoints)
                {
                    minX = Math.Min(minX, point.X);
                    minY = Math.Min(minY, point.Y);
                    maxX = Math.Max(maxX, point.X);
                    maxY = Math.Max(maxY, point.Y);
                }
                //rect = new Rectangle((int)minX, (int)minY, (int)(maxX - minX), (int)(maxY - minY));
                rect = new Rectangle(cropRect.Left + (int)(minX / mul), cropRect.Top + (int)(minY / mul), (int)((maxX - minX) / mul), (int)((maxY - minY) / mul));
                return(true);
            }
            url  = "";
            rect = new Rectangle();
            return(false);
        }
Esempio n. 3
0
 private void Scan(object sender, EventArgs e)
 {
     using (System.IO.Stream stream = webRes.GetResponseStream())
     {
         Bitmap            img    = new Bitmap(Image.FromStream(stream));
         MultiFormatReader reader = new MultiFormatReader();
         ZXing.Multi.GenericMultipleBarcodeReader barcodeReader = new ZXing.Multi.GenericMultipleBarcodeReader(reader);
         if (img != null)
         {
             pictureBox1.Image = img;
             LuminanceSource source       = new BitmapLuminanceSource(img);
             BinaryBitmap    binaryBitmap = new BinaryBitmap(new ZXing.Common.HybridBinarizer(source));
             Result[]        results      = barcodeReader.decodeMultiple(binaryBitmap);
             if (results != null)
             {
                 timer.Stop();
                 foreach (Result result in results)
                 {
                     //firstly upload img.
                     //Because that server communication with algorithm after getting projectInfo
                     //sync not async
                     UploadProImg(img);                             //upload project img
                     Thread.Sleep(500);                             //process wait 500, socket sync is stupid
                     string identifyResult = UploadProInfo(result); //prase project info and upload
                     MessageBox.Show(identifyResult);
                 }
             }
         }
     }
 }
Esempio n. 4
0
        internal static BinaryBitmap getBinaryBitmap(String path)
        {
            var bufferedImage   = getBufferedImage(path);
            var luminanceSource = new BitmapLuminanceSource(bufferedImage);

            return(new BinaryBitmap(new GlobalHistogramBinarizer(luminanceSource)));
        }
Esempio n. 5
0
        static void barcode_decode(string path)
        {
            ImageConverter converter = new ImageConverter();

            var reader = new ZXing.QrCode.QRCodeReader();
            //ZXing.BinaryBitmap
            var dest = (Bitmap)Bitmap.FromFile(path);
            var bb   = (byte[])converter.ConvertTo(dest, typeof(byte[]));
            // ;
            // BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
            var source = new BitmapLuminanceSource(dest);
            // LuminanceSource source = new RGBLuminanceSource(bb,dest.Width,dest.Height, RGBLuminanceSource.BitmapFormat.RGB32);
            HybridBinarizer binarizer = new HybridBinarizer(source);
            BinaryBitmap    binBitmap = new BinaryBitmap(binarizer);
            QRCodeReader    qrr       = new QRCodeReader();
            var             result    = qrr.decode(binBitmap);

            if (result != null)
            {
                var text = result.Text;
                Console.WriteLine(text);
            }
            else
            {
                Console.WriteLine("Err");
            }
        }
Esempio n. 6
0
        /// <summary>
        /// 使用二维码匹配SS服务器信息
        /// </summary>
        /// <param name="url">二维码地址</param>
        /// <returns>结果的Server对象</returns>
        protected Server getFreeServerByQrCode(string url)
        {
            Server serv = null;

            HttpGet(url, Convert.ToString(Environment.TickCount), (responseStream) =>
            {
                using (Bitmap target = new Bitmap(responseStream))
                {
                    var source          = new BitmapLuminanceSource(target);
                    var bitmap          = new BinaryBitmap(new HybridBinarizer(source));
                    QRCodeReader reader = new QRCodeReader();
                    var result          = reader.decode(bitmap);

                    if (result != null)
                    {
                        serv = new Server(result.Text);
                    }
                    else
                    {
                        Logging.Error("Decode QR Code Err");
                    }
                }
            });
            return(serv);
        }
Esempio n. 7
0
        /// <summary>
        /// »ñÈ¡¶þάÂë×Ö·û´®
        /// </summary>
        /// <returns></returns>
        public string GetQRCodeString()
        {
            Bitmap bmap = GetClipboardBitmap();

            if (bmap == null)
            {
                return(null);
            }
            QRCodeReader          qrRead    = new QRCodeReader();
            BitmapLuminanceSource source    = new BitmapLuminanceSource(bmap);
            BinaryBitmap          binBitmap = new BinaryBitmap(new HybridBinarizer(source));

            string retString = null;

            try
            {
                Result results = qrRead.decode(binBitmap);
                if (results != null)
                {
                    retString = DeEncryString(results.Text);
                }
            }
            catch (Exception ex)
            {
                return(null);
            }

            return(retString);
        }
Esempio n. 8
0
        public static string ScanQRCodeFromScreen()
        {
            var screenLeft   = SystemParameters.VirtualScreenLeft;
            var screenTop    = SystemParameters.VirtualScreenTop;
            var screenWidth  = SystemParameters.VirtualScreenWidth;
            var screenHeight = SystemParameters.VirtualScreenHeight;

            using (Bitmap bmp = new Bitmap((int)screenWidth, (int)screenHeight))
            {
                using (Graphics g = Graphics.FromImage(bmp))
                    g.CopyFromScreen((int)screenLeft, (int)screenTop, 0, 0, bmp.Size);
                int maxTry = 10;
                for (int i = 0; i < maxTry; i++)
                {
                    int       marginLeft = (int)((double)bmp.Width * i / 2.5 / maxTry);
                    int       marginTop  = (int)((double)bmp.Height * i / 2.5 / maxTry);
                    Rectangle cropRect   = new Rectangle(marginLeft, marginTop, bmp.Width - marginLeft * 2, bmp.Height - marginTop * 2);
                    Bitmap    target     = new Bitmap((int)screenWidth, (int)screenHeight);

                    double imageScale = screenWidth / cropRect.Width;
                    using (Graphics g = Graphics.FromImage(target))
                        g.DrawImage(bmp, new Rectangle(0, 0, target.Width, target.Height), cropRect, GraphicsUnit.Pixel);
                    var          source = new BitmapLuminanceSource(target);
                    var          bitmap = new BinaryBitmap(new HybridBinarizer(source));
                    QRCodeReader reader = new QRCodeReader();
                    var          result = reader.decode(bitmap);
                    if (result != null)
                    {
                        return(result.Text);
                    }
                }
            }
            return("");
        }
Esempio n. 9
0
        private void addServerQRCode(object parameter)
        {
            Bitmap bitmapScreen = new Bitmap((int)SystemParameters.PrimaryScreenWidth, (int)SystemParameters.PrimaryScreenHeight, PixelFormat.Format32bppArgb);

            using (Graphics graphics = Graphics.FromImage(bitmapScreen))
            {
                graphics.CopyFromScreen(0, 0, 0, 0, bitmapScreen.Size, CopyPixelOperation.SourceCopy);
            }

            var sourceScreen = new BitmapLuminanceSource(bitmapScreen);
            var bitmap       = new BinaryBitmap(new HybridBinarizer(sourceScreen));

            QRCodeReader reader = new QRCodeReader();
            var          result = reader.decode(bitmap);

            if (result == null || string.IsNullOrWhiteSpace(result.Text))
            {
                App.ShowNotify(sr_config_0_found);
                return;
            }

            List <ServerProfile> serverList = ServerManager.ImportServers(result.Text);

            if (serverList.Count > 0)
            {
                int added = addServer(serverList);
                App.ShowNotify($"{added} {sr_config_x_imported}");
            }
            else
            {
                App.ShowNotify(sr_config_0_imported);
            }
        }
        public static Result ReadQRCode(IntPtr windowHandle)
        {
            NativeMethods.RectStruct rect;
            NativeMethods.GetWindowRect(windowHandle, out rect);
            int width  = rect.Right - rect.Left;
            int height = rect.Bottom - rect.Top;

            using (Bitmap bitmap = new Bitmap(width, height))
            {
                using (Graphics g = Graphics.FromImage(bitmap))
                {
                    int x = rect.Left;
                    int y = rect.Top;
                    g.CopyFromScreen(new Point(x, y), Point.Empty, new Size(width, height));
                }
                LuminanceSource source = new BitmapLuminanceSource(bitmap);
                var             reader = new BarcodeReader();
                reader.AutoRotate = true;
                reader.Options.PossibleFormats = new List <BarcodeFormat> {
                    BarcodeFormat.QR_CODE
                };
                reader.Options.Hints.Add(DecodeHintType.TRY_HARDER, true);
                return(reader.Decode(source));
            }
        }
Esempio n. 11
0
        public Result DecodeBitmap(Bitmap image)
        {
            var          source = new BitmapLuminanceSource(image);
            BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));

            return(decode(bitmap));
        }
Esempio n. 12
0
        private static Rectangle FindBarcodeRectangle(Bitmap bitmap, ResultPoint[] resultPoints)
        {
            var   startX = resultPoints[0].X;
            float startY;

            var   width = resultPoints[1].X - resultPoints[0].X;
            float height;


            var luminanceSource        = new BitmapLuminanceSource(bitmap);
            var binarizer              = new HybridBinarizer(luminanceSource);
            var bitMatrix              = binarizer.BlackMatrix;
            var whiteRectangleDetector = WhiteRectangleDetector.Create(bitMatrix);
            var whiteRectanblePoints   = whiteRectangleDetector.detect();

            if (whiteRectanblePoints != null)
            {
                height = whiteRectanblePoints[3].Y - whiteRectanblePoints[0].Y;
                startY = whiteRectanblePoints[0].Y;
            }
            else
            {
                height = 1;
                startY = resultPoints[0].Y;
            }

            var barcodeRectangle = new Rectangle((int)startX, (int)startY, (int)width, (int)height);

            return(barcodeRectangle);
        }
        static void ZXing_Test_Single(string file, ZXing.Multi.GenericMultipleBarcodeReader multiBarcodeReader)
        {
            Bitmap          bitmap = (Bitmap)Image.FromFile(file);
            LuminanceSource source = new BitmapLuminanceSource(bitmap);

            ZXing.BinaryBitmap bBitmap = new ZXing.BinaryBitmap(new HybridBinarizer(source));
            Stopwatch          swZXing = Stopwatch.StartNew();

            ZXing.Result[] zResults = multiBarcodeReader.decodeMultiple(bBitmap);
            swZXing.Stop();

            if (zResults != null)
            {
                //Console.WriteLine("ZXing\t time: " + swZXing.Elapsed.TotalMilliseconds + "ms" + ",\t result count: " + zResults.Length);
                Console.WriteLine("{0, -10}{1, -20}{2, -20}", "ZXing", "time: " + swZXing.Elapsed.TotalMilliseconds + "ms", " result count: " + zResults.Length);
            }
            else
            {
                //Console.WriteLine("ZXing\t time: " + swZXing.Elapsed.TotalMilliseconds + "ms" + ",\t result count: failed");
                Console.WriteLine("{0, -10}{1, -20}{2, -20}", "ZXing", "time: " + swZXing.Elapsed.TotalMilliseconds + "ms", " result count: failed");
            }

            if (zResults != null)
            {
                //foreach (ZXing.Result zResult in zResults)
                //{
                //    Console.WriteLine("ZXing result: " + zResult.Text);
                //}
            }
        }
Esempio n. 14
0
        public IActionResult Post(IFormFile file)
        {
            Response.StatusCode = 200;

            if (file == null)
            {
                return(Content(""));
            }

            // create a barcode reader instance
            IBarcodeReader reader = new ZXing.CoreCompat.System.Drawing.BarcodeReader()
            {
                AutoRotate = true,
                Options    = new ZXing.Common.DecodingOptions()
                {
                    TryHarder       = true,
                    PossibleFormats = new List <BarcodeFormat>()
                    {
                        BarcodeFormat.All_1D
                    }
                }
            };

            // load a bitmap
            Bitmap bitmap = (Bitmap)Image.FromStream(file.OpenReadStream());
            BitmapLuminanceSource image = new BitmapLuminanceSource(bitmap);

            // detect and decode the barcode inside the bitmap
            Result result = reader.Decode(image);

            return(Content(result?.Text));
        }
Esempio n. 15
0
        public Result Decode(string path)
        {
            Bitmap image;

            try
            {
                image = (Bitmap)Image.FromFile(path);
            }
            catch (Exception)
            {
                throw new FileNotFoundException("Resource not found: " + path);
            }

            using (image)
            {
                LuminanceSource source;
                source = new BitmapLuminanceSource(image);
                BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
                Result       result = new MultiFormatReader().decode(bitmap);
                if (result == null)
                {
                    throw new Exception("Unable to decode QR code.");
                }
                return(result);
            }
        }
        private bool checkForFalsePositives(WriteableBitmap image, float rotationInDegrees)
#endif
        {
            var rotatedImage = rotateImage(image, rotationInDegrees);
            var source       = new BitmapLuminanceSource(rotatedImage);
            var bitmap       = new BinaryBitmap(new HybridBinarizer(source));
            var result       = getReader().decode(bitmap);

            if (result != null)
            {
                Log.InfoFormat("Found false positive: '{0}' with format '{1}' (rotation: {2})",
                               result.Text, result.BarcodeFormat, (int)rotationInDegrees);
                return(false);
            }

            // Try "try harder" getMode
            var hints = new Dictionary <DecodeHintType, Object>();

            hints[DecodeHintType.TRY_HARDER] = true;
            result = getReader().decode(bitmap, hints);
            if (result != null)
            {
                Log.InfoFormat("Try harder found false positive: '{0}' with format '{1}' (rotation: {2})",
                               result.Text, result.BarcodeFormat, (int)rotationInDegrees);
                return(false);
            }
            return(true);
        }
        public static string GetQRCode(Bitmap imageToSearch)
        {
            //IL_000f: Unknown result type (might be due to invalid IL or missing references)
            //IL_0015: Expected O, but got Unknown
            //IL_0016: Unknown result type (might be due to invalid IL or missing references)
            //IL_001d: Expected O, but got Unknown
            //IL_001f: Unknown result type (might be due to invalid IL or missing references)
            //IL_0029: Expected O, but got Unknown
            //IL_0024: Unknown result type (might be due to invalid IL or missing references)
            //IL_002b: Expected O, but got Unknown
            //IL_0048: Unknown result type (might be due to invalid IL or missing references)
            //IL_004f: Expected O, but got Unknown
            if (false)
            {
                Dictionary <DecodeHintType, object> dictionary = new Dictionary <DecodeHintType, object>();
                QRCodeReader          val  = new QRCodeReader();
                BitmapLuminanceSource val2 = new BitmapLuminanceSource(imageToSearch);
                BinaryBitmap          val3 = new BinaryBitmap(new HybridBinarizer(val2));
                Result val4 = val.decode(val3);
                return((val4 != null) ? val4.Text : null);
            }
            QRDecoder val5 = new QRDecoder();

            byte[][] array = val5.ImageDecoder(imageToSearch);
            if (array == null)
            {
                return(null);
            }
            if (array.GetLength(0) > 0)
            {
                return(Encoding.UTF8.GetString(array[0]));
            }
            return(null);
        }
        public void testMultiQRCodes()
        {
            var path   = buildTestBase("test/data/blackbox/multi-qrcode-1");
            var source = new BitmapLuminanceSource((Bitmap)Bitmap.FromFile(Path.Combine(path, "1.png")));
            var bitmap = new BinaryBitmap(new HybridBinarizer(source));

            var reader  = new QRCodeMultiReader();
            var results = reader.decodeMultiple(bitmap);

            Assert.IsNotNull(results);
            Assert.AreEqual(4, results.Length);

            var barcodeContents = new HashSet <String>();

            foreach (Result result in results)
            {
                barcodeContents.Add(result.Text);
                Assert.AreEqual(BarcodeFormat.QR_CODE, result.BarcodeFormat);
                var metadata = result.ResultMetadata;
                Assert.IsNotNull(metadata);
            }

            var expectedContents = new HashSet <String>
            {
                "You earned the class a 5 MINUTE DANCE PARTY!!  Awesome!  Way to go!  Let's boogie!",
                "You earned the class 5 EXTRA MINUTES OF RECESS!!  Fabulous!!  Way to go!!",
                "You get to SIT AT MRS. SIGMON'S DESK FOR A DAY!!  Awesome!!  Way to go!! Guess I better clean up! :)",
                "You get to CREATE OUR JOURNAL PROMPT FOR THE DAY!  Yay!  Way to go!  "
            };

            foreach (var expected in expectedContents)
            {
                Assert.That(barcodeContents.Contains(expected), Is.True);
            }
        }
Esempio n. 19
0
        private Result decode(Uri uri, IDictionary <DecodeHintType, object> hints)
        {
            Bitmap image;

            try
            {
                image = (Bitmap)Bitmap.FromFile(uri.LocalPath);
            }
            catch (Exception)
            {
                throw new FileNotFoundException("Resource not found: " + uri);
            }

            LuminanceSource source;

            if (config.Crop == null)
            {
                source = new BitmapLuminanceSource(image);
            }
            else
            {
                int[] crop = config.Crop;
                source = new BitmapLuminanceSource(image).crop(crop[0], crop[1], crop[2], crop[3]);
            }
            BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));

            if (config.DumpBlackPoint)
            {
                dumpBlackPoint(uri, image, bitmap);
            }
            Result result = new MultiFormatReader().decode(bitmap, hints);

            if (result != null)
            {
                if (config.Brief)
                {
                    Console.Out.WriteLine(uri + ": Success");
                }
                else
                {
                    ParsedResult parsedResult = ResultParser.parseResult(result);
                    Console.Out.WriteLine(uri + " (format: " + result.BarcodeFormat + ", type: " +
                                          parsedResult.Type + "):\nRaw result:\n" + result.Text + "\nParsed result:\n" +
                                          parsedResult.DisplayResult);

                    Console.Out.WriteLine("Found " + result.ResultPoints.Length + " result points.");
                    for (int i = 0; i < result.ResultPoints.Length; i++)
                    {
                        ResultPoint rp = result.ResultPoints[i];
                        Console.Out.WriteLine("  Point " + i + ": (" + rp.X + ',' + rp.Y + ')');
                    }
                }
            }
            else
            {
                Console.Out.WriteLine(uri + ": No barcode found");
            }
            return(result);
        }
Esempio n. 20
0
        public Result DecodeFromImagePath(string path)
        {
            var          image  = (Bitmap)Image.FromFile(path);
            var          source = new BitmapLuminanceSource(image);
            BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));

            return(decode(bitmap));
        }
        public static Result ScanBitmap(Bitmap target)
        {
            var source = new BitmapLuminanceSource(target);
            var bitmap = new BinaryBitmap(new HybridBinarizer(source));
            var reader = new QRCodeReader();

            return(reader.decode(bitmap));
        }
Esempio n. 22
0
 public void CheckUpdate(ShadowsocksController controller, bool use_proxy)
 {
     try
     {
         QRCodeNodeResult = false;
         Configuration config = controller.GetConfiguration();
         foreach (var item in config.nodeFeedQRCodeURLs)
         {
             bool   success    = false;
             byte[] qrCodeData = null;
             qrCodeData = DownloadData(config, item.url, use_proxy);
             //if (qrCodeData == null)
             //{
             //    qrCodeData = DownloadData(config, item.url, !use_proxy);
             //}
             if (qrCodeData != null)
             {
                 //读入MemoryStream对象
                 MemoryStream memoryStream = new MemoryStream(qrCodeData, 0, qrCodeData.Length);
                 memoryStream.Write(qrCodeData, 0, qrCodeData.Length);
                 //转成图片
                 Image        image  = Image.FromStream(memoryStream);
                 Bitmap       target = new Bitmap(image);
                 var          source = new BitmapLuminanceSource(target);
                 var          bitmap = new BinaryBitmap(new HybridBinarizer(source));
                 QRCodeReader reader = new QRCodeReader();
                 var          result = reader.decode(bitmap);
                 if (result != null)
                 {
                     success = AddServerBySSURL(ref config, result.Text, config.nodeFeedQRCodeGroup, true);
                 }
             }
             if (success)
             {
                 item.state = QRCodeUrlState.Normal;
             }
             else
             {
                 item.state = QRCodeUrlState.Exception;
             }
         }
         controller.SaveServersConfig(config);
         QRCodeNodeResult = true;
         if (NewQRCodeNodeFound != null)
         {
             NewQRCodeNodeFound(this, new EventArgs());
         }
     }
     catch (Exception ex)
     {
         Logging.Debug(ex.ToString());
         if (NewQRCodeNodeFound != null)
         {
             NewQRCodeNodeFound(this, new EventArgs());
         }
         return;
     }
 }
Esempio n. 23
0
        private Result decode(Uri uri, Bitmap image, string originalInput, IDictionary <DecodeHintType, object> hints)
        {
            LuminanceSource source;

            if (config.Crop == null)
            {
                source = new BitmapLuminanceSource(image);
            }
            else
            {
                int[] crop = config.Crop;
                source = new BitmapLuminanceSource(image).crop(crop[0], crop[1], crop[2], crop[3]);
            }
            if (config.DumpBlackPoint)
            {
                BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
                dumpBlackPoint(uri, image, bitmap, source);
            }
            var reader = new BarcodeReader {
                AutoRotate = config.AutoRotate
            };

            foreach (var entry in hints)
            {
                reader.Options.Hints.Add(entry.Key, entry.Value);
            }
            Result result = reader.Decode(source);

            if (result != null)
            {
                if (config.Brief)
                {
                    Console.Out.WriteLine(uri + ": Success");
                }
                else
                {
                    ParsedResult parsedResult = ResultParser.parseResult(result);
                    var          resultString = originalInput + " (format: " + result.BarcodeFormat + ", type: " + parsedResult.Type + "):" + Environment.NewLine;
                    for (int i = 0; i < result.ResultPoints.Length; i++)
                    {
                        ResultPoint rp = result.ResultPoints[i];
                        Console.Out.WriteLine("  Point " + i + ": (" + rp.X + ',' + rp.Y + ')');
                    }
                    resultString += "Raw result:" + Environment.NewLine + result.Text + Environment.NewLine;
                    resultString += "Parsed result:" + Environment.NewLine + parsedResult.DisplayResult + Environment.NewLine;

                    Console.Out.WriteLine(resultString);
                    ResultString = resultString;
                }
            }
            else
            {
                var resultString = originalInput + ": No barcode found";
                Console.Out.WriteLine(resultString);
                ResultString = resultString;
            }
            return(result);
        }
Esempio n. 24
0
        private void button2_Click(object sender, EventArgs e)
        {
            if (this.pictureBox1.Image == null)
            {
                return;
            }
            Image  img = this.pictureBox1.Image;
            Bitmap bmap;

            try
            {
                bmap = new Bitmap(img);
            }
            catch (System.IO.IOException ioe)
            {
                MessageBox.Show(ioe.ToString());
                return;
            }
            if (bmap == null)
            {
                MessageBox.Show("无法解析该图像!");
                return;
            }

            LuminanceSource source = new BitmapLuminanceSource(bmap);
            BinaryBitmap    bitmap = new BinaryBitmap(new HybridBinarizer(source));
            Result          result;

            try
            {
                result = new MultiFormatReader().decode(bitmap);
            }
            catch (ReaderException re)
            {
                MessageBox.Show("解码出现异常,可能不支持此编码!", "提示");
                //MessageBox.Show(re.ToString());
                return;
            }
            if (result == null)
            {
                //DmtxImageDecoder decoder = new DmtxImageDecoder();
                //var decodedData = decoder.DecodeImage(bmap, 1, new TimeSpan(0, 0, 3));
                //if (decodedData.Count != 1)
                //    throw new Exception("Encoding or decoding failed!");
                Console.WriteLine("解码失败");
            }
            else
            {
                string value = result.Text;
                if (result.BarcodeFormat == BarcodeFormat.PDF_417 || result.BarcodeFormat == BarcodeFormat.AZTEC)
                {
                    value = HttpUtility.UrlDecode(result.Text);
                }
                Console.WriteLine("decode result => format: " + result.BarcodeFormat + "   value: " + value);
            }
        }
Esempio n. 25
0
        private Result[] decodeMulti(Uri uri, string originalInput, IDictionary <DecodeHintType, object> hints)
        {
            Bitmap image;

            try
            {
                image = (Bitmap)Bitmap.FromFile(uri.LocalPath);
            }
            catch (Exception)
            {
                throw new FileNotFoundException("Resource not found: " + uri);
            }

            using (image)
            {
                LuminanceSource source;
                if (config.Crop == null)
                {
                    source = new BitmapLuminanceSource(image);
                }
                else
                {
                    int[] crop = config.Crop;
                    source = new BitmapLuminanceSource(image).crop(crop[0], crop[1], crop[2], crop[3]);
                }

                var reader = new BarcodeReader {
                    AutoRotate = config.AutoRotate, TryInverted = true
                };
                foreach (var entry in hints)
                {
                    reader.Options.Hints.Add(entry.Key, entry.Value);
                }
                Result[] results = reader.DecodeMultiple(source);
                if (results != null && results.Length > 0)
                {
                    foreach (var result in results)
                    {
                        var points = "";
                        for (int i = 0; i < result.ResultPoints.Length; i++)
                        {
                            if (i > 0)
                            {
                                points += ",";
                            }
                            ResultPoint rp = result.ResultPoints[i];
                            points += "{\"x\":" + rp.X + ",\"y\":" + rp.Y + "}";
                        }
                        var resultString = "{\"type\":\"" + result.BarcodeFormat + "\",\"data\":\"" + result.Text + "\",\"orientation\":" + result.ResultMetadata[ResultMetadataType.ORIENTATION] + ",\"points\":[" + points + "]}";
                        Console.Out.WriteLine(resultString);
                    }
                    return(results);
                }
                return(null);
            }
        }
Esempio n. 26
0
        private static EncryptedKeyStore BitmapToKeyStore(Bitmap image)
        {
            LuminanceSource source;

            source = new BitmapLuminanceSource(image);
            BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
            Result       result = new MultiFormatReader().decode(bitmap);

            return(result != null?JsonConvert.DeserializeObject <EncryptedKeyStore>(result.Text) : null);
        }
Esempio n. 27
0
        public static string ScanScreen()
        {
            try
            {
                foreach (Screen screen in Screen.AllScreens)
                {
                    using (Bitmap fullImage = new Bitmap(screen.Bounds.Width,
                                                         screen.Bounds.Height))
                    {
                        using (Graphics g = Graphics.FromImage(fullImage))
                        {
                            g.CopyFromScreen(screen.Bounds.X,
                                             screen.Bounds.Y,
                                             0, 0,
                                             fullImage.Size,
                                             CopyPixelOperation.SourceCopy);
                        }

                        int maxTry = 10;
                        for (int i = 0; i < maxTry; i++)
                        {
                            int       marginLeft = (int)((double)fullImage.Width * i / 2.5 / maxTry);
                            int       marginTop  = (int)((double)fullImage.Height * i / 2.5 / maxTry);
                            Rectangle cropRect   = new Rectangle(marginLeft, marginTop, fullImage.Width - marginLeft * 2,
                                                                 fullImage.Height - marginTop * 2);
                            Bitmap target = new Bitmap(screen.Bounds.Width, screen.Bounds.Height);

                            double imageScale = (double)screen.Bounds.Width / (double)cropRect.Width;
                            using (Graphics g = Graphics.FromImage(target))
                            {
                                g.DrawImage(fullImage, new Rectangle(0, 0, target.Width, target.Height),
                                            cropRect,
                                            GraphicsUnit.Pixel);
                            }

                            BitmapLuminanceSource source = new BitmapLuminanceSource(target);
                            BinaryBitmap          bitmap = new BinaryBitmap(new HybridBinarizer(source));
                            QRCodeReader          reader = new QRCodeReader();
                            Result result = reader.decode(bitmap);
                            if (result != null)
                            {
                                string ret = result.Text;
                                return(ret);
                            }
                        }
                    }
                }
            }
            catch
            {
            }

            return(string.Empty);
        }
        public static bool Detect(Bitmap capturedImage)
        {
            var source    = new BitmapLuminanceSource(capturedImage);
            var binarizer = new HybridBinarizer(source);
            var bbitmap   = new BinaryBitmap(binarizer);

            var detect = ZXing.PDF417.Internal.Detector.detect(bbitmap, null, false);
            var result = detect.Points.Count > 0;

            return(result);
        }
Esempio n. 29
0
        private void Decode(IEnumerable <Bitmap> bitmaps)
        {
            _timeStart = DateTime.Now.Ticks;
            results.Clear();
            var fileName = new FileInfo(_config.FilePath).Name;

            var i = 1;

            foreach (var bitmap in bitmaps)
            {
                var singleStart = DateTime.Now.Ticks;

                // https://github.com/micjahn/ZXing.Net/issues/132 requires bindings package
                // as here: https://stackoverflow.com/questions/28561772/c-sharp-with-zxing-net-decoding-the-qr-code
                var imageAsLuminance = new BitmapLuminanceSource(bitmap);

                try
                {
                    var mappedResult = CallDecode(imageAsLuminance, singleStart);

                    var singleTime = new TimeSpan(DateTime.Now.Ticks - singleStart);
                    mappedResult.FileName   = fileName;
                    mappedResult.Duration   = singleTime;
                    mappedResult.PageInTiff = i;
                    results.Add(mappedResult);
                }
                catch (Exception)
                {
                    string message      = "Decoder failed with read exception.";
                    var    singleTime   = new TimeSpan(DateTime.Now.Ticks - singleStart);
                    var    mappedResult = new DecodeResult();
                    mappedResult.Success    = false;
                    mappedResult.Note       = message;
                    mappedResult.FileName   = fileName;
                    mappedResult.Duration   = singleTime;
                    mappedResult.PageInTiff = i;
                    results.Add(mappedResult);
                }

                i++;
            }

            // save analysis
            var timerStop = DateTime.Now.Ticks;

            statistics.FileName        = fileName;
            statistics.ExecuteDuration = new TimeSpan(timerStop - _timeStart);
            statistics.Results         = results;

            if (results == null)
            {
                statistics.Note = "No barcode found in image";
            }
        }
        public void Should_Calculate_Luminance_And_Decode(string fileName, PixelFormat pixelFormat, string content)
        {
            var bitmap  = (Bitmap)Bitmap.FromFile(fileName);
            var bitmap2 = bitmap.Clone(new Rectangle(0, 0, bitmap.Width, bitmap.Height), pixelFormat);

            Assert.That(bitmap2.PixelFormat, Is.EqualTo(pixelFormat));
            var luminance = new BitmapLuminanceSource(bitmap2);
            var reader    = new BarcodeReader();
            var result    = reader.Decode(luminance);

            Assert.That(result?.Text, Is.EqualTo(content));
        }
Esempio n. 31
0
 internal static BinaryBitmap getBinaryBitmap(String path)
 {
    var bufferedImage = getBufferedImage(path);
    var luminanceSource = new BitmapLuminanceSource(bufferedImage);
    return new BinaryBitmap(new GlobalHistogramBinarizer(luminanceSource));
 }