Exemplo n.º 1
0
        private async Task <string> ReadImageAsync(byte[] data)
        {
            try
            {
                var bitmap = new BitmapImage();
                using (var stream = new InMemoryRandomAccessStream())
                {
                    await stream.WriteAsync(data.AsBuffer());

                    stream.Seek(0);
                    await bitmap.SetSourceAsync(stream);
                }

                var source    = new RGBLuminanceSource(data, bitmap.PixelWidth, bitmap.PixelHeight);
                var reader    = new ZXing.QrCode.QRCodeReader();
                var binarizer = new HybridBinarizer(source);
                var bitmapx   = new BinaryBitmap(binarizer);
                var result    = reader.decode(bitmapx);

                return(result.Text);
            }
            catch (Exception ex)
            {
                return(string.Empty);
            }
        }
Exemplo n.º 2
0
        public static string parse(Binarizer bin)
        {
            var bitmap = new BinaryBitmap(bin);
            var reader = new ZXing.QrCode.QRCodeReader();
            var result = reader.decode(bitmap);

            if (result == null)
            {
                return(null);
            }
            return(result.Text);
        }
Exemplo n.º 3
0
 /// <summary>
 /// 读取二维码内容
 /// </summary>
 /// <param name="bitmap"></param>
 /// <returns></returns>
 public String ReadQrCode(Bitmap bitmap)
 {
     try
     {
         ZXing.BitmapLuminanceSource bitmapLuminanceSource = new BitmapLuminanceSource(bitmap);
         BinaryBitmap image = new BinaryBitmap(new ZXing.Common.HybridBinarizer(bitmapLuminanceSource));
         ZXing.QrCode.QRCodeReader qRCodeReader = new ZXing.QrCode.QRCodeReader();
         Result res = qRCodeReader.decode(image);
         return(res.Text);
     }
     catch
     {
         return(string.Empty);
     }
 }
Exemplo n.º 4
0
        public static List <QRCode> ExtractFrom(Image image)
        {
            List <QRCode> output = new List <QRCode>();
            Bitmap        bitmap = new Bitmap(image);

            ZXing.QrCode.QRCodeReader    qr        = new ZXing.QrCode.QRCodeReader();
            ZXing.LuminanceSource        source    = new ZXing.BitmapLuminanceSource(bitmap);
            ZXing.Common.HybridBinarizer hybrid    = new ZXing.Common.HybridBinarizer(source);
            ZXing.BinaryBitmap           binBitmap = new ZXing.BinaryBitmap(hybrid);

            ZXing.Result[] multiresults = new ZXing.Multi.QrCode.QRCodeMultiReader().decodeMultiple(binBitmap);

            if (multiresults != null && multiresults.Length > 0)
            {
                foreach (ZXing.Result result in multiresults)
                {
                    QRCode qrCode = new QRCode(result.Text);
                    qrCode.Points = new PointF[result.ResultPoints.Length];
                    for (int i = 0; i < result.ResultPoints.Length; i++)
                    {
                        qrCode.Points[i] = new PointF(result.ResultPoints[i].X, result.ResultPoints[i].Y);
                    }
                    output.Add(qrCode);
                }
            }

            ZXing.Result singleresult = qr.decode(binBitmap);

            if (singleresult != null)
            {
                QRCode qrCode = new QRCode(singleresult.Text);
                qrCode.Points    = new PointF[4];
                qrCode.Points[0] = new PointF(singleresult.ResultPoints[0].X, singleresult.ResultPoints[0].Y);
                qrCode.Points[1] = new PointF(singleresult.ResultPoints[1].X, singleresult.ResultPoints[1].Y);
                qrCode.Points[2] = new PointF(singleresult.ResultPoints[2].X, singleresult.ResultPoints[2].Y);
                if (singleresult.ResultPoints.Length > 2)
                {
                    qrCode.Points[3] = new PointF(singleresult.ResultPoints[3].X, singleresult.ResultPoints[3].Y);
                }
                output.Add(qrCode);
            }

            return(output);
        }
