Windows phone 8.1 使用Zxing扫描windows phone 8.1应用商店应用程序的条形码每次都不起作用

Windows phone 8.1 使用Zxing扫描windows phone 8.1应用商店应用程序的条形码每次都不起作用,windows-phone-8.1,Windows Phone 8.1,我试过使用静态图像,效果很好,但当我使用照相机时,条形码阅读器。解码大部分时间返回空值,只有很少一次我得到结果。我也尝试过聚焦,但问题是一样的 Xaml code: <Grid> <Canvas Margin="0" Height="400" Width="600" HorizontalAlignment="Center"

我试过使用静态图像,效果很好,但当我使用照相机时,条形码阅读器。解码大部分时间返回空值,只有很少一次我得到结果。我也尝试过聚焦,但问题是一样的

Xaml code:


    <Grid>
        <Canvas Margin="0" 
                Height="400" 
                Width="600" 
                HorizontalAlignment="Center" 
                VerticalAlignment="Center">
            <CaptureElement x:Name="VideoCapture" Stretch="UniformToFill"  />
            <Image x:Name="CaptureImage" Width="480" Height="640" Visibility="Collapsed" />
        </Canvas>
        <TextBlock x:Name="Error" VerticalAlignment="Bottom" FontSize="32" Width="480" TextAlignment="Center" Margin="0,400,0,37" />
        <TextBlock x:Name="ScanResult" VerticalAlignment="Bottom" TextAlignment="Center" FontSize="32" Width="480"/>
    </Grid> 



