二维码扫描的实现,简单的来说可以分三步走:“成像”、“截图”与“识别”。
UWP开发中,最常用的媒体工具非MediaCapture莫属了,下面就来简单介绍一下如何利用MediaCapture来实现扫描和截图并且利用Zxing识别二维码,以及会遇到的问题和需要注意的地方。
1. 初始化与成像
1 private async void InitMediaCaptureAsync() 2 { 3 //寻找后置摄像头 4 var allVideoDevices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture); 5 var cameraDevice = allVideoDevices.FirstOrDefault(x => x.EnclosureLocation != null && x.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Back); 6 7 if (cameraDevice == null) 8 { 9 Debug.WriteLine("No camera device found!"); 10 11 return; 12 } 13 14 var settings = new MediaCaptureInitializationSettings 15 { 16 StreamingCaptureMode = StreamingCaptureMode.Video, 17 //必须,否则截图的时候会很卡很慢 18 PhotoCaptureSource = PhotoCaptureSource.VideoPreview, 19 VideoDeviceId = cameraDevice.Id 20 }; 21 22 _mediaCapture = new MediaCapture(); 23 24 try 25 { 26 await _mediaCapture.InitializeAsync(settings); 27 _initialized = true;//初始化成功 28 } 29 catch (UnauthorizedAccessException) 30 { 31 Debug.WriteLine("The app was denied access to the camera"); 32 } 33 catch (Exception ex) 34 { 35 Debug.WriteLine("Exception when initializing MediaCapture with {0}: {1}", cameraDevice.Id, ex.ToString()); 36 } 37 38 if (_initialized) 39 { 40 var focusControl = _mediaCapture.VideoDeviceController.FocusControl; 41 42 if (focusControl.Supported) 43 { 44 var focusSettings = new FocusSettings() 45 { 46 Mode = focusControl.SupportedFocusModes.FirstOrDefault(f => f == FocusMode.Continuous), 47 DisableDriverFallback = true, 48 AutoFocusRange = focusControl.SupportedFocusRanges.FirstOrDefault(f => f == AutoFocusRange.FullRange), 49 Distance = focusControl.SupportedFocusDistances.FirstOrDefault(f => f == ManualFocusDistance.Nearest) 50 }; 51 52 //设置聚焦,最好使用FocusMode.Continuous,否则影响截图会很模糊,不利于识别 53 focusControl.Configure(focusSettings); 54 } 55 56 captureElement.Source = _mediaCapture; 57 captureElement.FlowDirection = FlowDirection.LeftToRight; 58 59 try 60 { 61 await _mediaCapture.StartPreviewAsync(); 62 _previewing = true; 63 } 64 catch (Exception ex) 65 { 66 Debug.WriteLine("Exception when starting the preview: {0}", ex.ToString()); 67 } 68 69 if (_previewing) 70 { 71 try 72 { 73 if (_mediaCapture.VideoDeviceController.FlashControl.Supported) 74 { 75 //关闭闪光灯 76 _mediaCapture.VideoDeviceController.FlashControl.Enabled = false; 77 } 78 } 79 catch 80 { 81 } 82 83 if (focusControl.Supported) 84 { 85 //开始聚焦 86 await focusControl.FocusAsync(); 87 } 88 } 89 } 90 }