Exemplo n.º 5
0
        private string ReadImageAsync(byte[] data)
        {
            try
            {
                var originalImage = BitmapFactory.DecodeByteArray(data, 0, data.Length);

                var source    = new RGBLuminanceSource(data, originalImage.Width, originalImage.Height);
                var reader    = new ZXing.QrCode.QRCodeReader();
                var binarizer = new HybridBinarizer(source);
                var bitmapx   = new BinaryBitmap(binarizer);
                var result    = reader.decode(bitmapx);

                return(result.Text);
            }
            catch (Exception ex)
            {
                return(string.Empty);
            }
        }
Exemplo n.º 6
0
        public static string QRDecoder(System.IO.Stream qrCodeFileStream)
        {
            var sKManagedStream = new SkiaSharp.SKManagedStream(qrCodeFileStream, true);
            var sKBitmap        = SkiaSharp.SKBitmap.Decode(sKManagedStream);

            sKManagedStream.Dispose();
            if (sKBitmap.IsEmpty)
            {
                sKBitmap.Dispose();
                throw new Exception("未识别的图片文件");
            }

            var w  = sKBitmap.Width;
            var h  = sKBitmap.Height;
            int ps = w * h;

            byte[] bytes     = new byte[ps * 3];
            int    byteIndex = 0;

            for (var x = 0; x < w; x++)
            {
                for (var y = 0; y < h; y++)
                {
                    var color = sKBitmap.GetPixel(x, y);
                    bytes[byteIndex + 0] = color.Red;
                    bytes[byteIndex + 1] = color.Green;
                    bytes[byteIndex + 2] = color.Blue;
                    byteIndex           += 3;
                }
            }
            sKBitmap.Dispose();

            var qRCodeReader       = new ZXing.QrCode.QRCodeReader();
            var rGBLuminanceSource = new ZXing.RGBLuminanceSource(bytes, w, h);
            var hybridBinarizer    = new ZXing.Common.HybridBinarizer(rGBLuminanceSource);
            var binaryBitmap       = new ZXing.BinaryBitmap(hybridBinarizer);
            var hints = new Dictionary <ZXing.DecodeHintType, object>();

            hints.Add(ZXing.DecodeHintType.CHARACTER_SET, "utf-8");
            var result = qRCodeReader.decode(binaryBitmap, hints);

            return(result != null ? result.Text : "");
        }
            public void CheckBarCode()
            {
                try {
                    using(var bbImage = new System.Drawing.Bitmap (codeImage)){
                        Reader barReader = new ZXing.QrCode.QRCodeReader();
                        //Reader barReader = new MultiFormatReader ();
                        LuminanceSource source = new RGBLuminanceSource (bbImage, (int)codeImage.Size.Width, (int)codeImage.Size.Height);
                        BinaryBitmap bb = new BinaryBitmap (new HybridBinarizer (source));

                        Result res = barReader.decode (bb);
                        InvokeOnMainThread (() => {
                            codeImage.Dispose();
                            if (res != null) {
                                //result has the string from the image
                                //AppDelegate.main.decryptVC.txtScanResult.Text = res.Text;
                                AppDelegate.main.decryptVC.ProcessScannedCode(res.Text);
                            } else {
                                //no valid code found;
                            }
                            numRuns++;
                            barChecking = false;
                        });
                    }

                } catch (Exception e) {
                    barChecking = false;
                    Console.WriteLine (e);
                }
            }