CS.code

      private readonly MediaCapture _mediaCapture = new MediaCapture();
        private Result _result;
        private bool _navBack;
        public Scan1xaml()
        {
            this.InitializeComponent();
            this.NavigationCacheMode = NavigationCacheMode.Required;
        }

        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.
        /// This parameter is typically used to configure the page.</param>
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            InitCameraPreviewAction();

            //await DecodeStaticResource();
            //return;
        }

        private async void InitCameraPreviewAction()
        {
#if _TestCatpureImage_
  await DecodeStaticResource();
            return;
#endif
            var canUseCamera = true;
            try
            {
                var cameras = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);
                if (cameras.Count < 1)
                {
                    Error.Text = "No camera found, decoding static image";
                    await DecodeStaticResource();
                    return;
                }
                MediaCaptureInitializationSettings settings;
                if (cameras.Count == 1)
                {
                    settings = new MediaCaptureInitializationSettings { VideoDeviceId = cameras[0].Id }; // 0 => front, 1 => back
                }
                else
                {
                    settings = new MediaCaptureInitializationSettings { VideoDeviceId = cameras[1].Id }; // 0 => front, 1 => back
                }
                await _mediaCapture.InitializeAsync(settings);


                FocusSettings focusSetting = new FocusSettings()
                {
                    Mode = FocusMode.Continuous,                   
                    AutoFocusRange = AutoFocusRange.Normal,
                    DisableDriverFallback = false,                    
                    WaitForFocus = true
                };

                _mediaCapture.VideoDeviceController.FocusControl.Configure(focusSetting);
                await _mediaCapture.VideoDeviceController.ExposureControl.SetAutoAsync(true);


                SetResolution();
                VideoCapture.Source = _mediaCapture;
                try
                {
                    //should update CurrentOrientation
                    _mediaCapture.SetPreviewRotation(VideoRotationLookup(DisplayProperties.CurrentOrientation, false));
                    //set flash close
                    _mediaCapture.VideoDeviceController.FlashControl.Enabled = false;
                }
                catch (Exception e)
                {
                    App.WpLog(e);
                }

                await _mediaCapture.StartPreviewAsync();
                var count = 0;

                while (_result == null && !_navBack)
                {
                    count++;
                    App.WpLog(count);
                    var photoStorageFile = await KnownFolders.PicturesLibrary.CreateFileAsync("scan.jpg", CreationCollisionOption.GenerateUniqueName);
                    await _mediaCapture.CapturePhotoToStorageFileAsync(ImageEncodingProperties.CreateJpeg(), photoStorageFile);

                    var stream = await photoStorageFile.OpenReadAsync();
                    // initialize with 1,1 to get the current size of the image
                    var writeableBmp = new WriteableBitmap(1, 1);
                    writeableBmp.SetSource(stream);
                    // and create it again because otherwise the WB isn't fully initialized and decoding
                    // results in a IndexOutOfRange
                    writeableBmp = new WriteableBitmap(writeableBmp.PixelWidth, writeableBmp.PixelHeight);
                    stream.Seek(0);
                    writeableBmp.SetSource(stream);

                    _result = ScanBitmap(writeableBmp);

                    await photoStorageFile.DeleteAsync(StorageDeleteOption.PermanentDelete);
                }

                await _mediaCapture.StopPreviewAsync();
                VideoCapture.Visibility = Visibility.Collapsed;
                CaptureImage.Visibility = Visibility.Visible;
                ScanResult.Text = _result.Text;

            }
            catch (Exception ex)
            {
                Error.Text = ex.Message;
                App.WpLog("use camera fail: " + ex);
                canUseCamera = false;
            }

            if (canUseCamera || _navBack) return;
            //tips error 
        }

        private async System.Threading.Tasks.Task DecodeStaticResource()
        {
#if _TestCatpureImage_
            var file = await KnownFolders.PicturesLibrary.GetFileAsync("scan_test.jpg");
            var image = new BitmapImage();
            image.SetSource(await file.OpenAsync(FileAccessMode.Read));
            CaptureImage.Source = image;
            CaptureImage.Visibility = Visibility.Visible; 
            return;
#else
            var file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(@"Assets\bar.png");
            //var file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(@"Assets\TestZXing.png");
            var stream = await file.OpenReadAsync();
            // initialize with 1,1 to get the current size of the image
            var writeableBmp = new WriteableBitmap(1, 1);
            writeableBmp.SetSource(stream);
            // and create it again because otherwise the WB isn't fully initialized and decoding
            // results in a IndexOutOfRange
            writeableBmp = new WriteableBitmap(writeableBmp.PixelWidth, writeableBmp.PixelHeight);
            stream.Seek(0);
            writeableBmp.SetSource(stream);
            CaptureImage.Source = writeableBmp;
            VideoCapture.Visibility = Visibility.Collapsed;
            CaptureImage.Visibility = Visibility.Visible;

            _result = ScanBitmap(writeableBmp);
            if (_result != null)
            {
                ScanResult.Text += _result.Text;
            }
            return;
#endif
        }

        private Result ScanBitmap(WriteableBitmap writeableBmp)
        {
            try
            {
                var barcodeReader = new BarcodeReader
                {
                    TryHarder = true,
                    AutoRotate = true
                };
                var result = barcodeReader.Decode(writeableBmp);

                if (result != null)
                {
                    CaptureImage.Source = writeableBmp;
                }

                return result;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private Windows.Media.Capture.VideoRotation VideoRotationLookup(
         Windows.Graphics.Display.DisplayOrientations displayOrientation,
         bool counterclockwise)
        {
            switch (displayOrientation)
            {
                case Windows.Graphics.Display.DisplayOrientations.Landscape:
                    return Windows.Media.Capture.VideoRotation.None;

                case Windows.Graphics.Display.DisplayOrientations.Portrait:
                    return (counterclockwise) ? Windows.Media.Capture.VideoRotation.Clockwise270Degrees :
                        Windows.Media.Capture.VideoRotation.Clockwise90Degrees;

                case Windows.Graphics.Display.DisplayOrientations.LandscapeFlipped:
                    return Windows.Media.Capture.VideoRotation.Clockwise180Degrees;

                case Windows.Graphics.Display.DisplayOrientations.PortraitFlipped:
                    return (counterclockwise) ? Windows.Media.Capture.VideoRotation.Clockwise90Degrees :
                        Windows.Media.Capture.VideoRotation.Clockwise270Degrees;
                default:
                    return Windows.Media.Capture.VideoRotation.None;
            }
        }

        //This is how you can set your resolution
        public async void SetResolution()
        {
            System.Collections.Generic.IReadOnlyList<IMediaEncodingProperties> res;
            res = this._mediaCapture.VideoDeviceController.GetAvailableMediaStreamProperties(MediaStreamType.VideoPreview);
            uint maxResolution = 0;
            int indexMaxResolution = 0;

            if (res.Count >= 1)
            {
                for (int i = 0; i < res.Count; i++)
                {
                    var vp = (VideoEncodingProperties)res[i];
                    App.WpLog(vp.Width + " _ " + vp.Height);
                    if (vp.Width > maxResolution)
                    {
                        indexMaxResolution = i;
                        maxResolution = vp.Width;
                        Debug.WriteLine("Resolution: " + vp.Width);
                    }
                }
                await this._mediaCapture.VideoDeviceController.SetMediaStreamPropertiesAsync(MediaStreamType.VideoPreview, res[res.Count - 1]);
            }
        }

        protected override async void OnNavigatingFrom(NavigatingCancelEventArgs e)
        {
            try
            {
                _navBack = true;
                VideoCapture.Visibility = Visibility.Collapsed;
                await _mediaCapture.StopPreviewAsync();
                VideoCapture.Source = null;
            }
            catch (Exception exception)
            {
                App.WpLog(exception);
            }
        }
Xaml代码:
编码
私有只读媒体捕获_MediaCapture=new MediaCapture();
私人结果(u Result);;
私人住宅;
公共扫描1xAML()
{
this.InitializeComponent();
this.NavigationCacheMode=NavigationCacheMode.Required;
}
/// 
///当此页面即将显示在框架中时调用。
/// 
///描述如何到达此页面的事件数据。
///此参数通常用于配置页面。
受保护的异步重写无效OnNavigatedTo(NavigationEventArgs e)
{
InitCameraPreviewAction();
//等待解码静态资源();
//返回;
}
私有异步void InitCameraPreviewAction()
{
#if\u TestCatpureImage_
等待解码静态资源();
回来
#恩迪夫
var canUseCamera=true;
尝试
{
var摄像机=等待设备信息.FindAllAsync(DeviceClass.VideoCapture);
如果(照相机计数<1)
{
错误。Text=“未找到摄像头,正在解码静态图像”;
等待解码静态资源();
回来
}
MediaCaptureInitializationSettings;
如果(cameras.Count==1)
{
settings=new MediaCaptureInitializationSettings{VideoDeviceId=cameras[0].Id};//0=>前,1=>后
}
其他的
{
settings=new MediaCaptureInitializationSettings{VideoDeviceId=cameras[1].Id};//0=>front,1=>back
}
等待mediaCapture.InitializeAsync(设置);
聚焦设置聚焦设置=新聚焦设置()
{
模式=焦点模式。连续,
自动聚焦范围=自动聚焦范围。正常,
DisableDriverCallback=false,
WaitForFocus=true
};
_mediaCapture.VideoDeviceController.FocusControl.Configure(调焦设置);
Wait_mediaCapture.VideoDeviceController.ExposureControl.SetAutoAsync(true);
SetResolution();
VideoCapture.Source=\u mediaCapture;
尝试
{
//应该更新当前方向
_mediaCapture.SetPreviewRotation(VideoRotationLookup(DisplayProperties.CurrentOrientation,false));
//设置闪光灯关闭
_mediaCapture.VideoDeviceController.FlashControl.Enabled=false;
}
捕获(例外e)
{
附录WpLog(e);
}
等待_mediaCapture.startPreviewSync();
var计数=0;
while(_result==null&&!_navBack)
{
计数++;
App.WpLog(计数);
var photoStorageFile=await KnownFolders.PicturesLibrary.CreateFileAsync(“scan.jpg”,CreationCollisionOption.GenerateUniqueName);
wait_mediaCapture.CapturePhotoToStorageFileAsync(ImageEncodingProperties.CreateJpeg(),photoStorageFile);
var stream=wait photoStorageFile.OpenReadAsync();
//使用1,1初始化以获取图像的当前大小
var writeableBmp=新的WriteableBitmap(1,1);
writeableBmp.SetSource(流);
//并再次创建它,因为否则WB没有完全初始化和解码
//结果是一个指数崩盘
writeableBmp=新的WriteableBitmap(writeableBmp.PixelWidth,writeableBmp.PixelHeight);
stream.Seek(0);
writeableBmp.SetSource(流);
_结果=扫描位图(可写位图);
等待photoStorageFile.DeleteAsync(StorageDeleteOption.PermanentDelete);
}
等待_mediaCapture.stoppereviewasync();
VideoCapture.Visibility=Visibility.Collapsed;
CaptureImage.Visibility=可见性.Visibility;
ScanResult.Text=_result.Text;
}
捕获(例外情况除外)
{
错误。文本=例如消息;
App.WpLog(“使用摄像头失败:+ex”);
canUseCamera=false;
}
如果(可使用摄像头| | | | |导航)返回;
//提示错误
}
专用异步System.Threading.Tasks.Task DecodeStaticResource()
{
#if\u TestCatpureImage_
var file=await KnownFolders.PicturesLibrary.GetFileAsync(“scan_test.jpg”);
var image=新的位图图像();
SetSource(wait file.OpenAsync(FileAccessMode.Read));
CaptureImage.Source=图像;
CaptureImage.Visibility=可见性.Visibility;
回来
#否则
var file=await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(@“Assets\bar.png”);
//var file=wait Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(@“Assets\TestZXing.png”);
var stream=await file.OpenReadAsync();
//使用1,1初始化以获取图像的当前大小
var writeableBmp=新的WriteableBitmap(1,1);
writeableBmp.SetSource(流);
//