private void ReadBitmap(Bitmap bitmap)
        {
            var reader = new ZXing.BarcodeReader();
            reader.Options.TryHarder = true;
            reader.AutoRotate = true;

            var decoded = reader.Decode(bitmap);

            if (decoded != null)
            {
                var text = decoded.Text;

                var uri = new Uri(text);

                if (uri.Scheme == "otpauth")
                {
                    var queryString = HttpUtility.ParseQueryString(uri.Query);
                    var secret = queryString["secret"];
                    var account = uri.LocalPath.StartsWith("/") ? uri.LocalPath.Substring(1) : uri.LocalPath;
                    txtAccountName.Text = HttpUtility.UrlDecode(account);
                    Key = secret;
                }
                else
                {
                    MessageBox.Show("The QR Code does not contain valid OAuth data", "Authentiqr.NET", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                MessageBox.Show("The QR Code could not be read", "Authentiqr.NET", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Beispiel #2
1
        private void LoadFromQR(Bitmap bitmap)
        {
            ZXing.BarcodeReader reader = new ZXing.BarcodeReader();
            reader.PossibleFormats = new[] { ZXing.BarcodeFormat.QR_CODE };
            ZXing.Result result = reader.Decode(bitmap);

            if (result != null)
            {
                try
                {
                    AC.Pattern pattern = AC.Pattern.CreateFromRawData(result.RawBytes);
                    LoadPattern(pattern);
                }
                catch (NotImplementedException)
                {
                    MessageBox.Show("This type of pattern is currently not supported.", Text);
                }
            }
            else
            {
                MessageBox.Show("A valid QR code was not found in the selected image.", Text);
            }
        }
        async Task <ZXing.Result> DecodeThread()
        {
            ZXing.BarcodeReader barcodeReader = new ZXing.BarcodeReader();
            ZXing.Result        res           = null;
            bool running = true;

            void DecodingThreadFunc()
            {
                lock (m_ColorsLock)
                {
                    if (m_Colors32 != null && m_Colors32.Length > 0)
                    {
                        res = barcodeReader.Decode(m_Colors32, m_Width, m_Height, ZXing.RGBLuminanceSource.BitmapFormat.RGBA32);
                    }
                }
                running = false;
            }

            m_DecodeThread = new Thread(DecodingThreadFunc);
            m_DecodeThread.Start();

            while (running)
            {
                await Task.Delay(1);
            }

            return(res);
        }
        public async Task ScanBarcodeAsync(Windows.Storage.StorageFile file)
        {
            WriteableBitmap bitmap;
            BitmapDecoder decoder;
            using (IRandomAccessStream str = await file.OpenReadAsync())
            {
                decoder = await BitmapDecoder.CreateAsync(str);
                bitmap = new WriteableBitmap(Convert.ToInt32(decoder.PixelWidth), Convert.ToInt32(decoder.PixelHeight));
                await bitmap.SetSourceAsync(str);
            }

            lock (locker)
            {                
                ZXing.BarcodeReader reader = new ZXing.BarcodeReader();
                reader.Options.PossibleFormats = new ZXing.BarcodeFormat[] { ZXing.BarcodeFormat.CODE_128, ZXing.BarcodeFormat.QR_CODE, ZXing.BarcodeFormat.CODE_39 };
                reader.Options.TryHarder = true;
                reader.AutoRotate = true;
                var results = reader.Decode(bitmap);
                if (results == null)
                {
                    this.OnBarcodeScannCompleted(new BarcodeScanCompletedEventArgs(false, string.Empty));
                }
                else
                {
                    this.OnBarcodeScannCompleted(new BarcodeScanCompletedEventArgs(true, results.Text));
                }
            }
        }
Beispiel #5
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ScanBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker bw = (BackgroundWorker)sender;

            while (!scanBackgroundWorker.CancellationPending)
            {
                // バーコード読み取り
                ZXing.BarcodeReader reader = new ZXing.BarcodeReader();
                reader.AutoRotate        = true;
                reader.Options.TryHarder = true;

                //画像取得
                capture.Grab();
                OpenCvSharp.NativeMethods.videoio_VideoCapture_operatorRightShift_Mat(capture.CvPtr, frame.CvPtr);

                // Windows FormsではBitmapを渡す
                ZXing.Result result = reader.Decode(BitmapConverter.ToBitmap(frame.CvtColor(ColorConversionCodes.BGR2GRAY)));

                if (result != null)
                {
                    this.Invoke(new Action <ZXing.Result>(this.UpdateBarcodeFormatText), result);
                }

                bw.ReportProgress(0);
            }
        }
Beispiel #6
0
        private void ReadBitmap(Bitmap bitmap)
        {
            var reader = new ZXing.BarcodeReader();

            reader.Options.TryHarder = true;
            reader.AutoRotate        = true;

            var decoded = reader.Decode(bitmap);

            if (decoded != null)
            {
                var text = decoded.Text;

                var uri = new Uri(text);

                if (uri.Scheme == "otpauth")
                {
                    var queryString = HttpUtility.ParseQueryString(uri.Query);
                    var secret      = queryString["secret"];
                    var account     = uri.LocalPath.StartsWith("/") ? uri.LocalPath.Substring(1) : uri.LocalPath;
                    txtAccountName.Text = HttpUtility.UrlDecode(account);
                    Key = secret;
                }
                else
                {
                    MessageBox.Show("The QR Code does not contain valid OAuth data", "Authentiqr.NET", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                MessageBox.Show("The QR Code could not be read", "Authentiqr.NET", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Beispiel #7
0
        private async void Button_Click(object sender, EventArgs e)
        {
            var dialog = new OpenFileDialog();

            dialog.Title  = "バーコードの写った画像ファイルを開く";
            dialog.Filter = "画像ファイル(*.png;*.jpg;*.jpeg;*.gif;*.bmp)|*.png;*.jpg;*.jpeg;*.gif;*.bmp";
            if (dialog.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            ClearResult();
            Application.DoEvents();

            // 選択された画像ファイルを表示
            var source = new Bitmap(dialog.FileName);

            this.Image1.Image = source;

            // バーコード読み取り
            ZXing.BarcodeReader reader = new ZXing.BarcodeReader()
            {
                AutoRotate = true,
            };
            // Windows FormsではBitmapを渡す
            //ZXing.Result result = reader.Decode(Image1.Image as Bitmap);
            // ☟別スレッドでやるなら、作成済みのBitmapインスタンスは渡せない
            ZXing.Result result
                = await Task.Run(() => reader.Decode(new Bitmap(dialog.FileName)));

            if (result != null)
            {
                ShowResult(result);
            }
        }
Beispiel #8
0
        /// <summary>
        /// QR読み取り処理
        /// </summary>
        /// <param name="image"></param>
        private void qrRead(System.Drawing.Image image)
        {
            try
            {
                Bitmap myBitmap = new Bitmap(image);

                string text = string.Empty;

                using (Mat imageMat = OpenCvSharp.Extensions.BitmapConverter.ToMat(myBitmap))
                {
                    // QRコードの解析
                    ZXing.BarcodeReader reader = new ZXing.BarcodeReader();

                    //テンポラリパス
                    for (int i = 0; i < maxFilterSize; i++)
                    {
                        //奇数にする必要があるので、さらに加算
                        i++;

                        //偶数を指定するとExceptionが発生します。
                        int filterSize = i;

                        //別変数のMATにとる
                        using (Mat imageMatFilter = imageMat.GaussianBlur(new OpenCvSharp.Size(filterSize, filterSize), 0))
                        {
                            //ビットマップに戻します
                            using (Bitmap filterResult = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(imageMatFilter))
                            {
                                try
                                {
                                    //QRコードの解析
                                    ZXing.Result result = reader.Decode(filterResult);

                                    //これでQRコードのテキストが読める
                                    if (result != null)
                                    {
                                        text = result.Text;
                                        System.Windows.Forms.MessageBox.Show(text, "読み取り値"); //メッセージポップアップ
                                        return;
                                    }
                                }
                                catch
                                {
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //システムエラー発生時
                System.Windows.Forms.MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace);
                this.Close();
            }
            finally
            {
            }
        }
Beispiel #9
0
        //private int imgWidth = -1;
        //private int imgHeight = -1;

        ////[SerializeField] private Text uiDebugText;

        //// Use this for initialization
        //void Start()
        //{
        //    HoloCameraManager.Instance.TakeImageAction += DecodeQr;

        //    //InputManager.Instance.AddGlobalListener(gameObject);
        //    //InputManager.Instance.RemoveGlobalListener();
        //}

        //private void DecodeQr(List<byte> bytes)
        //{
        //    imgWidth = HoloCameraManager.Instance.Resolution.width;
        //    imgHeight = HoloCameraManager.Instance.Resolution.height;
        //    this.uiDebugText.text += "\n" + Decode(bytes.ToArray(), imgWidth, imgHeight);
        //}

        public static string Decode(byte[] src, int width, int height)
        {
#if ENABLE_WINMD_SUPPORT
            ZXing.IBarcodeReader reader = new ZXing.BarcodeReader();
            var res = reader.Decode(src, width, height, ZXing.BitmapFormat.BGRA32);
            if (res == null)
            {
                return(null);
            }
            return(res.Text);
#else
            return(null);
#endif
        }
Beispiel #10
0
 private ProtectedString ParseFromImage(System.Drawing.Bitmap bitmap)
 {
     if (bitmap == null)
     {
         return(ProtectedString.EmptyEx);
     }
     ZXing.BarcodeReader r      = new ZXing.BarcodeReader();
     ZXing.Result        result = r.Decode(bitmap);
     if (result != null)
     {
         return(new ProtectedString(true, result.Text));
     }
     return(ProtectedString.EmptyEx);
 }
 private void BtnUpload_Click(object sender, EventArgs e)
 {
     if (FileUpload1.HasFile)
     {
         DivInfo.Visible    = false;
         DivWarning.Visible = false;
         var ext      = Path.GetExtension(FileUpload1.FileName).ToLower();
         var tempPath = Path.GetTempFileName() + ext;
         FileUpload1.SaveAs(tempPath);
         HashSet <String> exts = new HashSet <string> {
             ".bmp", ".png", ".jpg", ".gif", ".png"
         };
         if (exts.Contains(ext))
         {
             ImageQR.ImageUrl = "/handlers/imageloader.ashx?ImgPath=" + tempPath;
             var qr      = new ZXing.BarcodeReader();
             var options = new DecodingOptions
             {
                 CharacterSet = "UTF-8",
             };
             qr.Options = options;
             Bitmap bmp = (Bitmap)Bitmap.FromFile(tempPath);
             var    res = qr.Decode(bmp);
             if (res != null && !string.IsNullOrEmpty(res.Text))
             {
                 try
                 {
                     var decrypt = Crypto.Decrypt(res.Text);
                     LoadHeaderInfo(decrypt.Trim());
                 }
                 catch
                 {
                     CommonWeb.Alert(this, "Qr dapat dibaca tapi tidak valid.");
                 }
             }
             else
             {
                 CommonWeb.Alert(this, "Qr tidak dapat dibaca, atau gambar tidak valid.");
             }
         }
         else
         {
             CommonWeb.Alert(this, "Silakan upload file dengan tipe gambar");
         }
     }
     else
     {
         CommonWeb.Alert(this, "Silakan pilih foto QR LHP terlebih dahulu.");
     }
 }
        public Form1()
        {
            InitializeComponent();

            Bitmap img = new Bitmap("qrcode.gif");

            ZXing.BarcodeReader reader = new ZXing.BarcodeReader();
            ZXing.Result        result = reader.Decode(img);

            if (result != null)
            {
                textBox1.Text = result.BarcodeFormat.ToString();
                textBox2.Text = result.Text;
            }
        }
        /// <summary>
        /// Decodes a barcode from the given image.
        /// </summary>
        /// <param name="image">The image of the barcode.</param>
        /// <returns>The data encoded in the barcode.</returns>
        ///
        /// <remarks>Uses the ZXing.NET library to parse the image.</remarks>
        public string DecodeBarcode(Image image)
        {
            var reader = new ZXing.BarcodeReader();

            var bmp  = new Bitmap(image);
            var data = reader.Decode(bmp);

            if (data != null)
            {
                return(data.Text);
            }
            else
            {
                return("");
            }
        }
Beispiel #14
0
        private void timer3_Tick(object sender, EventArgs e)
        {
            System.Drawing.Bitmap bitmap = null;
            //宣告 QRCode Reader 物件

            ZXing.IBarcodeReader reader = new ZXing.BarcodeReader();

            bitmap = (Bitmap)pictureBox2.Image;
            //進行解碼的動作
            ZXing.Result result = reader.Decode(bitmap);

            if (result != null)
            {   //如果有成功解讀,則顯示文字
                label10.Text = result.Text;
            }
        }
Beispiel #15
0
        private void button2_Click(object sender, EventArgs e)
        {
            ZXing.BarcodeReader barcodeReader = new ZXing.BarcodeReader();
            string deskPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);

            System.IO.FileInfo fi = new System.IO.FileInfo(deskPath + @"\test.jpg");

            if (fi.Exists)
            {
                var barcodeBitmap = (Bitmap)Image.FromFile(deskPath + @"\test.jpg");
                var result        = barcodeReader.Decode(barcodeBitmap);

                this.textBox1.Text = result.Text;
            }
            else
            {
                MessageBox.Show("Please generate QRcode first.\n Press barcode maker button.", "Nofile", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void ReadBitmap(Bitmap bitmap)
        {
            var reader  = new ZXing.BarcodeReader();
            var decoded = reader.Decode(bitmap);

            RenderQRCode(decoded.Text);

            Regex otpInfo = new Regex(@"otpauth://totp/(.*)\?secret=([^&]+)(&.*)?");

            if (otpInfo.IsMatch(decoded.Text))
            {
                var match = otpInfo.Match(decoded.Text);
                txtAccountName.Text = HttpUtility.UrlDecode(match.Groups[1].Value);
                SetKey(match.Groups[2].Value);
            }
            else
            {
                MessageBox.Show("The QR Code does not contain valid OAuth data", "LCGoogleApps", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Beispiel #17
0
        private void TimerEventProcessor(object sender, EventArgs e)
        {
            Image <Bgr, Byte> frame = new Image <Bgr, Byte>(360, 280);

            frame             = cap.QueryFrame();
            _pictureBox.Image = frame.ToBitmap();

            ZXing.IBarcodeReader reader = new ZXing.BarcodeReader();

            ZXing.Result result = reader.Decode(frame.ToBitmap());

            qrRealTime._timer.Tick += new EventHandler(qrRealTime._timer_Tick);

            if (result != null)
            {
                _timer.Stop();
                _pictureBox.Image = null;
                MessageBox.Show(result.Text);
                qrRealTime._timer.Stop();
            }
        }
Beispiel #18
0
        private void CamSearchForm_Load(object sender, EventArgs e)
        {
            lblCaption.Left = (Width - lblCaption.Width) / 2;
            Thread threadShowPicture = new Thread(ShowPicture);

            videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice); //Загрузка списка доступных камер
            if (videoDevices.Count > 0)
            {
                foreach (FilterInfo device in videoDevices)
                {
                    lbSources.Items.Add(device.Name);
                }
            }
            lbSources.SelectedIndex = 0;

            reader = new ZXing.BarcodeReader();
            reader.Options.PossibleFormats = new List <ZXing.BarcodeFormat>(); //Возможные форматы для ридера. Создание коллекции
            reader.Options.PossibleFormats.Add(ZXing.BarcodeFormat.QR_CODE);   //Добавление в коллекцию формата QRCode

            threadShowPicture.Start();                                         //Поток вывода изобаржения камеры на форму
        }
Beispiel #19
0
        private void ReadBitmap(Bitmap bitmap)
        {
            var reader = new ZXing.BarcodeReader();

            reader.Options.TryHarder = true;
            reader.AutoRotate        = true;

            var decoded = reader.Decode(bitmap);

            if (decoded != null)
            {
                if (!ParseOtpAuth(decoded.Text))
                {
                    MessageBox.Show("The QR Code does not contain valid OAuth data", "Authentiqr.NET", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                MessageBox.Show("The QR Code could not be read", "Authentiqr.NET", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Beispiel #20
0
        public Barcode Read(Bitmap barcodeImage)
        {
            if (barcodeImage is null)
            {
                return(null);
            }
            barcodeImage = AddWhiteBorder(barcodeImage);

            ZXing.BarcodeReader reader = new ZXing.BarcodeReader();
            reader.Options.AssumeGS1 = true;
            reader.Options.TryHarder = true;
            reader.TryInverted       = true;
            reader.AutoRotate        = true;

            ZXing.Result result = reader.Decode(barcodeImage);
            if (result is null)
            {
                return(null);
            }

            return(new Barcode(result.Text, FormatMap.Resolve(result.BarcodeFormat)));
        }
Beispiel #21
0
        private void InitializeDecoder(PhotoConfirmationCapturedEventArgs photoResult)
        {
            _image  = new BitmapImage();
            _reader = new ZXing.BarcodeReader();


            Task.Run(delegate()
            {
                _reader.Options.TryHarder = false;
                _reader.TryInverted       = false;
                _reader.AutoRotate        = false;
                _image.SetSource(photoResult.Frame);
                ZXing.Result result = _reader.Decode(new WriteableBitmap(_image.PixelWidth, _image.PixelHeight));
                if (result != null)
                {
                    AddBarcodeToResults(result);
                }
                else
                {
                    SetActivityMessage("No barcode detected", false);
                }
            }).ConfigureAwait(false).GetAwaiter().GetResult();
        }
Beispiel #22
0
        private void LoadFromQR(Bitmap bitmap)
        {
            ZXing.BarcodeReader reader = new ZXing.BarcodeReader();
            reader.PossibleFormats = new[] { ZXing.BarcodeFormat.QR_CODE };
            reader.TryHarder = true;
            ZXing.Result[] results = reader.DecodeMultiple(bitmap);

            if (results != null && results.Length > 0)
            {
                try
                {
                    byte[] rawBytes = null;
                    if (results.Length == 1)
                        rawBytes = results[0].RawBytes;
                    else
                    {
                        QRSelectDialog qrSelectDialog = new QRSelectDialog(bitmap, results.Select(r => RectangleFromResultPoints(r.ResultPoints)).ToArray());
                        if (qrSelectDialog.ShowDialog() != DialogResult.OK)
                            return;

                        rawBytes = results[qrSelectDialog.SelectedIndex].RawBytes;
                    }

                    AC.Pattern pattern = AC.Pattern.CreateFromRawData(rawBytes);
                    LoadPattern(pattern);
                }
                catch (NotImplementedException)
                {
                    MessageBox.Show("This type of pattern is currently not supported.", Text);
                }
            }
            else
            {
                MessageBox.Show("A valid QR code was not found in the selected image.", Text);
            }
        }
 /// <summary>
 /// バーコードリーダー
 /// </summary>
 /// <param name="_bitmap">ビットマップ</param>
 /// <returns>バーコードリーダーの結果</returns>
 public async Task <ZXing.Result> BarcodeReader(Bitmap _bitmap)
 {
     ZXing.BarcodeReader reader = new ZXing.BarcodeReader();
     reader.AutoRotate = true;
     return(await Task.Run(() => reader.Decode(_bitmap)));
 }
Beispiel #24
0
 /// <summary>
 /// Initializes a new instance of the <see cref="BarcodeReader"/> class.
 /// </summary>
 public BarcodeReader()
 {
     wrappedReader = new ZXing.BarcodeReader();
 }
Beispiel #25
0
        public void OnPreviewFrame(byte[] bytes, Android.Hardware.Camera camera)
        {
            //Check and see if we're still processing a previous frame
            if (processingTask != null && !processingTask.IsCompleted)
            {
                return;
            }

            if ((DateTime.UtcNow - lastPreviewAnalysis).TotalMilliseconds < options.DelayBetweenAnalyzingFrames)
            {
                return;
            }

            var cameraParameters = camera.GetParameters();
            var width            = cameraParameters.PreviewSize.Width;
            var height           = cameraParameters.PreviewSize.Height;

            //var img = new YuvImage(bytes, ImageFormatType.Nv21, cameraParameters.PreviewSize.Width, cameraParameters.PreviewSize.Height, null);
            lastPreviewAnalysis = DateTime.UtcNow;

            processingTask = Task.Factory.StartNew(() =>
            {
                try
                {
                    if (barcodeReader == null)
                    {
                        barcodeReader = new ZXing.BarcodeReader(null, null, null, (p, w, h, f) =>
                                                                new ZXing.PlanarYUVLuminanceSource(p, w, h, 0, 0, w, h, false));
                        //new PlanarYUVLuminanceSource(p, w, h, dataRect.Left, dataRect.Top, dataRect.Width(), dataRect.Height(), false))

                        if (this.options.TryHarder.HasValue)
                        {
                            barcodeReader.Options.TryHarder = this.options.TryHarder.Value;
                        }
                        if (this.options.PureBarcode.HasValue)
                        {
                            barcodeReader.Options.PureBarcode = this.options.PureBarcode.Value;
                        }
                        if (!string.IsNullOrEmpty(this.options.CharacterSet))
                        {
                            barcodeReader.Options.CharacterSet = this.options.CharacterSet;
                        }
                        if (this.options.TryInverted.HasValue)
                        {
                            barcodeReader.TryInverted = this.options.TryInverted.Value;
                        }

                        if (this.options.PossibleFormats != null && this.options.PossibleFormats.Count > 0)
                        {
                            barcodeReader.Options.PossibleFormats = new List <ZXing.BarcodeFormat>();

                            foreach (var pf in this.options.PossibleFormats)
                            {
                                barcodeReader.Options.PossibleFormats.Add(pf);
                            }
                        }
                    }

                    bool rotate   = false;
                    int newWidth  = width;
                    int newHeight = height;

                    var cDegrees = getCameraDisplayOrientation(this.activity);

                    if (cDegrees == 90 || cDegrees == 270)
                    {
                        rotate    = true;
                        newWidth  = height;
                        newHeight = width;
                    }

                    var start = PerformanceCounter.Start();

                    if (rotate)
                    {
                        bytes = rotateCounterClockwise(bytes, width, height);
                    }

                    var result = barcodeReader.Decode(bytes, newWidth, newHeight, ZXing.RGBLuminanceSource.BitmapFormat.Unknown);

                    PerformanceCounter.Stop(start, "Decode Time: {0} ms (width: " + width + ", height: " + height + ", degrees: " + cDegrees + ", rotate: " + rotate + ")");

                    if (result == null || string.IsNullOrEmpty(result.Text))
                    {
                        return;
                    }

                    Android.Util.Log.Debug("ZXing.Mobile", "Barcode Found: " + result.Text);

                    ShutdownCamera();

                    callback(result);
                }
                catch (ZXing.ReaderException)
                {
                    Android.Util.Log.Debug("ZXing.Mobile", "No barcode Found");
                    // ignore this exception; it happens every time there is a failed scan
                }
                catch (Exception)
                {
                    // TODO: this one is unexpected.. log or otherwise handle it
                    throw;
                }
            });
        }
Beispiel #26
0
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            var picker = new Windows.Storage.Pickers.FileOpenPicker();

            picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail;
            picker.FileTypeFilter.Add(".jpg");
            picker.FileTypeFilter.Add(".jpeg");
            picker.FileTypeFilter.Add(".png");
            picker.FileTypeFilter.Add(".gif");
            picker.FileTypeFilter.Add(".bmp");

            Windows.Storage.StorageFile file = await picker.PickSingleFileAsync();

            if (file == null)
            {
                return;
            }

            ClearResult();

            // 選択された画像ファイルからSoftwareBitmapを作る
            // https://docs.microsoft.com/ja-jp/windows/uwp/audio-video-camera/imaging
            SoftwareBitmap softwareBitmap;

            using (IRandomAccessStream stream = await file.OpenReadAsync())
            {
                BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);

                softwareBitmap = await decoder.GetSoftwareBitmapAsync();
            }
            // Image コントロールは、BGRA8 エンコードを使用し、プリマルチプライ処理済みまたはアルファ チャネルなしの画像しか受け取れない
            // 異なるフォーマットの場合は変換する☟
            if (softwareBitmap.BitmapPixelFormat != BitmapPixelFormat.Bgra8 ||
                softwareBitmap.BitmapAlphaMode == BitmapAlphaMode.Straight)
            {
                softwareBitmap = SoftwareBitmap.Convert(softwareBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied);
            }
            // ImageコントロールにはSoftwareBitmapSourceを渡す
            var source = new SoftwareBitmapSource();
            await source.SetBitmapAsync(softwareBitmap);

            this.Image1.Source = source;

            // バーコード読み取り
            ZXing.BarcodeReader _reader
                = new ZXing.BarcodeReader
                {
                AutoRotate = true,
                Options    = { TryHarder = true }
                };
            // UWPではSoftwareBitmapかWriteableBitmapを渡す
            //ZXing.Result result = _reader.Decode(softwareBitmap);
            // ☟別スレッドでやるときも、作成済みのSoftwareBitmapインスタンスを渡してよい
            ZXing.Result result
                = await Task.Run(() => _reader.Decode(softwareBitmap));

            if (result != null)
            {
                ShowResult(result);
            }
        }
        private string ToImage(HttpPostedFile file)
        {
            var reader = new ZXing.BarcodeReader();

            return(reader.Decode(new Bitmap(System.Drawing.Image.FromStream(file.InputStream))).Text);
        }
        private void InitializeDecoder(PhotoConfirmationCapturedEventArgs photoResult)
        {
            _image = new BitmapImage();
            _reader = new ZXing.BarcodeReader();

            Task.Run(delegate()
            {
            _reader.Options.TryHarder = false;
            _reader.TryInverted = false;
            _reader.AutoRotate = false;
            _image.SetSource(photoResult.Frame);
            ZXing.Result result = _reader.Decode(new WriteableBitmap(_image.PixelWidth, _image.PixelHeight));
            if (result != null)
            {
                AddBarcodeToResults(result);
            }
            else
            {
                SetActivityMessage("No barcode detected", false);
            }
            }).ConfigureAwait(false).GetAwaiter().GetResult();
        }