Exemplo n.º 8
0
        private async void ScanQRCodeItem_Click(object sender, EventArgs e)
        {
            foreach (Screen screen in Screen.AllScreens)
            {
                using (var fullImage = new System.Drawing.Bitmap(screen.Bounds.Width,
                                                                 screen.Bounds.Height))
                {
                    using (var g = System.Drawing.Graphics.FromImage(fullImage))
                    {
                        g.CopyFromScreen(screen.Bounds.X,
                                         screen.Bounds.Y,
                                         0, 0,
                                         fullImage.Size,
                                         System.Drawing.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);
                        var cropRect   = new System.Drawing.Rectangle(marginLeft, marginTop, fullImage.Width - marginLeft * 2, fullImage.Height - marginTop * 2);
                        var target     = new System.Drawing.Bitmap(screen.Bounds.Width, screen.Bounds.Height);

                        double imageScale = (double)screen.Bounds.Width / (double)cropRect.Width;
                        using (var g = System.Drawing.Graphics.FromImage(target))
                        {
                            g.DrawImage(fullImage, new System.Drawing.Rectangle(0, 0, target.Width, target.Height),
                                        cropRect,
                                        System.Drawing.GraphicsUnit.Pixel);
                        }
                        var source = new ZXing.BitmapLuminanceSource(target);
                        var bitmap = new ZXing.BinaryBitmap(new ZXing.Common.HybridBinarizer(source));
                        var reader = new ZXing.QrCode.QRCodeReader();
                        var result = reader.decode(bitmap);
                        if (result != null)
                        {
                            var splash = new QRCodeSplashForm();
                            if (result.Text.StartsWith("vmess://", StringComparison.OrdinalIgnoreCase))
                            {
                                var success = await controller.AddServerBySSURL(result.Text);

                                if (success)
                                {
                                    splash.FormClosed += splash_FormClosed;
                                }
                            }
                            else if (result.Text.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || result.Text.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
                            {
                                _urlToOpen         = result.Text;
                                splash.FormClosed += openURLFromQRCode;
                            }
                            else
                            {
                                _urlToOpen         = result.Text;
                                splash.FormClosed += copyFromQRCode;
                            }
                            double minX = Int32.MaxValue, minY = Int32.MaxValue, maxX = 0, maxY = 0;
                            foreach (ZXing.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);
                            }
                            minX /= imageScale;
                            minY /= imageScale;
                            maxX /= imageScale;
                            maxY /= imageScale;
                            double margin = (maxX - minX) * 0.20f;
                            minX             += -margin + marginLeft;
                            maxX             += margin + marginLeft;
                            minY             += -margin + marginTop;
                            maxY             += margin + marginTop;
                            splash.Location   = new System.Drawing.Point(screen.Bounds.X, screen.Bounds.Y);
                            splash.TargetRect = new System.Drawing.Rectangle((int)minX + screen.Bounds.X, (int)minY + screen.Bounds.Y, (int)maxX - (int)minX, (int)maxY - (int)minY);
                            splash.Size       = new System.Drawing.Size(fullImage.Width, fullImage.Height);
                            splash.Show();
                            return;
                        }
                    }
                }
            }
            MessageBox.Show(I18N.GetString("No QRCode found. Try to zoom in or move it to the center of the screen."));
        }
Exemplo n.º 9
0
        public void splitTiff(GdPictureImaging _gdPictureImaging, string file)
        {
            lock (lockThis)
            {
                string diretoriodeEnvio = ConfigurationManager.AppSettings["pastaSAIDA"];
                string diretorioMerge   = ConfigurationManager.AppSettings["pastaMERGE"];
                string diretorioerro    = ConfigurationManager.AppSettings["pastaERRO"];
                string diretoriobackup  = ConfigurationManager.AppSettings["pastaBACKUP"];
                string pastazuada       = ConfigurationManager.AppSettings["pastazuada"];
                string pastaJoin        = ConfigurationManager.AppSettings["pastaJoin"];

                String identificacaoArquivo = Guid.NewGuid().ToString();
                string merge        = diretorioMerge + @"\" + identificacaoArquivo;
                string pastajoinArq = pastaJoin + @"\" + identificacaoArquivo;
                if (!Directory.Exists(merge))
                {
                    Directory.CreateDirectory(merge);
                }

                if (!Directory.Exists(pastajoinArq))
                {
                    Directory.CreateDirectory(pastajoinArq);
                }
                int TiffImageID = _gdPictureImaging.TiffCreateMultiPageFromFile(file);

                int           ImageCount = _gdPictureImaging.TiffGetPageCount(TiffImageID);
                string        DocmentName = "";
                int           ContadorPaginas = 0;
                String        CodUnimed = "", NumBeneficiario, CodPrestador, DataAtendimento, NumNotaGuia;
                List <string> lista = new List <string>();
                try
                {
                    for (int i = 1; i <= ImageCount; i++)
                    {
                        var tif = _gdPictureImaging.TiffSelectPage(TiffImageID, i);
                        if (tif == 0)
                        {
                            List <String> barcode = new List <string>();
                            ContadorPaginas++;



                            if (_gdPictureImaging.BarcodeQRReaderDoScan(TiffImageID) == GdPicture.GdPictureStatus.OK)
                            {
                                var str = pastajoinArq + @"\" + Guid.NewGuid() + ".tif";
                                _gdPictureImaging.SaveAsTIFF(TiffImageID, str, TiffCompression.TiffCompressionCCITT4);
                                // load a bitmap

                                var             readers        = new ZXing.QrCode.QRCodeReader();
                                var             barcodeBitmsap = (Bitmap)Bitmap.FromFile(str);
                                LuminanceSource sources        = new BitmapLuminanceSource(barcodeBitmsap);
                                BinaryBitmap    binBitmap      = new BinaryBitmap(new GlobalHistogramBinarizer(sources));
                                var             resulst        = readers.decode(binBitmap);
                                barcodeBitmsap.Dispose();


                                if (resulst != null)
                                {
                                    barcode.Add(resulst.Text);
                                }

                                if (barcode.Count == 0)
                                {
                                    var result = _gdPictureImaging.BarcodeQRReaderGetBarcodeCount();
                                    for (int bar = 1; bar <= result; bar++)
                                    {
                                        barcode.Add(_gdPictureImaging.BarcodeQRReaderGetBarcodeValue(bar));
                                    }
                                }



                                if (barcode.Count > 0)
                                {
                                    foreach (var item in barcode)
                                    {
                                        if (item.Length == 54)
                                        {
                                            if (DocmentName == "")
                                            {
                                                CodUnimed       = item.Substring(0, 4);
                                                NumBeneficiario = item.Substring(4, 13);
                                                CodPrestador    = item.Substring(17, 9).TrimStart('0');
                                                DataAtendimento = item.Substring(26, 8);
                                                NumNotaGuia     = item.Substring(34, 20).TrimStart('0');
                                                DocmentName     = "Producao Medica_" + CodUnimed + "_" + NumBeneficiario + "_" + CodPrestador + "_" + DataAtendimento + "_" + NumNotaGuia + "_GuiasAtendimento.tif";
                                            }

                                            else
                                            {
                                                if (lista.Count > 0)
                                                {
                                                    ///join dos arquivos
                                                    _gdPictureImaging.TiffMergeFiles(lista.ToArray(), merge + @"\" + DocmentName, TiffCompression.TiffCompressionCCITT4);
                                                    while (true)
                                                    {
                                                        if (!IsFileLocked(merge + @"\" + DocmentName))
                                                        {
                                                            break;
                                                        }
                                                    }
                                                    if (!File.Exists(diretoriodeEnvio + @"\" + DocmentName))
                                                    {
                                                        File.Move(merge + @"\" + DocmentName, diretoriodeEnvio + @"\" + DocmentName);
                                                    }
                                                    lista = new List <string>();


                                                    CodUnimed       = item.Substring(0, 4);
                                                    NumBeneficiario = item.Substring(4, 13);
                                                    CodPrestador    = item.Substring(17, 9).TrimStart('0');
                                                    DataAtendimento = item.Substring(26, 8);
                                                    NumNotaGuia     = item.Substring(34, 20).TrimStart('0');
                                                    DocmentName     = "Producao Medica_" + CodUnimed + "_" + NumBeneficiario + "_" + CodPrestador + "_" + DataAtendimento + "_" + NumNotaGuia + "_GuiasAtendimento.tif";// "Producao Medica_" + CodUnimed + "_" + NumBeneficiario + "_" + CodPrestador + "_" + DataAtendimento + "_" + NumNotaGuia + "_GuiasAtendimento.tif";
                                                }
                                            }
                                        }
                                    }
                                    var intDestDocID = _gdPictureImaging.CreateClonedGdPictureImageI(TiffImageID);
                                    var guid         = Guid.NewGuid();
                                    var nome         = merge + @"\" + guid + ".tif";
                                    _gdPictureImaging.SaveAsTIFF(intDestDocID, nome, TiffCompression.TiffCompressionCCITT4);
                                    lista.Add(nome);
                                }
                                else
                                {
                                    var intDestDocID = _gdPictureImaging.CreateClonedGdPictureImageI(TiffImageID);
                                    var guid         = Guid.NewGuid();
                                    var nome         = merge + @"\" + guid + ".tif";
                                    _gdPictureImaging.SaveAsTIFF(intDestDocID, nome, TiffCompression.TiffCompressionCCITT4);
                                    lista.Add(nome);
                                }
                            }


                            if (ContadorPaginas == 1 && (barcode.Where(_s => _s.Length > 54).Count() > 0 || barcode.Where(_s => _s.Length > 54).Count() < 0))
                            {
                                var intDestDocID = _gdPictureImaging.CreateClonedGdPictureImageI(TiffImageID);
                                var guid         = Guid.NewGuid();
                                var nome         = pastazuada + @"\" + guid + ".tif";
                                _gdPictureImaging.SaveAsTIFF(intDestDocID, nome, TiffCompression.TiffCompressionCCITT4);
                                lista.Add(nome);
                            }

                            if (ContadorPaginas == ImageCount)
                            {
                                if (DocmentName == "")
                                {
                                    _gdPictureImaging.ReleaseGdPictureImage(TiffImageID);
                                    while (true)
                                    {
                                        if (!IsFileLocked(file))
                                        {
                                            break;
                                        }
                                    }
                                    if (!File.Exists(pastazuada + @"\" + Path.GetFileName(file)))
                                    {
                                        File.Move(file, pastazuada + @"\" + Path.GetFileName(file));
                                    }
                                }
                                else
                                {
                                    var d = _gdPictureImaging.TiffMergeFiles(lista.ToArray(), diretorioMerge + @"\" + DocmentName, TiffCompression.TiffCompressionCCITT4);

                                    while (true)
                                    {
                                        if (!IsFileLocked(diretorioMerge + @"\" + DocmentName))
                                        {
                                            //if (File.Exists(diretoriodeEnvio + @"\" + DocmentName))
                                            //{
                                            //    File.Delete(diretoriodeEnvio + @"\" + DocmentName);
                                            //}
                                            if (!File.Exists(diretoriodeEnvio + @"\" + DocmentName))
                                            {
                                                File.Move(diretorioMerge + @"\" + DocmentName, diretoriodeEnvio + @"\" + DocmentName);
                                            }
                                            else
                                            {
                                                int contador = 0;
                                                var nomeArq  = diretorioMerge + @"\" + DocmentName.Replace(".tif", "") + "(" + contador + ")" + ".tif";
                                                while (File.Exists(nomeArq))
                                                {
                                                    contador++;
                                                    nomeArq = diretorioMerge + @"\" + DocmentName.Replace(".tif", "") + "(" + contador + ")" + ".tif";
                                                }

                                                File.Move(diretorioMerge + @"\" + DocmentName, diretoriodeEnvio + @"\" + nomeArq);
                                            }

                                            break;
                                        }
                                    }
                                }
                                lista = new List <string>();
                            }
                        }
                    }
                }

                catch (Exception ex)
                {
                    using (FileStream fs = File.Create("c:\\errrrrrrr.txt"))
                    {
                        Byte[] info = new UTF8Encoding(true).GetBytes(ex.Message);
                        // Add some information to the file.
                        fs.Write(info, 0, info.Length);
                    }
                    throw new Exception(ex.Message);
                }
                finally
                {
                    _gdPictureImaging.ReleaseGdPictureImage(TiffImageID);

                    while (true)
                    {
                        if (!IsFileLocked(file))
                        {
                            File.Delete(file);
                            break;
                        }
                    }
                    deleteMerge(merge);
                    deleteMerge(pastajoinArq);
                }
            }
        }