[C#/WINUI3/COMMUNITY TOOLKIT/.NET8] CameraHelper 클래스 : 카메라 이미지 캡처하기 (오류)
■ CameraHelper 클래스를 사용해 카메라 이미지를 캡처하는 방법을 보여준다. ※ 아래 코드를 실행하면 카메라 이미지가 캡처가 되는데 버튼을 자주 클릭해야 했다. ▶
■ CameraHelper 클래스를 사용해 카메라 이미지를 캡처하는 방법을 보여준다. ※ 아래 코드를 실행하면 카메라 이미지가 캡처가 되는데 버튼을 자주 클릭해야 했다. ▶
■ MediaPlayerElement 엘리먼트에서 MediaCapture 객체를 사용해 카메라 캡처하는 방법을 보여준다. ▶ ExpandToFillGrid.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
using Windows.Foundation; using Microsoft.UI.Xaml.Controls; namespace TestProject { /// <summary> /// 전체 확장 그리드 /// </summary> public class ExpandToFillGrid : Grid { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Protected #region 측정하기 (오버라이드) - MeasureOverride(availableSize) /// <summary> /// 측정하기 (오버라이드) /// </summary> /// <param name="availableSize">이용 가능 크기</param> /// <returns>측정 크기</returns> protected override Size MeasureOverride(Size availableSize) { Size desiredSize = base.MeasureOverride(new Size(availableSize.Width, 100)); return desiredSize; } #endregion } } |
▶ MainWindow.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
<?xml version="1.0" encoding="utf-8"?> <Window x:Class="TestProject.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:TestProject" Title="TestProject"> <Grid Margin="10"> <Grid.ColumnDefinitions> <ColumnDefinition Width="*" /> <ColumnDefinition Width="Auto" /> </Grid.ColumnDefinitions> <Grid MinWidth="400" MinHeight="300" RowSpacing="10" ColumnSpacing="4" RowDefinitions="Auto,*" ColumnDefinitions="*,100"> <TextBlock Name="displayNameTextBlock" Grid.Row="0" Grid.Column="0" VerticalAlignment="Center" /> <MediaPlayerElement Name="mediaPlayerElement" Grid.Row="1" Grid.Column="0" Stretch="Uniform" AutoPlay="True" /> <TextBlock Name="captureTextBlock" Grid.Row="0" Grid.Column="1" VerticalAlignment="Center" Text="Captured : " Visibility="Collapsed" /> <Grid Name="captureGrid" Grid.Row="1" Grid.Column="1" Margin="5 0 5 0"> <ScrollViewer VerticalScrollMode="Enabled"> <StackPanel Name="captureImageStackPanel" Spacing="2" /> </ScrollViewer> </Grid> </Grid> <StackPanel Grid.Column="1" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="5 0 0 0"> <ToggleSwitch Name="mirrorTogglePreviewSwitch" Header="Mirror preview" IsOn="False" ToolTipService.ToolTip="Mirrors only the preview, not captured photos" /> <Button Name="captureButton" Content="Capture Photo" /> </StackPanel> </Grid> </Window> |
▶ MainWindow.xaml.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 |
using System; using System.Collections.Generic; using System.Linq; using Microsoft.UI.Xaml; using Microsoft.UI.Xaml.Controls; using Microsoft.UI.Xaml.Media; using Microsoft.UI.Xaml.Media.Imaging; using Windows.Foundation; using Windows.Media.Capture; using Windows.Media.Capture.Frames; using Windows.Media.Core; using Windows.Media.MediaProperties; using Windows.Storage.Streams; namespace TestProject { /// <summary> /// 메인 윈도우 /// </summary> public sealed partial class MainWindow : Window { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 미디어 프레임 소스 그룹 /// </summary> private MediaFrameSourceGroup mediaFrameSourceGroup; /// <summary> /// 미디어 캡처 /// </summary> private MediaCapture mediaCapture; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - MainWindow() /// <summary> /// 생성자 /// </summary> public MainWindow() { InitializeComponent(); StartMediaPlayerElement(); ExpandToFillGrid expandToFillGrid = new ExpandToFillGrid(); ScrollViewer scrollViewer = this.captureGrid.Children[0] as ScrollViewer; this.captureGrid.Children.Remove(scrollViewer); this.captureGrid.Children.Add(expandToFillGrid); expandToFillGrid.Children.Add(scrollViewer); this.mirrorTogglePreviewSwitch.Toggled += mirrorPreviewToggleSwitch_Toggled; this.captureButton.Click += captureButton_Click; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Private //////////////////////////////////////////////////////////////////////////////// Event #region Mirror preview 토글 스위치 토글시 처리하기 - mirrorPreviewToggleSwitch_Toggled(sender, e) /// <summary> /// Mirror preview 토글 스위치 토글시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void mirrorPreviewToggleSwitch_Toggled(object sender, RoutedEventArgs e) { if(this.mirrorTogglePreviewSwitch.IsOn) { this.mediaPlayerElement.RenderTransform = new ScaleTransform() { ScaleX = -1 }; this.mediaPlayerElement.RenderTransformOrigin = new Point(0.5, 0.5); } else { this.mediaPlayerElement.RenderTransform = null; } } #endregion #region Capture 버튼 클릭시 처리하기 - captureButton_Click(sender, e) /// <summary> /// Capture 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private async void captureButton_Click(object sender, RoutedEventArgs e) { ImageEncodingProperties properties = ImageEncodingProperties.CreateJpeg(); InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream(); await this.mediaCapture.CapturePhotoToStreamAsync(properties, stream); stream.Seek(0); BitmapImage bitmapImage = new BitmapImage(); await bitmapImage.SetSourceAsync(stream); Image image = new Image() { Source = bitmapImage }; this.captureImageStackPanel.Children.Insert(0, image); this.captureTextBlock.Visibility = Visibility.Visible; } #endregion //////////////////////////////////////////////////////////////////////////////// Function #region 미디어 플레이어 엘리먼트 시작하기 - StartMediaPlayerElement() /// <summary> /// 미디어 플레이어 엘리먼트 시작하기 /// </summary> async private void StartMediaPlayerElement() { IReadOnlyList<MediaFrameSourceGroup> mediaFrameSourceGroupList = await MediaFrameSourceGroup.FindAllAsync(); if(mediaFrameSourceGroupList.Count == 0) { this.displayNameTextBlock.Text = "No camera devices found."; return; } this.mediaFrameSourceGroup = mediaFrameSourceGroupList.First(); this.displayNameTextBlock.Text = "Viewing : " + this.mediaFrameSourceGroup.DisplayName; this. mediaCapture = new MediaCapture(); MediaCaptureInitializationSettings settings = new MediaCaptureInitializationSettings() { SourceGroup = this.mediaFrameSourceGroup, SharingMode = MediaCaptureSharingMode.SharedReadOnly, StreamingCaptureMode = StreamingCaptureMode.Video, MemoryPreference = MediaCaptureMemoryPreference.Cpu }; await this.mediaCapture.InitializeAsync(settings); MediaFrameSource mediaFrameSource = this.mediaCapture.FrameSources[this.mediaFrameSourceGroup.SourceInfos[0].Id]; this.mediaPlayerElement.Source = MediaSource.CreateFromMediaFrameSource(mediaFrameSource); } #endregion } } |
TestProject.zip
■ IMediaPicker 인터페이스의 PickPhotoAsync 메소드를 사용해 갤러리 사진을 구하는 방법을 보여준다. ▶ Platforms/Android/AndroidManifest.xml
1 2 3 4 5 6 7 8 9 10 11 12 |
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android"> <application android:allowBackup="true" android:icon="@mipmap/appicon" android:roundIcon="@mipmap/appicon_round" android:supportsRtl="true" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> </manifest> |
▶ MainPage.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<?xml version="1.0" encoding="utf-8" ?> <ContentPage x:Class="TestProject.MainPage" xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"> <StackLayout HorizontalOptions="Center" VerticalOptions="Center" Spacing="10"> <Border HorizontalOptions="Center" StrokeThickness="5" Stroke="Gray"> <Border.StrokeShape> <Rectangle /> </Border.StrokeShape> <Image x:Name="image" WidthRequest="300" HeightRequest="300" Aspect="Fill" /> </Border> <Button x:Name="pickButton" HorizontalOptions="Center" Text="사진 파일 선택하기" /> </StackLayout> </ContentPage> |
▶ MainPage.xaml.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
namespace TestProject; /// <summary> /// 메인 페이지 /// </summary> public partial class MainPage : ContentPage { //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - MainPage() /// <summary> /// 생성자 /// </summary> public MainPage() { InitializeComponent(); this.pickButton.Clicked += pickButton_Clicked; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Private #region 사진 파일 선택하기 버튼 클릭시 처리하기 - pickButton_Clicked(sender, e) /// <summary> /// 사진 파일 선택하기 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private async void pickButton_Clicked(object sender, EventArgs e) { if(MediaPicker.Default.IsCaptureSupported) { FileResult fileResult = await MediaPicker.Default.PickPhotoAsync(); if(fileResult != null) { Stream stream = await fileResult.OpenReadAsync(); this.image.Source = ImageSource.FromStream(() => stream); } } } #endregion } |
TestProject.zip
■ IMediaPicker 인터페이스의 CapturePhotoAsync 메소드를 사용해 사진을 촬영하는 방법을 보여준다. (ANDROID) ▶ Platforms/Andriod/Resources/AndroidManifest.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android"> <application android:allowBackup="true" android:icon="@mipmap/appicon" android:roundIcon="@mipmap/appicon_round" android:supportsRtl="true"></application> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.CAMERA" /> <queries> <intent> <action android:name="android.media.action.IMAGE_CAPTURE" /> </intent> </queries> </manifest> |
▶ MainPage.xaml
1 2 3 4 5 6 7 8 9 10 11 |
<?xml version="1.0" encoding="utf-8" ?> <ContentPage x:Class="TestProject.MainPage" xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"> <Button x:Name="takeButton" HorizontalOptions="Center" VerticalOptions="Center" Text="사진 촬영하기" /> </ContentPage> |
▶ MainPage.xaml.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
namespace TestProject; /// <summary> /// 메인 페이지 /// </summary> public partial class MainPage : ContentPage { //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - MainPage() /// <summary> /// 생성자 /// </summary> public MainPage() { InitializeComponent(); this.takeButton.Clicked += takeButton_Clicked; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Private #region 사진 촬영하기 버튼 클릭시 처리하기 - takeButton_Clicked(sender, e) /// <summary> /// 사진 촬영하기 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private async void takeButton_Clicked(object sender, EventArgs e) { if(MediaPicker.Default.IsCaptureSupported) { FileResult fileResult = await MediaPicker.Default.CapturePhotoAsync(); if(fileResult != null) { string filePath = Path.Combine(FileSystem.CacheDirectory, fileResult.FileName); using Stream stream = await fileResult.OpenReadAsync(); using FileStream fileStream = File.OpenWrite(filePath); await stream.CopyToAsync(fileStream); } } } #endregion } |
TestProject.zip
■ 카메라를 사용해 얼굴을 탐지하는 방법을 보여준다. ▶ MainPage.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 |
<Page x:Class="TestProject.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" FontFamily="나눔고딕코딩" FontSize="16"> <Page.Resources> <SolidColorBrush x:Key="TranslucentBlackBrushKey" Color="Black" Opacity="0.3" /> </Page.Resources> <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> <Grid.Resources> <Style TargetType="Button"> <Setter Property="Margin" Value="10 40" /> <Setter Property="MinWidth" Value="80" /> <Setter Property="MinHeight" Value="80" /> <Setter Property="Foreground" Value="White" /> <Setter Property="BorderBrush" Value="White" /> <Setter Property="Background" Value="{StaticResource TranslucentBlackBrushKey}" /> <Setter Property="RenderTransformOrigin" Value="0.5 0.5" /> </Style> <Style TargetType="Viewbox"> <Setter Property="MaxWidth" Value="40" /> <Setter Property="MaxHeight" Value="40" /> </Style> </Grid.Resources> <CaptureElement Name="previewCaptureElement" Stretch="Uniform" /> <Canvas> <Canvas Name="faceCanvas" RenderTransformOrigin="0.5 0.5" /> </Canvas> <StackPanel HorizontalAlignment="Right" VerticalAlignment="Center"> <Button Name="photoButton" IsEnabled="False" Click="photoButton_Click"> <Viewbox> <SymbolIcon Symbol="Camera" /> </Viewbox> </Button> <Button Name="videoButton" IsEnabled="False" Click="videoButton_Click"> <Grid> <Ellipse Name="startVideoEllipse" Width="20" Height="20" Fill="Red" /> <Rectangle Name="stopVideoRectangle" Width="20" Height="20" Fill="White" Visibility="Collapsed" /> </Grid> </Button> </StackPanel> <Button Name="faceDetectionButton" IsEnabled="False" Click="faceDetectionButton_Click"> <Viewbox> <Grid> <SymbolIcon Name="faceDetectionSymbolIcon1" Symbol="Contact2" Visibility="Collapsed" /> <SymbolIcon Name="faceDetectionSymbolIcon2" Symbol="Contact" Visibility="Visible" /> </Grid> </Viewbox> </Button> </Grid> </Page> |
▶ MainPage.xaml.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 |
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Windows.ApplicationModel; using Windows.Devices.Enumeration; using Windows.Devices.Sensors; using Windows.Foundation; using Windows.Foundation.Metadata; using Windows.Graphics.Display; using Windows.Graphics.Imaging; using Windows.Media; using Windows.Media.Core; using Windows.Media.Capture; using Windows.Media.FaceAnalysis; using Windows.Media.MediaProperties; using Windows.Phone.UI.Input; using Windows.Storage; using Windows.Storage.FileProperties; using Windows.Storage.Streams; using Windows.System.Display; using Windows.UI; using Windows.UI.Core; using Windows.UI.ViewManagement; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; using Windows.UI.Xaml.Shapes; namespace TestProject { /// <summary> /// 메인 페이지 /// </summary> public sealed partial class MainPage : Page { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 회전 키 GUID /// </summary> private static readonly Guid _rotationKeyGUID = new Guid("C380465D-2271-428C-9B83-ECEA3B4A85C1"); #endregion ////////////////////////////////////////////////////////////////////////////////////////// Instance //////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 디스플레이 정보 /// </summary> private readonly DisplayInformation displayInformation = DisplayInformation.GetForCurrentView(); /// <summary> /// 단순 방향 센서 /// </summary> private readonly SimpleOrientationSensor orientationSensor = SimpleOrientationSensor.GetDefault(); /// <summary> /// 장치 단순 방향 /// </summary> private SimpleOrientation deviceOrientation = SimpleOrientation.NotRotated; /// <summary> /// 디스플레이 방향 /// </summary> private DisplayOrientations displayOrientations = DisplayOrientations.Portrait; /// <summary> /// 캡처 저장소 폴더 /// </summary> private StorageFolder captureStorageFolder = null; /// <summary> /// 디스플레이 요청 /// </summary> private readonly DisplayRequest displayRequest = new DisplayRequest(); /// <summary> /// 시스템 미디어 전송 컨트롤 /// </summary> private readonly SystemMediaTransportControls systemMediaTransportControls = SystemMediaTransportControls.GetForCurrentView(); /// <summary> /// 미디어 캡처 /// </summary> private MediaCapture mediaCapture; /// <summary> /// 미디어 인코딩 속성 /// </summary> private IMediaEncodingProperties mediaEncodingProperties; /// <summary> /// 초기화 여부 /// </summary> private bool isInitialized; /// <summary> /// 레코딩 여부 /// </summary> private bool isRecording; /// <summary> /// 미리보기 미러링 여부 /// </summary> private bool mirroringPreview; /// <summary> /// 외부 카메라 여부 /// </summary> private bool externalCamera; /// <summary> /// 얼굴 탐지 효과 /// </summary> private FaceDetectionEffect faceDetectionEffect; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - MainPage() /// <summary> /// 생성자 /// </summary> public MainPage() { InitializeComponent(); #region 윈도우 크기를 설정한다. double width = 800d; double height = 600d; double dpi = (double)DisplayInformation.GetForCurrentView().LogicalDpi; ApplicationView.PreferredLaunchWindowingMode = ApplicationViewWindowingMode.PreferredLaunchViewSize; Size windowSize = new Size(width * 96d / dpi, height * 96d / dpi); ApplicationView.PreferredLaunchViewSize = windowSize; Window.Current.Activate(); ApplicationView.GetForCurrentView().TryResizeView(windowSize); #endregion #region 윈도우 제목을 설정한다. ApplicationView.GetForCurrentView().Title = "카메라를 사용해 얼굴 탐지하기"; #endregion NavigationCacheMode = NavigationCacheMode.Disabled; Application.Current.Suspending += Application_Suspending; Application.Current.Resuming += Application_Resuming; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Protected #region 탐색되는 경우 처리하기 - OnNavigatedTo(e) /// <summary> /// 탐색되는 경우 처리하기 /// </summary> /// <param name="e">이벤트 인자</param> protected override async void OnNavigatedTo(NavigationEventArgs e) { await SetupUIAsync(); await InitializeCameraAsync(); } #endregion #region 탐색하는 경우 처리하기 - OnNavigatingFrom(e) /// <summary> /// 탐색하는 경우 처리하기 /// </summary> /// <param name="e">이벤트 인자</param> protected override async void OnNavigatingFrom(NavigatingCancelEventArgs e) { await CleanupCameraAsync(); await CleanupUIAsync(); } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Private //////////////////////////////////////////////////////////////////////////////// Event #region 애플리케이션 일시 중단시 처리하기 - Application_Suspending(sender, e) /// <summary> /// 애플리케이션 일시 중단시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private async void Application_Suspending(object sender, SuspendingEventArgs e) { if(Frame.CurrentSourcePageType == typeof(MainPage)) { SuspendingDeferral deferral = e.SuspendingOperation.GetDeferral(); await CleanupCameraAsync(); await CleanupUIAsync(); deferral.Complete(); } } #endregion #region 애플리케이션 재개시 처리하기 - Application_Resuming(sender, e) /// <summary> /// 애플리케이션 재개시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private async void Application_Resuming(object sender, object e) { if(Frame.CurrentSourcePageType == typeof(MainPage)) { await SetupUIAsync(); await InitializeCameraAsync(); } } #endregion #region 단순 방향 센서 방향 변경시 처리하기 - orientationSensor_OrientationChanged(sender, e) /// <summary> /// 단순 방향 센서 방향 변경시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private async void orientationSensor_OrientationChanged ( SimpleOrientationSensor sender, SimpleOrientationSensorOrientationChangedEventArgs e ) { if(e.Orientation != SimpleOrientation.Faceup && e.Orientation != SimpleOrientation.Facedown) { this.deviceOrientation = e.Orientation; await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => UpdateButtonOrientation()); } } #endregion #region 디스플레이 정보 방향 변경시 처리하기 - displayInformation_OrientationChanged(sender, e) /// <summary> /// 디스플레이 정보 방향 변경시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> /// <remarks> /// 이 이벤트는 SetupUIAsync 함수에 설정된 DisplayInformation.AutoRotationPreferences 값이 적용되지 않을 때 /// 페이지가 회전될 때 발생한다. /// </remarks> private async void displayInformation_OrientationChanged(DisplayInformation sender, object e) { this.displayOrientations = sender.CurrentOrientation; if(this.mediaEncodingProperties != null) { await SetPreviewRotationAsync(); } await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => UpdateButtonOrientation()); } #endregion #region 미디어 캡처 레코드 제한 초과시 처리하기 - mediaCapture_RecordLimitationExceeded(sender) /// <summary> /// 미디어 캡처 레코드 제한 초과시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> private async void mediaCapture_RecordLimitationExceeded(MediaCapture sender) { // 녹음을 중지해야 하며 앱에서 녹음을 완료할 것으로 예상되는 알림이다. await StopRecordingAsync(); await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => UpdateCaptureControls()); } #endregion #region 미디어 캡처 실패시 처리하기 - mediaCapture_Failed(sender, e) /// <summary> /// 미디어 캡처 실패시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private async void mediaCapture_Failed(MediaCapture sender, MediaCaptureFailedEventArgs e) { await CleanupCameraAsync(); await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => UpdateCaptureControls()); } #endregion #region 시스템 미디어 전송 컨트롤 속성 변경시 처리하기 - systemMediaTransportControls_PropertyChanged(sender, e) /// <summary> /// 시스템 미디어 전송 컨트롤 속성 변경시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> /// <remarks> /// 앱이 최소화되는 경우 이 메소드는 미디어 속성 변경 이벤트를 처리한다. /// 앱이 음소거 알림을 수신하면 더 이상 포그라운드에 있지 않는다. /// </remarks> private async void systemMediaTransportControls_PropertyChanged ( SystemMediaTransportControls sender, SystemMediaTransportControlsPropertyChangedEventArgs e ) { await Dispatcher.RunAsync ( CoreDispatcherPriority.Normal, async () => { // 이 페이지가 현재 표시되고 있는 경우에만 이 이벤트를 처리한다. if ( e.Property == SystemMediaTransportControlsProperty.SoundLevel && Frame.CurrentSourcePageType == typeof(MainPage) ) { // 앱이 음소거되고 있는지 확인한다. 그렇다면 최소화하고 있다. // 그렇지 않으면 초기화되지 않은 경우 초점이 맞춰진다. if(sender.SoundLevel == SoundLevel.Muted) { await CleanupCameraAsync(); } else if (!this.isInitialized) { await InitializeCameraAsync(); } } } ); } #endregion #region 얼굴 탐지 효과 얼굴 탐지시 처리하기 - faceDetectionEffect_FaceDetected(sender, e) /// <summary> /// 얼굴 탐지 효과 얼굴 탐지시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private async void faceDetectionEffect_FaceDetected(FaceDetectionEffect sender, FaceDetectedEventArgs e) { await Dispatcher.RunAsync ( CoreDispatcherPriority.Normal, () => HighlightDetectedFaces(e.ResultFrame.DetectedFaces) ); } #endregion #region 하드웨어 버튼 카메라 PRESS 처리하기 - HardwareButtons_CameraPressed(sender, e) /// <summary> /// 하드웨어 버튼 카메라 PRESS 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private async void HardwareButtons_CameraPressed(object sender, CameraEventArgs e) { await TakePhotoAsync(); } #endregion #region 사진 버튼 클릭시 처리하기 - photoButton_Click(sender, e) /// <summary> /// 사진 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private async void photoButton_Click(object sender, RoutedEventArgs e) { await TakePhotoAsync(); } #endregion #region 비디오 버튼 클릭시 처리하기 - videoButton_Click(sender, e) /// <summary> /// 비디오 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private async void videoButton_Click(object sender, RoutedEventArgs e) { if(!this.isRecording) { await StartRecordingAsync(); } else { await StopRecordingAsync(); } UpdateCaptureControls(); } #endregion #region 얼굴 탐지 버튼 클릭시 처리하기 - faceDetectionButton_Click(sender, e) /// <summary> /// 얼굴 탐지 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private async void faceDetectionButton_Click(object sender, RoutedEventArgs e) { if(this.faceDetectionEffect == null || !this.faceDetectionEffect.Enabled) { this.faceCanvas.Children.Clear(); await CreateFaceDetectionEffectAsync(); } else { await CleanUpFaceDetectionEffectAsync(); } UpdateCaptureControls(); } #endregion //////////////////////////////////////////////////////////////////////////////// Function #region 카메라 방향 구하기 - GetCameraOrientation() /// <summary> /// 카메라 방향 구하기 /// </summary> /// <returns>카메라 방향</returns> /// <remarks> /// 카메라가 외부에 있는지 또는 사용자를 향하고 있는지를 고려하여 장치 방향에서 현재 카메라 방향을 계산한다. /// </remarks> private SimpleOrientation GetCameraOrientation() { if(this.externalCamera) { return SimpleOrientation.NotRotated; } SimpleOrientation targetOrientation = this.deviceOrientation; // 세로 우선 장치에서 카메라 센서가 기본 방향에 대해 90도 오프셋으로 장착된다는 사실을 고려한다. if(this.displayInformation.NativeOrientation == DisplayOrientations.Portrait) { switch(targetOrientation) { case SimpleOrientation.Rotated90DegreesCounterclockwise : targetOrientation = SimpleOrientation.NotRotated; break; case SimpleOrientation.Rotated180DegreesCounterclockwise : targetOrientation = SimpleOrientation.Rotated90DegreesCounterclockwise; break; case SimpleOrientation.Rotated270DegreesCounterclockwise : targetOrientation = SimpleOrientation.Rotated180DegreesCounterclockwise; break; case SimpleOrientation.NotRotated : targetOrientation = SimpleOrientation.Rotated270DegreesCounterclockwise; break; } } // 전면 카메라에 대해 미리보기가 미러링되는 경우 회전이 반전되어야 한다. if(this.mirroringPreview) { // 이것은 90도와 270도 경우에만 영향을 미친다. // 0도와 180도 회전은 시계 방향과 반시계 방향이 동일하기 때문이다. switch(targetOrientation) { case SimpleOrientation.Rotated90DegreesCounterclockwise : return SimpleOrientation.Rotated270DegreesCounterclockwise; case SimpleOrientation.Rotated270DegreesCounterclockwise : return SimpleOrientation.Rotated90DegreesCounterclockwise; } } return targetOrientation; } #endregion #region 사진 방향 구하기 - GetPhotoOrientation(cameraOrientation) /// <summary> /// 사진 방향 구하기 /// </summary> /// <param name="cameraOrientation">카메라 방향</param> /// <returns>사진 방향</returns> private static PhotoOrientation GetPhotoOrientation(SimpleOrientation cameraOrientation) { switch(cameraOrientation) { case SimpleOrientation.Rotated90DegreesCounterclockwise : return PhotoOrientation.Rotate90; case SimpleOrientation.Rotated180DegreesCounterclockwise : return PhotoOrientation.Rotate180; case SimpleOrientation.Rotated270DegreesCounterclockwise : return PhotoOrientation.Rotate270; case SimpleOrientation.NotRotated : default : return PhotoOrientation.Normal; } } #endregion #region 장치 방향 각도 구하기 - GetDeviceOrientationDegrees(deviceOrientation) /// <summary> /// 장치 방향 각도 구하기 /// </summary> /// <param name="deviceOrientation">장치 방향</param> /// <returns>장치 방향 각도</returns> private static int GetDeviceOrientationDegrees(SimpleOrientation deviceOrientation) { switch(deviceOrientation) { case SimpleOrientation.Rotated90DegreesCounterclockwise : return 90; case SimpleOrientation.Rotated180DegreesCounterclockwise : return 180; case SimpleOrientation.Rotated270DegreesCounterclockwise : return 270; case SimpleOrientation.NotRotated : default : return 0; } } #endregion #region 디스플레이 방향 각도 구하기 - GetDisplayOrientationDegrees(displayOrientations) /// <summary> /// 디스플레이 방향 각도 구하기 /// </summary> /// <param name="displayOrientations">디스플레이 방향</param> /// <returns>디스플레이 방향 각도 구하기</returns> private static int GetDisplayOrientationDegrees(DisplayOrientations displayOrientations) { switch(displayOrientations) { case DisplayOrientations.Portrait : return 90; case DisplayOrientations.LandscapeFlipped : return 180; case DisplayOrientations.PortraitFlipped : return 270; case DisplayOrientations.Landscape : default : return 0; } } #endregion #region 카메라 장치 정보 구하기 - GetCameraDeviceInformation(targetPanel) /// <summary> /// 카메라 장치 정보 구하기 /// </summary> /// <param name="targetPanel">타겟 패널</param> /// <returns>카메라 장치 정보</returns> private static async Task<DeviceInformation> GetCameraDeviceInformation ( Windows.Devices.Enumeration.Panel targetPanel ) { // 사진 캡처에 사용할 수 있는 장치를 가져온다. DeviceInformationCollection collection = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture); // 패널별로 원하는 카메라를 가져온다. DeviceInformation deviceInformation = collection.FirstOrDefault ( x => x.EnclosureLocation != null && x.EnclosureLocation.Panel == targetPanel ); // 원하는 패널에 장착된 장치가 없으면 처음 발견된 장치를 반환한다. return deviceInformation ?? collection.FirstOrDefault(); } #endregion #region 버튼 방향 업데이트하기 - UpdateButtonOrientation() /// <summary> /// 버튼 방향 업데이트하기 /// </summary> /// <remarks> /// 공간의 현재 장치 방향과 화면의 페이지 방향을 사용하여 컨트롤에 적용할 회전 변환을 계산합니다. /// </remarks> private void UpdateButtonOrientation() { int deviceOrientationDegrees = GetDeviceOrientationDegrees (this.deviceOrientation ); int displayOritentationDegrees = GetDisplayOrientationDegrees(this.displayOrientations); if(this.displayInformation.NativeOrientation == DisplayOrientations.Portrait) { deviceOrientationDegrees -= 90; } int angle = (360 + displayOritentationDegrees + deviceOrientationDegrees) % 360; RotateTransform transform = new RotateTransform { Angle = angle }; this.photoButton.RenderTransform = transform; this.videoButton.RenderTransform = transform; this.faceDetectionButton.RenderTransform = transform; } #endregion #region 캡처 컨트롤 업데이트히기 - UpdateCaptureControls() /// <summary> /// 캡처 컨트롤 업데이트히기 /// </summary> /// <remarks> /// 이 방법은 앱의 현재 상태와 장치의 기능에 따라 아이콘을 업데이트하고 /// 사진/비디오 버튼을 활성화/비활성화하고 표시하거나/숨긴다. /// </remarks> private void UpdateCaptureControls() { // 버튼은 미리보기가 성공적으로 시작된 경우에만 활성화되어야 한다. this.photoButton.IsEnabled = this.mediaEncodingProperties != null; this.videoButton.IsEnabled = this.mediaEncodingProperties != null; this.faceDetectionButton.IsEnabled = this.mediaEncodingProperties != null; // 효과 유무에 따라 얼굴 탐지 아이콘을 업데이트한다. this.faceDetectionSymbolIcon1.Visibility = (this.faceDetectionEffect != null && this.faceDetectionEffect.Enabled) ? Visibility.Visible : Visibility.Collapsed; this.faceDetectionSymbolIcon2.Visibility = (this.faceDetectionEffect == null || !this.faceDetectionEffect.Enabled) ? Visibility.Visible : Visibility.Collapsed; // 얼굴 탐지 캔버스를 숨기고 지운다. this.faceCanvas.Visibility = (this.faceDetectionEffect != null && this.faceDetectionEffect.Enabled) ? Visibility.Visible : Visibility.Collapsed; // 레코딩시 적색 "레코딩" 아이콘 대신 "중지" 아이콘을 표시하도록 레코딩 버튼을 업데이트한다. this.startVideoEllipse.Visibility = this.isRecording ? Visibility.Collapsed : Visibility.Visible; this.stopVideoRectangle.Visibility = this.isRecording ? Visibility.Visible : Visibility.Collapsed; // 카메라가 사진 촬영과 비디오 녹화를 동시에 지원하지 않는 경우 녹화에서 사진 버튼을 비활성화한다. if(this.isInitialized && !this.mediaCapture.MediaCaptureSettings.ConcurrentRecordAndPhotoSupported) { this.photoButton.IsEnabled = !this.isRecording; // 비활성화된 경우 버튼을 보이지 않게 하여 상호 작용할 수 없음을 분명히 한다. this.photoButton.Opacity = this.photoButton.IsEnabled ? 1 : 0; } } #endregion #region 이벤트 핸들러 등록하기 - RegisterEventHandlers() /// <summary> /// 이벤트 핸들러 등록하기 /// </summary> private void RegisterEventHandlers() { if(ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons")) { HardwareButtons.CameraPressed += HardwareButtons_CameraPressed; } if(this.orientationSensor != null) { this.orientationSensor.OrientationChanged += orientationSensor_OrientationChanged; UpdateButtonOrientation(); } this.displayInformation.OrientationChanged += displayInformation_OrientationChanged; this.systemMediaTransportControls.PropertyChanged += systemMediaTransportControls_PropertyChanged; } #endregion #region 이벤트 핸들러 등록취소하기 - UnregisterEventHandlers() /// <summary> /// 이벤트 핸들러 등록취소하기 /// </summary> private void UnregisterEventHandlers() { if(ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons")) { HardwareButtons.CameraPressed -= HardwareButtons_CameraPressed; } if(this.orientationSensor != null) { this.orientationSensor.OrientationChanged -= orientationSensor_OrientationChanged; } this.displayInformation.OrientationChanged -= displayInformation_OrientationChanged; this.systemMediaTransportControls.PropertyChanged -= systemMediaTransportControls_PropertyChanged; } #endregion #region UI 셋업하기 (비동기) - SetupUIAsync() /// <summary> /// UI 셋업하기 (비동기) /// </summary> /// <returns>태스크</returns> /// <remarks> /// 페이지 방향을 잠그고 상태 표시줄(전화에서)을 숨기고 /// 하드웨어 버튼 및 방향 센서에 대해 등록된 이벤트 핸들러를 숨기려고 시도합니다. /// </remarks> private async Task SetupUIAsync() { // 더 나은 경험을 제공하므로 CaptureElement가 회전하지 않도록 페이지를 가로 방향으로 잠그도록 시도한다. DisplayInformation.AutoRotationPreferences = DisplayOrientations.Landscape; // 상태 표시줄 숨긴다. if(ApiInformation.IsTypePresent("Windows.UI.ViewManagement.StatusBar")) { await Windows.UI.ViewManagement.StatusBar.GetForCurrentView().HideAsync(); } // 현재 상태로 방향 변수를 채운다. this.displayOrientations = this.displayInformation.CurrentOrientation; if(this.orientationSensor != null) { this.deviceOrientation = this.orientationSensor.GetCurrentOrientation(); } RegisterEventHandlers(); StorageLibrary picturesStorageLibrary = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Pictures); this.captureStorageFolder = picturesStorageLibrary.SaveFolder ?? ApplicationData.Current.LocalFolder; } #endregion #region UI 청소하기 (비동기) - CleanupUIAsync() /// <summary> /// UI 청소하기 (비동기) /// </summary> /// <returns></returns> /// <remarks> /// 하드웨어 버튼 및 방향 센서에 대한 이벤트 핸들러를 등록취소하고, /// 상태 표시줄(전화기에 대한) 표시를 허용하고, /// 페이지 방향 잠금을 제거한다. /// </remarks> private async Task CleanupUIAsync() { UnregisterEventHandlers(); if(ApiInformation.IsTypePresent("Windows.UI.ViewManagement.StatusBar")) { await Windows.UI.ViewManagement.StatusBar.GetForCurrentView().ShowAsync(); } DisplayInformation.AutoRotationPreferences = DisplayOrientations.None; } #endregion #region 카메라 초기화하기 (비동기) - InitializeCameraAsync() /// <summary> /// 카메라 초기화하기 (비동기) /// </summary> /// <returns></returns> private async Task InitializeCameraAsync() { if(this.mediaCapture == null) { // 가능한 경우 전면 카메라를 가져오는 것을 시도하고, 그렇지 않은 경우 다른 카메라 장치를 사용한다. DeviceInformation cameraDeviceInformation = await GetCameraDeviceInformation ( Windows.Devices.Enumeration.Panel.Front ); if(cameraDeviceInformation == null) { return; } this.mediaCapture = new MediaCapture(); // 동영상 녹화가 최대 시간에 도달했을 때와 문제가 발생했을 때 이벤트를 등록한다. this.mediaCapture.RecordLimitationExceeded += mediaCapture_RecordLimitationExceeded; this.mediaCapture.Failed += mediaCapture_Failed; MediaCaptureInitializationSettings settings = new MediaCaptureInitializationSettings { VideoDeviceId = cameraDeviceInformation.Id }; try { await this.mediaCapture.InitializeAsync(settings); this.isInitialized = true; } catch(UnauthorizedAccessException) { } if(this.isInitialized) { if ( cameraDeviceInformation.EnclosureLocation == null || cameraDeviceInformation.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Unknown ) { this.externalCamera = true; } else { this.externalCamera = false; this.mirroringPreview = (cameraDeviceInformation.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Front); } await StartPreviewAsync(); UpdateCaptureControls(); } } } #endregion #region 카메라 청소하기 (비동기) - CleanupCameraAsync() /// <summary> /// 카메라 청소하기 (비동기) /// </summary> /// <returns>태스크</returns> /// <remarks> /// 카메라 리소스를 정리하고(비디오 녹화 및/또는 필요한 경우 미리 보기를 중지한 후) /// MediaCapture 이벤트에서 등록을 취소한다. /// </remarks> private async Task CleanupCameraAsync() { if(this.isInitialized) { // 정리 중 녹음이 진행 중인 경우 중지하여 녹음을 저장한다. if(this.isRecording) { await StopRecordingAsync(); } if(this.faceDetectionEffect != null) { await CleanUpFaceDetectionEffectAsync(); } if(this.mediaEncodingProperties != null) { // 미리 보기를 중지하는 호출은 완성을 위해 여기에 포함되지만 // 나중에 MediaCapture.Dispose()에 대한 호출이 수행되는 경우 // 미리 보기가 해당 지점에서 자동으로 중지되므로 안전하게 제거할 수 있다. await StopPreviewAsync(); } this.isInitialized = false; } if(this.mediaCapture != null) { this.mediaCapture.RecordLimitationExceeded -= mediaCapture_RecordLimitationExceeded; this.mediaCapture.Failed -= mediaCapture_Failed; this.mediaCapture.Dispose(); this.mediaCapture = null; } } #endregion #region 미리보기 사각형 구하기 - GetPreviewRectangle(previewResolution, previewControl) /// <summary> /// 미리보기 사각형 구하기 /// </summary> /// <param name="previewResolution">미리보기 비디오 인코딩 속성</param> /// <param name="previewControl">미리보기 컨트롤</param> /// <returns>미리보기 사각형</returns> /// <remarks> /// 크기 조정 모드가 균일일 때 미리 보기 컨트롤 내에서 미리 보기 스트림을 포함하는 사각형의 크기와 위치를 계산한다. /// </remarks> public Rect GetPreviewRectangle(VideoEncodingProperties previewResolution, CaptureElement previewControl) { Rect previewRectangle = new Rect(); // 모든 것이 올바르게 초기화되기 전에 이 함수가 호출된 경우 빈 결과를 반환한다. if ( previewControl == null || previewControl.ActualHeight < 1 || previewControl.ActualWidth < 1 || previewResolution == null || previewResolution.Height == 0 || previewResolution.Width == 0 ) { return previewRectangle; } uint streamWidth = previewResolution.Width; uint streamHeight = previewResolution.Height; // 세로 방향의 경우 너비와 높이를 바꿔야 한다. if ( this.displayOrientations == DisplayOrientations.Portrait || this.displayOrientations == DisplayOrientations.PortraitFlipped ) { streamWidth = previewResolution.Height; streamHeight = previewResolution.Width; } // 컨트롤의 미리보기 표시 영역이 전체 너비와 높이에 걸쳐 있다고 // 가정하여 시작한다(필요한 치수의 경우 다음에서 수정된다). previewRectangle.Width = previewControl.ActualWidth; previewRectangle.Height = previewControl.ActualHeight; // UI가 미리보기보다 "넓은" 경우 레터박스가 측면에 표시된다. if((previewControl.ActualWidth / previewControl.ActualHeight > streamWidth / (double)streamHeight)) { double scale = previewControl.ActualHeight / streamHeight; double scaledWidth = streamWidth * scale; previewRectangle.X = (previewControl.ActualWidth - scaledWidth) / 2.0; previewRectangle.Width = scaledWidth; } else // 미리보기 스트림은 UI보다 "넓음"이므로 레터박스가 상단+하단에 표시된다. { double scale = previewControl.ActualWidth / streamWidth; double scaledHeight = streamHeight * scale; previewRectangle.Y = (previewControl.ActualHeight - scaledHeight) / 2.0; previewRectangle.Height = scaledHeight; } return previewRectangle; } #endregion #region 미리보기 회전 설정하기 (비동기) - SetPreviewRotationAsync() /// <summary> /// 미리보기 회전 설정하기 (비동기) /// </summary> /// <returns>태스크</returns> /// <remarks> /// 장치와 관련된 UI의 현재 방향을 가져오고(AutoRotationPreferences를 준수할 수 없는 경우) /// 미리 보기에 수정 회전을 적용한다. /// </remarks> private async Task SetPreviewRotationAsync() { // 카메라가 장치에 장착된 경우에만 방향을 업데이트해야 한다. if(this.externalCamera) { return; } // 미리보기를 회전할 방향과 거리를 계산한다. int rotationDegrees = GetDisplayOrientationDegrees(this.displayOrientations); // 미리보기가 미러링되는 경우 회전 방향을 반전해야 한다. if(this.mirroringPreview) { rotationDegrees = (360 - rotationDegrees) % 360; } // 미리보기 스트림에 회전 메타 데이터를 추가하여 미리보기 프레임을 렌더링하고 가져올 때 // 종횡비/치수가 일치하도록 한다. IMediaEncodingProperties properties = this.mediaCapture.VideoDeviceController.GetMediaStreamProperties ( MediaStreamType.VideoPreview ); properties.Properties.Add(_rotationKeyGUID, rotationDegrees); await this.mediaCapture.SetEncodingPropertiesAsync(MediaStreamType.VideoPreview, properties, null); } #endregion #region 미리보기 시작하기 (비동기) - StartPreviewAsync() /// <summary> /// 미리보기 시작하기 (비동기) /// </summary> /// <returns>태스크</returns> /// <remarks> /// 미리보기를 시작하고 화면을 켜두도록 요청한 후 회전 및 미러링을 위해 조정한다. /// </remarks> private async Task StartPreviewAsync() { // 미리보기가 실행되는 동안 장치가 절전 모드로 전환되지 않도록 방지한다. this.displayRequest.RequestActive(); // UI에서 미리보기 소스를 설정하고 필요한 경우 미러링을 처리한다. this.previewCaptureElement.Source = this.mediaCapture; this.previewCaptureElement.FlowDirection = this.mirroringPreview ? FlowDirection.RightToLeft : FlowDirection.LeftToRight; // 미리보기를 시작한다. await this.mediaCapture.StartPreviewAsync(); this.mediaEncodingProperties = this.mediaCapture.VideoDeviceController.GetMediaStreamProperties ( MediaStreamType.VideoPreview ); // 현재 방향으로 미리보기를 초기화한다. if(this.mediaEncodingProperties != null) { this.displayOrientations = this.displayInformation.CurrentOrientation; await SetPreviewRotationAsync(); } } #endregion #region 미리보기 중단하기 (비동기) - StopPreviewAsync() /// <summary> /// 미리보기 중단하기 (비동기) /// </summary> /// <returns>태스크</returns> /// <remarks> /// 미리보기를 중지하고 화면을 절전 모드로 전환할 수 있도록 표시 요청을 비활성화한다. /// </remarks> private async Task StopPreviewAsync() { // 미리보기를 중단한다. this.mediaEncodingProperties = null; await this.mediaCapture.StopPreviewAsync(); // 이 메소드는 UI가 아닌 스레드에서 호출되는 경우가 있으므로 디스패처를 사용합니다. await Dispatcher.RunAsync ( CoreDispatcherPriority.Normal, () => { // UI를 청소한다. this.previewCaptureElement.Source = null; // 미리보기가 중지되었으므로 이제 장치 화면을 절전 모드로 전환한다. this.displayRequest.RequestRelease(); } ); } #endregion #region 레코딩 시작하기 (비동기) - StartRecordingAsync() /// <summary> /// 레코딩 시작하기 (비동기) /// </summary> /// <returns></returns> /// <remarks> /// MP4 비디오를 StorageFile에 녹화하고 회전 메타데이터를 추가한다. /// </remarks> private async Task StartRecordingAsync() { try { StorageFile videoStorageFile = await this.captureStorageFolder.CreateFileAsync ( "SimpleVideo.mp4", CreationCollisionOption.GenerateUniqueName ); MediaEncodingProfile mediaEncodingProfile = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Auto); // 필요한 경우 미러링을 고려하여 회전 각도를 계산한다. int rotationAngle = 360 - GetDeviceOrientationDegrees(GetCameraOrientation()); mediaEncodingProfile.Video.Properties.Add(_rotationKeyGUID, PropertyValue.CreateInt32(rotationAngle)); await this.mediaCapture.StartRecordToStorageFileAsync(mediaEncodingProfile, videoStorageFile); this.isRecording = true; } catch { } } #endregion #region 레코딩 중단하기 (비동기) - StopRecordingAsync() /// <summary> /// 레코딩 중단하기 (비동기) /// </summary> /// <returns>태스크</returns> private async Task StopRecordingAsync() { this.isRecording = false; await this.mediaCapture.StopRecordAsync(); } #endregion #region 사진 저장하기 (비동기) - SavePhotoAsync(stream, targetFile, photoOrientation) /// <summary> /// 사진 저장하기 (비동기) /// </summary> /// <param name="stream">랜덤 액세스 스트림</param> /// <param name="targetFile">타겟 저장소 파일</param> /// <param name="photoOrientation">사진 방향</param> /// <returns>태스크</returns> private static async Task SavePhotoAsync ( IRandomAccessStream stream, StorageFile targetFile, PhotoOrientation photoOrientation ) { using(IRandomAccessStream sourceStream = stream) { BitmapDecoder decoder = await BitmapDecoder.CreateAsync(sourceStream); using(IRandomAccessStream targetStream = await targetFile.OpenAsync(FileAccessMode.ReadWrite)) { BitmapEncoder encoder = await BitmapEncoder.CreateForTranscodingAsync(targetStream, decoder); BitmapPropertySet bitmapPropertySet = new BitmapPropertySet { { "System.Photo.Orientation", new BitmapTypedValue(photoOrientation, PropertyType.UInt16) } }; await encoder.BitmapProperties.SetPropertiesAsync(bitmapPropertySet); await encoder.FlushAsync(); } } } #endregion #region 사진 촬영하기 (비동기) - TakePhotoAsync() /// <summary> /// 사진 촬영하기 (비동기) /// </summary> /// <returns>태스크</returns> private async Task TakePhotoAsync() { this.videoButton.IsEnabled = this.mediaCapture.MediaCaptureSettings.ConcurrentRecordAndPhotoSupported; this.videoButton.Opacity = this.videoButton.IsEnabled ? 1 : 0; InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream(); await this.mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream); try { StorageFile storageFile = await this.captureStorageFolder.CreateFileAsync ( "SimplePhoto.jpg", CreationCollisionOption.GenerateUniqueName ); PhotoOrientation photoOrientation = GetPhotoOrientation(GetCameraOrientation()); await SavePhotoAsync(stream, storageFile, photoOrientation); } catch { } this.videoButton.IsEnabled = true; this.videoButton.Opacity = 1; } #endregion #region 얼굴 탐지 효과 생성하기 (비동기) - CreateFaceDetectionEffectAsync() /// <summary> /// 얼굴 탐지 효과 생성하기 (비동기) /// </summary> /// <returns>태스크</returns> private async Task CreateFaceDetectionEffectAsync() { FaceDetectionEffectDefinition definition = new FaceDetectionEffectDefinition(); definition.SynchronousDetectionEnabled = false; definition.DetectionMode = FaceDetectionMode.HighPerformance; this.faceDetectionEffect = await this.mediaCapture.AddVideoEffectAsync ( definition, MediaStreamType.VideoPreview ) as FaceDetectionEffect; this.faceDetectionEffect.FaceDetected += faceDetectionEffect_FaceDetected; this.faceDetectionEffect.DesiredDetectionInterval = TimeSpan.FromMilliseconds(33); this.faceDetectionEffect.Enabled = true; } #endregion #region 얼굴 탐지 효과 청소하기 (비동기) - CleanUpFaceDetectionEffectAsync() /// <summary> /// 얼굴 탐지 효과 청소하기 (비동기) /// </summary> /// <returns>태스크</returns> /// <remarks> /// 얼굴 탐지 효과를 비활성화 및 제거하고 얼굴 탐지를 위한 이벤트 처리기를 등록 취소한다. /// </remarks> private async Task CleanUpFaceDetectionEffectAsync() { this.faceDetectionEffect.Enabled = false; this.faceDetectionEffect.FaceDetected -= faceDetectionEffect_FaceDetected; await this.mediaCapture.RemoveEffectAsync(this.faceDetectionEffect); this.faceDetectionEffect = null; } #endregion #region 얼굴 캔버스 회전 설정하기 - SetFaceCanvasRotation() /// <summary> /// 얼굴 캔버스 회전 설정하기 /// </summary> /// <remarks> /// 현재 표시 방향을 사용하여 얼굴 탐지 캔버스에 적용할 회전 변환을 계산하고 /// 미리보기가 미러링되는 경우 미러링한다. /// </remarks> private void SetFaceCanvasRotation() { // 캔버스를 얼마나 회전시킬지 계산한다. int rotationDegrees = GetDisplayOrientationDegrees(this.displayOrientations); // SetPreviewRotationAsync와 마찬가지로 미리보기가 미러링되는 경우 회전 방향을 반전해야 한다. if(this.mirroringPreview) { rotationDegrees = (360 - rotationDegrees) % 360; } // 회전을 적용한다. RotateTransform transform = new RotateTransform { Angle = rotationDegrees }; this.faceCanvas.RenderTransform = transform; Rect previewRect = GetPreviewRectangle ( this.mediaEncodingProperties as VideoEncodingProperties, this.previewCaptureElement ); // 세로 모드 방향의 경우 회전 후 캔버스의 너비와 높이를 바꿔 컨트롤이 계속 미리보기와 겹치도록 한다. if ( this.displayOrientations == DisplayOrientations.Portrait || this.displayOrientations == DisplayOrientations.PortraitFlipped ) { this.faceCanvas.Width = previewRect.Height; this.faceCanvas.Height = previewRect.Width; // 크기 조정이 컨트롤의 중앙에 영향을 미치므로 캔버스의 위치도 조정해야 한다. Canvas.SetLeft(this.faceCanvas, previewRect.X - (previewRect.Height - previewRect.Width ) / 2); Canvas.SetTop (this.faceCanvas, previewRect.Y - (previewRect.Width - previewRect.Height) / 2); } else { this.faceCanvas.Width = previewRect.Width; this.faceCanvas.Height = previewRect.Height; Canvas.SetLeft(this.faceCanvas, previewRect.X); Canvas.SetTop (this.faceCanvas, previewRect.Y); } // 미리보기가 미러링되는 경우 캔버스도 미러링한다. this.faceCanvas.FlowDirection = this.mirroringPreview ? FlowDirection.RightToLeft : FlowDirection.LeftToRight; } #endregion #region 얼굴 사각형 구하기 - GetFaceRectangle(faceBitmapBounds) /// <summary> /// 얼굴 사각형 구하기 /// </summary> /// <param name="faceBitmapBounds">얼굴 비트맵 테두리</param> /// <returns>얼굴 사각형</returns> /// <remarks> /// 미리보기 좌표에 정의된 얼굴 정보를 가져와 미리보기 컨트롤의 위치와 크기를 고려하여 UI 좌표로 반환한다. /// </remarks> private Rectangle GetFaceRectangle(BitmapBounds faceBitmapBounds) { Rectangle rectangle = new Rectangle(); VideoEncodingProperties previewProperties = this.mediaEncodingProperties as VideoEncodingProperties; // 미리보기에 대한 사용 가능한 정보가 없으면 화면 좌표로 다시 크기 조정이 불가능하므로 빈 사각형을 반환한다. if(previewProperties == null) { return rectangle; } // 유사하게, 차원 중 하나라도 0이면(오류 경우에만 발생) 빈 사각형을 반환한다. if(previewProperties.Width == 0 || previewProperties.Height == 0) { return rectangle; } double streamWidth = previewProperties.Width; double streamHeight = previewProperties.Height; // 세로 방향의 경우 너비와 높이를 바꿔야 한다. if ( this.displayOrientations == DisplayOrientations.Portrait || this.displayOrientations == DisplayOrientations.PortraitFlipped ) { streamHeight = previewProperties.Width; streamWidth = previewProperties.Height; } // 실제 비디오 피드가 차지하는 사각형을 가져온다. Rect previewInUI = GetPreviewRectangle(previewProperties, previewCaptureElement); // 미리보기 스트림 좌표에서 창 좌표로 너비 및 높이를 크기 조정한다. rectangle.Width = (faceBitmapBounds.Width / streamWidth ) * previewInUI.Width; rectangle.Height = (faceBitmapBounds.Height / streamHeight) * previewInUI.Height; // 미리보기 스트림 좌표에서 창 좌표로 X 및 Y 좌표를 크기 조정한다. double x = (faceBitmapBounds.X / streamWidth ) * previewInUI.Width; double y = (faceBitmapBounds.Y / streamHeight) * previewInUI.Height; Canvas.SetLeft(rectangle, x); Canvas.SetTop (rectangle, y); return rectangle; } #endregion #region 탐지 얼굴 하이라이트 처리하기 - HighlightDetectedFaces(detectedFaceList) /// <summary> /// 탐지 얼굴 하이라이트 처리하기 /// </summary> /// <param name="detectedFaceList">탐지 얼굴 리스트</param> /// <remarks> /// 탐지된 모든 얼굴에 대해 반복하여 Rectangle을 생성하고 FaceCanvas에 얼굴 탐지 상자로 추가한다. /// </remarks> private void HighlightDetectedFaces(IReadOnlyList<DetectedFace> detectedFaceList) { // 이전 이벤트에서 기존 사각형을 제거한다. this.faceCanvas.Children.Clear(); for(int i = 0; i < detectedFaceList.Count; i++) { // 얼굴 좌표 단위는 미리보기 해상도 픽셀로 디스플레이 해상도와 스케일이 다를 수 있으므로 변환이 필요할 수 있다. Rectangle faceRectangle = GetFaceRectangle(detectedFaceList[i].FaceBox); faceRectangle.StrokeThickness = 2; faceRectangle.Stroke = (i == 0 ? new SolidColorBrush(Colors.Blue) : new SolidColorBrush(Colors.DeepSkyBlue)); this.faceCanvas.Children.Add(faceRectangle); } // 얼굴 캔버스 회전을 설정한다. SetFaceCanvasRotation(); } #endregion } } |
▶ App.xaml
1 2 3 4 5 6 |
<Application x:Class="TestProject.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> </Application> |
▶ App.xaml.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 |
using System; using System.Diagnostics; using Windows.ApplicationModel.Activation; using Windows.Globalization; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; namespace TestProject { /// <summary> /// 앱 /// </summary> sealed partial class App : Application { //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - App() /// <summary> /// 생성자 /// </summary> public App() { InitializeComponent(); } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Protected #region 시작시 처리하기 - OnLaunched(e) /// <summary> /// 시작시 처리하기 /// </summary> /// <param name="e">이벤트 인자</param> protected override void OnLaunched(LaunchActivatedEventArgs e) { #if DEBUG if(Debugger.IsAttached) { DebugSettings.EnableFrameRateCounter = true; } #endif Frame rootFrame = Window.Current.Content as Frame; if(rootFrame == null) { rootFrame = new Frame(); rootFrame.Language = ApplicationLanguages.Languages[0]; rootFrame.NavigationFailed += rootFrame_NavigationFailed; Window.Current.Content = rootFrame; } if(rootFrame.Content == null) { rootFrame.Navigate(typeof(MainPage), e.Arguments); } Window.Current.Activate(); } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Private #region 루트 프레임 네비게이션 실패시 처리하기 - rootFrame_NavigationFailed(sender, e) /// <summary> /// 루트 프레임 네비게이션 실패시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> void rootFrame_NavigationFailed(object sender, NavigationFailedEventArgs e) { throw new Exception($"페이지 로드를 실패했습니다 : {e.SourcePageType.FullName}"); } #endregion } } |
TestProject.zip
■ 카메라 정보를 조회하는 방법을 보여준다. ▶ Program.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
using System; using System.Management; namespace TestProject { /// <summary> /// 프로그램 /// </summary> class Program { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region 프로그램 시작하기 - Main() /// <summary> /// 프로그램 시작하기 /// </summary> private static void Main() { string cameraName = "USB2.0 PC CAMERA"; string queryString1 = "Select * From Win32_USBControllerDevice"; using(ManagementObjectSearcher searcher1 = new ManagementObjectSearcher(queryString1)) { ManagementObjectCollection collection1 = searcher1.Get(); foreach(ManagementBaseObject item1 in collection1) { string dependent = item1.GetPropertyValue("Dependent") as string; string deviceID = (dependent.Split(new string[] { "DeviceID=" }, 2, StringSplitOptions.None)[1]); string queryString2 = $"Select * From Win32_PnpEntity Where PNPClass = 'Camera' And PNPDeviceID = {deviceID}"; using(ManagementObjectSearcher searcher2 = new ManagementObjectSearcher(queryString2)) { ManagementObjectCollection collection2 = searcher2.Get(); foreach(ManagementBaseObject item2 in collection2) { string caption = item2.GetPropertyValue("Caption") as string; if(caption != cameraName) { continue; } foreach(PropertyData propertyData in item2.Properties) { Console.WriteLine($"{propertyData.Name} : {propertyData.Value}"); } Console.WriteLine(); } collection2.Dispose(); } } collection1.Dispose(); } } #endregion } } |
TestProject.zip
■ Get-CimInstance 명령을 사용해 카메라 인스턴스 ID를 구하는 방법을 보여준다. ▶ 실행 명령
1 2 3 4 5 |
$id = (Get-CimInstance -Class Win32_PnpEntity | where pnpclass -match 'camera').pnpDeviceID $id |
■ wmic 명령을 사용해 카메라의 물리적 장치 객체명(Physical Device Object Name)을 구하는 방법을 보여준다. ▶ 실행 명령
1 2 3 4 5 |
wmic path Win32_PnPSignedDriver where "FriendlyName LIKE '%camera%'" get DeviceName,FriendlyName,PDO wmic path Win32_PnPSignedDriver where "DeviceName = 'USB Video Device' and PDO LIKE '\\Device\\%'" get DeviceName,FriendlyName,PDO |
■ Get-PnpDevice 명령을 사용해 첫번째 카메라의 인스턴스 ID를 구하는 방법을 보여준다. ▶ 실행 명령
1 2 3 4 5 |
Get-PnpDevice -FriendlyName *camera*,*webcam* -Class camera,image | Select-Object -Property InstanceId | Select-Object -First 1 |
1. [장치 관리자] 대화 상자의 [카메라] /
■ USB 케이블 연결 카메라에서 사진 파일을 복사하는 방법을 보여준다. ▶ Program.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 |
using System; using System.Collections.Generic; using System.IO; using MediaDevices; namespace TestProject { /// <summary> /// 프로그램 /// </summary> class Program { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region 프로그램 시작하기 - Main() /// <summary> /// 프로그램 시작하기 /// </summary> private static void Main() { string cameraName = "Canon PowerShot SX230 HS"; string sourceRootDirectoryPath = @"\\이동식 저장소\DCIM"; string targetRootDirectoryPath = @"D:\Camera"; IEnumerable<MediaDevice> mediaDeviceEnumerable = MediaDevice.GetDevices(); foreach(MediaDevice mediaDevice in mediaDeviceEnumerable) { Console.WriteLine($"CAMERA NAME : {mediaDevice.FriendlyName}"); if(mediaDevice.FriendlyName.Contains(cameraName)) { mediaDevice.Connect(); string[] sourceDirectoryPathArray = mediaDevice.GetDirectories(sourceRootDirectoryPath); foreach(string sourceDirectoryPath in sourceDirectoryPathArray) { Console.WriteLine($" SOURCE DIRECTORY PATH : {sourceDirectoryPath}"); Console.WriteLine(); string sourceDirectoryName = sourceDirectoryPath.TrimEnd('\\'); sourceDirectoryName = sourceDirectoryName.Substring(sourceDirectoryName.LastIndexOf('\\') + 1); string[] sourceFilePathArray = mediaDevice.GetFiles(sourceDirectoryPath); foreach(string sourceFilePath in sourceFilePathArray) { Console.WriteLine($" SOURCE FILE PATH : {sourceFilePath}"); MemoryStream memoryStream = new MemoryStream(); mediaDevice.DownloadFile(sourceFilePath, memoryStream); memoryStream.Position = 0; string sourceFileName = sourceFilePath.TrimEnd('\\'); sourceFileName = sourceFileName.Substring(sourceFileName.LastIndexOf('\\') + 1); string targetDirectoryPath = Path.Combine(targetRootDirectoryPath, sourceDirectoryName); if(!Directory.Exists(targetDirectoryPath)) { Directory.CreateDirectory(targetDirectoryPath); } string targetFilePath = Path.Combine(targetRootDirectoryPath, sourceDirectoryName, sourceFileName); Console.WriteLine($" TARGET FILE PATH : {targetFilePath}"); Console.WriteLine(); CopyFile(memoryStream, targetFilePath); } } } } } #endregion #region 파일 복사하기 - CopyFile(sourceStream, targetFilePath) /// <summary> /// 파일 복사하기 /// </summary> /// <param name="sourceStream">소스 스트림</param> /// <param name="targetFilePath">타겟 파일 경로</param> private static void CopyFile(Stream sourceStream, string targetFilePath) { using(FileStream targetStream = new FileStream(targetFilePath, FileMode.Create, FileAccess.Write)) { byte[] targetByteArray = new byte[sourceStream.Length]; sourceStream.Read(targetByteArray, 0, (int)sourceStream.Length); targetStream.Write(targetByteArray, 0, targetByteArray.Length); sourceStream.Close(); } } #endregion } } |
※ 패키지 설치 : MediaDevices 1. 비주얼 스튜디오를 실행한다.
■ MediaDevices 누겟을 설치하는 방법을 보여준다. 1. Visual Studio를 실행한다. 2. [도구] / [NuGet 패키지 관리자] / [패키지 관리자 콘솔] 메뉴를 실행한다.
■ Enable-PnpDevice 명령을 사용해 카메라를 활성화하는 방법을 보여준다. ▶ 실행 명령
1 2 3 |
Enable-PnpDevice -InstanceId (Get-PnpDevice -FriendlyName *camera*,*webcam* -Class camera,image -Status Error).InstanceId |
※ PowerShell을 관리자 모드로 실행한다. ※ 카메라를 실행하고 있으면 즉시
■ Get-PnpDevice 명령을 사용해 카메라를 찾는 방법을 보여준다. ▶ 실행 명령
1 2 3 |
Get-PnpDevice -FriendlyName *camera*,*webcam* -Class camera,image |
■ Disable-PnpDevice 명령을 사용해 카메라를 비활성화하는 방법을 보여준다. ▶ 실행 명령
1 2 3 |
Disable-PnpDevice -InstanceId (Get-PnpDevice -FriendlyName *camera*,*webcam* -Class camera,image -Status OK).InstanceId |
※ PowerShell을 관리자 모드로 실행한다. ※ 카메라를 실행하고 있으면 즉시
■ CameraControl 클래스에서 카메라를 사용하는 방법을 보여준다. (기능 개선) [TestLibrary 프로젝트] ▶ CameraControl.xaml
1 2 3 4 5 6 7 8 9 10 11 |
<UserControl x:Class="TestLibrary.CameraControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:dxe="http://schemas.devexpress.com/winfx/2008/xaml/editors"> <dxe:CameraControl Name="cameraControl" Stretch="Fill" ShowSettingsButton="False" AllowAutoStart="False" /> </UserControl> |
▶ CameraControl.xaml.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 |
using System.Collections.Generic; using System.Linq; using System.Windows.Controls; using System.Windows.Media; using DevExpress.Xpf.Editors; namespace TestLibrary { /// <summary> /// 카메라 컨트롤 /// </summary> public partial class CameraControl : UserControl { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 캡처 여부 /// </summary> private bool isCapturing = false; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 장치명 - DeviceName /// <summary> /// 장치명 /// </summary> public string DeviceName { get { return this.cameraControl.DeviceInfo.Name; } set { DeviceInfo deviceInfo = GetDeviceInfo(value); this.cameraControl.DeviceInfo = deviceInfo; } } #endregion #region 캡처 여부 - IsCapturing /// <summary> /// 캡처 여부 /// </summary> public bool IsCapturing { get { return this.isCapturing; } } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - CameraControl() /// <summary> /// 생성자 /// </summary> public CameraControl() { InitializeComponent(); } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 장치명 리스트 구하기 - GetDeviceNameList() /// <summary> /// 장치명 리스트 구하기 /// </summary> /// <returns></returns> public static List<string> GetDeviceNameList() { List<DeviceInfo> deviceInfoList = GetDeviceInfoList(); List<string> list = new List<string>(); foreach(DeviceInfo deviceInfo in deviceInfoList) { list.Add(deviceInfo.Name); } return list; } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// private #region 장치 정보 리스트 구하기 - GetDeviceInfoList() /// <summary> /// 장치 정보 리스트 구하기 /// </summary> /// <returns>장치 정보 리스트</returns> private static List<DeviceInfo> GetDeviceInfoList() { DevExpress.Xpf.Editors.CameraControl control = new DevExpress.Xpf.Editors.CameraControl(); List<DeviceInfo> deviceInfoList = control.GetAvailableDevices().ToList(); return deviceInfoList; } #endregion #region 장치 정보 구하기 - GetDeviceInfo(deviceName) /// <summary> /// 장치 정보 구하기 /// </summary> /// <param name="deviceName">장치명</param> /// <returns>장치 정보</returns> private static DeviceInfo GetDeviceInfo(string deviceName) { if(string.IsNullOrEmpty(deviceName)) { return null; } List<DeviceInfo> deviceInfoList = GetDeviceInfoList(); DeviceInfo deviceInfo = deviceInfoList.Where(d => d.Name == deviceName).FirstOrDefault(); return deviceInfo; } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Instance //////////////////////////////////////////////////////////////////////////////// Public #region 시작하기 - Start() /// <summary> /// 시작하기 /// </summary> public void Start() { if(this.isCapturing) { return; } this.cameraControl.Start(); this.isCapturing = true; } #endregion #region 중단하기 - Stop() /// <summary> /// 중단하기 /// </summary> public void Stop() { if(!this.isCapturing) { return; } this.cameraControl.Stop(); this.isCapturing = false; } #endregion #region 이미지 구하기 - GetImage() /// <summary> /// 이미지 구하기 /// </summary> /// <returns>이미지 소스</returns> public ImageSource GetImage() { return this.cameraControl.TakeSnapshot(); } #endregion } } |
[TestProject 프로젝트] ▶ MainWindow.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
<Window x:Class="TestProject.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:library="clr-namespace:TestLibrary;assembly=TestLibrary" Width="800" Height="600" Title="CameraControl 클래스 : 카메라 사용하기 (기능 개선)" FontFamily="나눔고딕코딩" FontSize="16"> <Grid Margin="10"> <Grid.RowDefinitions> <RowDefinition Height="*" /> <RowDefinition Height="Auto" /> </Grid.RowDefinitions> <Border Grid.Row="0" HorizontalAlignment="Center" VerticalAlignment="Center" BorderThickness="1" BorderBrush="Black"> <library:CameraControl Name="cameraControl" Width="600" Height="480" /> </Border> <StackPanel Grid.Row="1" HorizontalAlignment="Right" VerticalAlignment="Center" Orientation="Horizontal"> <Button Name="startButton" Width="100" Height="30" Content="시작" /> <Button Name="imageButton" Margin="10 0 0 0" Width="100" Height="30" Content="이미지" /> </StackPanel> </Grid> </Window> |
■ FFMpeg을 사용해 웹 카메라를 사용하는 방법을 보여준다. (기능 개선) [TestLibrary 프로젝트] ▶ BITMAPINFOHEADER.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
using System.Runtime.InteropServices; namespace TestLibrary { /// <summary> /// 비트맵 정보 헤더 /// </summary> [StructLayout(LayoutKind.Sequential)] public struct BITMAPINFOHEADER { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Public #region Field /// <summary> /// 크기 /// </summary> public uint Size; /// <summary> /// 너비 /// </summary> public int Width; /// <summary> /// 높이 /// </summary> public int Height; /// <summary> /// 플레인 수 /// </summary> public ushort PlaneCount; /// <summary> /// 비트 수 /// </summary> public ushort BitCount; /// <summary> /// 압축 방법 /// </summary> public uint Compression; /// <summary> /// 이미지 크기 /// </summary> public uint ImageSize; /// <summary> /// 미터당 X 픽셀 수 /// </summary> public int XPixelCountPerMeter; /// <summary> /// 미터당 Y 픽셀 수 /// </summary> public int YPixelCountPerMeter; /// <summary> /// 사용 색상 인덱스 수 /// </summary> public uint UsedColorCount; /// <summary> /// 중료 색상 인덱스 수 /// </summary> public uint ImportantColorIndexCount; #endregion } } |
▶ DirectShowException.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
using System; using System.Runtime.InteropServices; namespace TestLibrary { /// <summary> /// DirectShow 예외 /// </summary> public sealed class DirectShowException : Exception { //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - DirectShowException(message, resultHandle) /// <summary> /// 생성자 /// </summary> /// <param name="message">메시지</param> /// <param name="resultHandle">결과 핸들</param> public DirectShowException(string message, int resultHandle) : base(message, Marshal.GetExceptionForHR(resultHandle)) { } #endregion } } |
▶ VideoCaptureDevice.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 |
using System; namespace TestLibrary { /// <summary> /// 비디오 캡처 장치 /// </summary> public sealed class VideoCaptureDevice : IEquatable<VideoCaptureDevice> { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 명칭 /// </summary> private readonly String name; /// <summary> /// 장치 경로 /// </summary> private readonly String devicePath; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 명칭 - Name /// <summary> /// 명칭 /// </summary> public string Name { get { return this.name; } } #endregion #region 장치 경로 - DevicePath /// <summary> /// 장치 경로 /// </summary> internal string DevicePath { get { return this.devicePath; } } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - VideoCaptureDevice(info) /// <summary> /// 생성자 /// </summary> public VideoCaptureDevice(VideoInputDeviceInfo info) { this.name = info.DeviceName; devicePath = info.DevicePath; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 연산자 == 재정의하기 - ==(left, right) /// <summary> /// 연산자 == 재정의하기 /// </summary> /// <param name="left">왼쪽 객체</param> /// <param name="right">오른쪽 객체</param> /// <returns>처리 결과</returns> public static bool operator ==(VideoCaptureDevice left, VideoCaptureDevice right) { return Equals(left, right); } #endregion #region 연산자 != 재정의하기 - !=(left, right) /// <summary> /// 연산자 != 재정의하기 /// </summary> /// <param name="left">왼쪽 객체</param> /// <param name="right">오른쪽 객체</param> /// <returns>처리 결과</returns> public static bool operator !=(VideoCaptureDevice left, VideoCaptureDevice right) { return !Equals(left, right); } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Instance //////////////////////////////////////////////////////////////////////////////// Public #region 동일 여부 구하기 - Equals(sourceObject) /// <summary> /// 동일 여부 구하기 /// </summary> /// <param name="sourceObject">소스 객체</param> /// <returns>동일 여부</returns> public override bool Equals(object sourceObject) { if(ReferenceEquals(null, sourceObject)) { return false; } if(ReferenceEquals(this, sourceObject)) { return true; } if(sourceObject.GetType() != typeof(VideoCaptureDevice)) { return false; } return Equals((VideoCaptureDevice)sourceObject); } #endregion #region 동일 여부 구하기 - Equals(source) /// <summary> /// 동일 여부 구하기 /// </summary> /// <param name="source">소스 객체</param> /// <returns>동일 여부</returns> public bool Equals(VideoCaptureDevice source) { if(ReferenceEquals(null, source)) { return false; } if(ReferenceEquals(this, source)) { return true; } return Equals(source.name, this.name) && Equals(source.devicePath, this.devicePath); } #endregion #region 해시 코드 구하기 - GetHashCode() /// <summary> /// 해시 코드 구하기 /// </summary> /// <returns>해시 코드</returns> public override int GetHashCode() { unchecked { return (this.name.GetHashCode() * 397) ^ this.devicePath.GetHashCode(); } } #endregion } } |
▶
■ CameraControl 클래스에서 카메라를 사용하는 방법을 보여준다. ▶ MainForm.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 |
using System; using System.Collections.Generic; using System.Windows.Forms; using DevExpress.Data.Camera; using DevExpress.XtraEditors; using DevExpress.XtraEditors.Camera; using DevExpress.XtraEditors.Controls; namespace TestProject { /// <summary> /// 메인 폼 /// </summary> public partial class MainForm : XtraForm { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 실행 여부 /// </summary> private bool isRunning = false; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - MainForm() /// <summary> /// 생성자 /// </summary> public MainForm() { InitializeComponent(); #region 장치 이미지 콤보 박스 에디터를 설정한다. List<CameraDeviceInfo> deviceInfoList = CameraControl.GetDevices(); if(deviceInfoList != null && deviceInfoList.Count > 0) { foreach(CameraDeviceInfo deviceInfo in deviceInfoList) { CameraDevice device = CameraControl.GetDevice(deviceInfo); ImageComboBoxItem item = new ImageComboBoxItem(); item.Description = device.Name; item.Value = device; this.deviceComboBoxEdit.Properties.Items.Add(item); } this.deviceComboBoxEdit.SelectedIndex = 0; } #endregion #region 선택 장치를 설정한다. CameraDevice deviceSelected; if(this.deviceComboBoxEdit.SelectedItem == null) { deviceSelected = null; } else { ImageComboBoxItem itemSelected = this.deviceComboBoxEdit.SelectedItem as ImageComboBoxItem; if(itemSelected == null) { deviceSelected = null; } else { deviceSelected = itemSelected.Value as CameraDevice; } } #endregion #region 카메라 컨트롤을 설정한다. this.cameraControl.AutoStartDefaultDevice = false; this.cameraControl.ShowSettingsButton = false; this.cameraControl.VideoStretchMode = VideoStretchMode.ZoomInside; this.cameraControl.Device = deviceSelected; #endregion #region 이벤트를 설정한다. this.deviceComboBoxEdit.SelectedIndexChanged += deviceComboBoxEdit_SelectedIndexChanged; this.startButton.Click += startButton_Click; #endregion } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Private //////////////////////////////////////////////////////////////////////////////// Event #region 장치 이미지 콤보 박스 에디터 선택 인덱스 변경시 처리하기 - deviceComboBoxEdit_SelectedIndexChanged(sender, e) /// <summary> /// 장치 이미지 콤보 박스 에디터 선택 인덱스 변경시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void deviceComboBoxEdit_SelectedIndexChanged(object sender, EventArgs e) { #region 선택 장치를 설정한다. CameraDevice deviceSelected; if(this.deviceComboBoxEdit.SelectedItem == null) { deviceSelected = null; } else { ImageComboBoxItem itemSelected = this.deviceComboBoxEdit.SelectedItem as ImageComboBoxItem; if(itemSelected == null) { deviceSelected = null; } else { deviceSelected = itemSelected.Value as CameraDevice; } } #endregion this.cameraControl.Device = deviceSelected; } #endregion #region 시작 버튼 클릭시 처리하기 - startButton_Click(sender, e) /// <summary> /// 시작 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void startButton_Click(object sender, EventArgs e) { if(this.isRunning) { this.isRunning = false; this.deviceComboBoxEdit.Enabled = true; this.startButton.Text = "시작"; this.cameraControl.Stop(); } else { if(this.cameraControl.Device == null) { XtraMessageBox.Show ( this, "카메라 장치를 선택해 주시기 바랍니다.", "INFORMATION", MessageBoxButtons.OK, MessageBoxIcon.Information ); return; } this.isRunning = true; this.deviceComboBoxEdit.Enabled = false; this.startButton.Text = "중단"; this.cameraControl.Start(); } } #endregion } } |
TestProject.zip
■ FFMpeg을 사용해 웹 카메라를 사용하는 방법을 보여준다. ▶ FFMpegHelper.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 |
using System; using System.IO; using System.Runtime.InteropServices; using FFmpeg.AutoGen; namespace TestProject { /// <summary> /// FFMPEG 헬퍼 /// </summary> public static class FFMpegHelper { //////////////////////////////////////////////////////////////////////////////////////////////////// Import ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region DLL 디렉토리 설정하기 - SetDllDirectory(directoryPath) /// <summary> /// DLL 디렉토리 설정하기 /// </summary> /// <param name="directoryPath">디렉토리 경로</param> /// <returns>처리 결과</returns> [DllImport("kernel32", SetLastError = true)] private static extern bool SetDllDirectory(string directoryPath); #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// LD_LIBRARY_PATH /// </summary> private const string LD_LIBRARY_PATH = "LD_LIBRARY_PATH"; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 등록하기 - Register() /// <summary> /// 등록하기 /// </summary> public static void Register() { switch(Environment.OSVersion.Platform) { case PlatformID.Win32NT : case PlatformID.Win32S : case PlatformID.Win32Windows : { string currentDirectoryPath = Environment.CurrentDirectory; while(currentDirectoryPath != null) { string dllDirectoryPath = Path.Combine(currentDirectoryPath, "FFMpegDLL"); if(Directory.Exists(dllDirectoryPath)) { Register(dllDirectoryPath); return; } currentDirectoryPath = Directory.GetParent(currentDirectoryPath)?.FullName; } break; } case PlatformID.Unix : case PlatformID.MacOSX : { string dllDirectoryPath = Environment.GetEnvironmentVariable(LD_LIBRARY_PATH); Register(dllDirectoryPath); break; } } } #endregion #region 에러 메시지 구하기 - GetErrorMessage(errorCode) /// <summary> /// 에러 메시지 구하기 /// </summary> /// <param name="errorCode">에러 코드</param> /// <returns>에러 메시지</returns> public static unsafe string GetErrorMessage(int errorCode) { int bufferSize = 1024; byte* buffer = stackalloc byte[bufferSize]; ffmpeg.av_strerror(errorCode, buffer, (ulong)bufferSize); string message = Marshal.PtrToStringAnsi((IntPtr)buffer); return message; } #endregion #region 에러시 예외 던지기 - ThrowExceptionIfError(error) /// <summary> /// 에러시 예외 던지기 /// </summary> /// <param name="errorCode">에러 코드</param> /// <returns>에러 코드</returns> public static int ThrowExceptionIfError(this int errorCode) { if(errorCode < 0) { throw new ApplicationException(GetErrorMessage(errorCode)); } return errorCode; } #endregion //////////////////////////////////////////////////////////////////////////////// Private #region 등록하기 - Register(dllDirectoryPath) /// <summary> /// 등록하기 /// </summary> /// <param name="dllDirectoryPath">DLL 디렉토리 경로</param> private static void Register(string dllDirectoryPath) { switch(Environment.OSVersion.Platform) { case PlatformID.Win32NT : case PlatformID.Win32S : case PlatformID.Win32Windows : SetDllDirectory(dllDirectoryPath); break; case PlatformID.Unix : case PlatformID.MacOSX : string currentValue = Environment.GetEnvironmentVariable(LD_LIBRARY_PATH); if(string.IsNullOrWhiteSpace(currentValue) == false && currentValue.Contains(dllDirectoryPath) == false) { string newValue = currentValue + Path.PathSeparator + dllDirectoryPath; Environment.SetEnvironmentVariable(LD_LIBRARY_PATH, newValue); } break; } } #endregion } } |
▶ VideoFrameConverter.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 |
using System; using System.Runtime.InteropServices; using System.Windows; using FFmpeg.AutoGen; namespace TestProject { /// <summary> /// 비디오 프레임 컨버터 /// </summary> public sealed unsafe class VideoFrameConverter : IDisposable { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 타겟 크기 /// </summary> private readonly Size targetSize; /// <summary> /// 컨텍스트 /// </summary> private readonly SwsContext* context; /// <summary> /// 버퍼 핸들 /// </summary> private readonly IntPtr buferHandle; /// <summary> /// 임시 프레임 데이터 /// </summary> private readonly byte_ptrArray4 temporaryFrameData; /// <summary> /// 임시 프레임 라인 크기 /// </summary> private readonly int_array4 temporaryFrameLineSize; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - VideoFrameConverter(sourceSize, sourcePixelFormat, targetSize, targetPixelFormat) /// <summary> /// 생성자 /// </summary> /// <param name="sourceSize">소스 크기</param> /// <param name="sourcePixelFormat">소스 픽셀 포맷</param> /// <param name="targetSize">타겟 크기</param> /// <param name="targetPixelFormat">타겟 픽셀 포맷</param> public VideoFrameConverter(Size sourceSize, AVPixelFormat sourcePixelFormat, Size targetSize, AVPixelFormat targetPixelFormat) { this.targetSize = targetSize; this.context = ffmpeg.sws_getContext ( (int)sourceSize.Width, (int)sourceSize.Height, sourcePixelFormat, (int)targetSize.Width, (int)targetSize.Height, targetPixelFormat, ffmpeg.SWS_FAST_BILINEAR, null, null, null ); if(this.context == null) { throw new ApplicationException("Could not initialize the conversion context."); } int bufferSize = ffmpeg.av_image_get_buffer_size(targetPixelFormat, (int)targetSize.Width, (int)targetSize.Height, 1); this.buferHandle = Marshal.AllocHGlobal(bufferSize); this.temporaryFrameData = new byte_ptrArray4(); this.temporaryFrameLineSize = new int_array4(); ffmpeg.av_image_fill_arrays ( ref this.temporaryFrameData, ref this.temporaryFrameLineSize, (byte*)this.buferHandle, targetPixelFormat, (int)targetSize.Width, (int)targetSize.Height, 1 ); } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 변환하기 - Convert(sourceFrame) /// <summary> /// 변환하기 /// </summary> /// <param name="sourceFrame">소스 프레임</param> /// <returns>프레임</returns> public AVFrame Convert(AVFrame sourceFrame) { ffmpeg.sws_scale ( this.context, sourceFrame.data, sourceFrame.linesize, 0, sourceFrame.height, this.temporaryFrameData, this.temporaryFrameLineSize ); byte_ptrArray8 targetFrameData = new byte_ptrArray8(); targetFrameData.UpdateFrom(this.temporaryFrameData); int_array8 targetFrameLineSize = new int_array8(); targetFrameLineSize.UpdateFrom(this.temporaryFrameLineSize); return new AVFrame { data = targetFrameData, linesize = targetFrameLineSize, width = (int)this.targetSize.Width, height = (int)this.targetSize.Height }; } #endregion #region 리소스 해제하기 - Dispose() /// <summary> /// 리소스 해제하기 /// </summary> public void Dispose() { Marshal.FreeHGlobal(this.buferHandle); ffmpeg.sws_freeContext(this.context); } #endregion } } |
▶ VideoStreamDecoder.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 |
using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Windows; using FFmpeg.AutoGen; namespace TestProject { /// <summary> /// 비디오 스트림 디코더 /// </summary> public sealed unsafe class VideoStreamDecoder : IDisposable { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 포맷 컨텍스트 /// </summary> private readonly AVFormatContext* formatContext; /// <summary> /// 스트림 인덱스 /// </summary> private readonly int streamIndex; /// <summary> /// 코덱 컨텍스트 /// </summary> private readonly AVCodecContext* codecContext; /// <summary> /// 패킷 /// </summary> private readonly AVPacket* packet; /// <summary> /// 프레임 /// </summary> private readonly AVFrame* frame; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 코덱명 - CodecName /// <summary> /// 코덱명 /// </summary> public string CodecName { get; } #endregion #region 프레임 크기 - FrameSize /// <summary> /// 프레임 크기 /// </summary> public Size FrameSize { get; } #endregion #region 픽셀 포맷 - PixelFormat /// <summary> /// 픽셀 포맷 /// </summary> public AVPixelFormat PixelFormat { get; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - VideoStreamDecoder(device) /// <summary> /// 생성자 /// </summary> /// <param name="device">장치</param> public VideoStreamDecoder(string device) { this.formatContext = ffmpeg.avformat_alloc_context(); AVFormatContext* formatContext = this.formatContext; ffmpeg.avdevice_register_all(); AVInputFormat* inputFormat = ffmpeg.av_find_input_format("dshow"); ffmpeg.avformat_open_input(&formatContext, device, inputFormat, null).ThrowExceptionIfError(); ffmpeg.avformat_find_stream_info(this.formatContext, null).ThrowExceptionIfError(); AVStream* stream = null; for(var i = 0; i < this.formatContext->nb_streams; i++) { if(this.formatContext->streams[i]->codec->codec_type == AVMediaType.AVMEDIA_TYPE_VIDEO) { stream = this.formatContext->streams[i]; break; } } if(stream == null) { throw new InvalidOperationException("Could not found video stream."); } this.streamIndex = stream->index; this.codecContext = stream->codec; AVCodecID codecID = this.codecContext->codec_id; AVCodec* codec = ffmpeg.avcodec_find_decoder(codecID); if(codec == null) { throw new InvalidOperationException("Unsupported codec."); } ffmpeg.avcodec_open2(this.codecContext, codec, null).ThrowExceptionIfError(); CodecName = ffmpeg.avcodec_get_name(codecID); FrameSize = new Size(this.codecContext->width, this.codecContext->height); PixelFormat = this.codecContext->pix_fmt; this.packet = ffmpeg.av_packet_alloc(); this.frame = ffmpeg.av_frame_alloc(); } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 컨텍스트 정보 딕셔너리 구하기 - GetContextInfoDictionary() /// <summary> /// 컨텍스트 정보 딕셔너리 구하기 /// </summary> /// <returns>컨텍스트 정보 딕셔너리</returns> public IReadOnlyDictionary<string, string> GetContextInfoDictionary() { AVDictionaryEntry* dictionaryEntry = null; Dictionary<string, string> resultDictionary = new Dictionary<string, string>(); while((dictionaryEntry = ffmpeg.av_dict_get(this.formatContext->metadata, "", dictionaryEntry, ffmpeg.AV_DICT_IGNORE_SUFFIX)) != null) { string key = Marshal.PtrToStringAnsi((IntPtr)dictionaryEntry->key ); string value = Marshal.PtrToStringAnsi((IntPtr)dictionaryEntry->value); resultDictionary.Add(key, value); } return resultDictionary; } #endregion #region 다음 프레임 디코드 시도하기 - TryDecodeNextFrame(frame) /// <summary> /// 다음 프레임 디코드 시도하기 /// </summary> /// <param name="frame">프레임</param> /// <returns>처리 결과</returns> public bool TryDecodeNextFrame(out AVFrame frame) { ffmpeg.av_frame_unref(this.frame); int errorCode; do { try { do { errorCode = ffmpeg.av_read_frame(this.formatContext, this.packet); if(errorCode == ffmpeg.AVERROR_EOF) { frame = *this.frame; return false; } errorCode.ThrowExceptionIfError(); } while(this.packet->stream_index != this.streamIndex); ffmpeg.avcodec_send_packet(this.codecContext, this.packet).ThrowExceptionIfError(); } finally { ffmpeg.av_packet_unref(this.packet); } errorCode = ffmpeg.avcodec_receive_frame(this.codecContext, this.frame); } while(errorCode == ffmpeg.AVERROR(ffmpeg.EAGAIN)); errorCode.ThrowExceptionIfError(); frame = *this.frame; return true; } #endregion #region 리소스 해제하기 - Dispose() /// <summary> /// 리소스 해제하기 /// </summary> public void Dispose() { ffmpeg.av_frame_unref(this.frame); ffmpeg.av_free(this.frame); ffmpeg.av_packet_unref(this.packet); ffmpeg.av_free(this.packet); ffmpeg.avcodec_close(this.codecContext); AVFormatContext* formatContext = this.formatContext; ffmpeg.avformat_close_input(&formatContext); } #endregion } } |
▶ MainWindow.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
<Window x:Class="TestProject.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Width="800" Height="600" Title="FFMpeg을 사용해 웹 카메라 사용하기" FontFamily="나눔고딕코딩" FontSize="16"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="*" /> <RowDefinition Height="Auto" /> </Grid.RowDefinitions> <Border Grid.Row="0" Margin="10" BorderThickness="1" BorderBrush="Black"> <Image Name="image" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" /> </Border> <Button Name="playButton" Grid.Row="1" Margin="0 0 10 10" HorizontalAlignment="Right" Width="100" Height="30" Content="재생" /> </Grid> </Window> |
▶ MainWindow.xaml.cs
■ 웹 카메라를 사용하는 방법을 보여준다. ※ 웹 카메라 캡처 부분을 캡처할 수 없었다. [TestProject 프로젝트] ▶ MainWindow.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
<Window x:Class="TestProject.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:library="clr-namespace:TestLibrary;assembly=TestLibrary" Width="800" Height="600" MinWidth="400" MinHeight="300" Title="웹 카메라 사용하기" FontFamily="나눔고딕코딩" FontSize="16"> <Grid Margin="10"> <Grid.RowDefinitions> <RowDefinition Height="*" /> <RowDefinition Height="10" /> <RowDefinition Height="Auto" /> </Grid.RowDefinitions> <Border Grid.Row="0" BorderThickness="1" BorderBrush="Black"> <library:WebCameraControl x:Name="webCameraControl" /> </Border> <StackPanel Grid.Row="2" Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center"> <ComboBox x:Name="videoCaptureDeviceComboBox" Margin="0 5 0 5" Width="200" Height="30" VerticalContentAlignment="Center" DisplayMemberPath="Name" /> <Button x:Name="startButton" Margin="20 5 0 5" Width="100" Height="30" IsEnabled="True" Content="시작하기" /> <Button x:Name="stopButton" Margin="10 5 0 5" Width="100" Height="30" Content="중단하기" IsEnabled="{Binding Path=IsCapturing, ElementName=webCameraControl}" /> <Button x:Name="imageButton" Margin="10 5 0 5" Width="100" Height="30" Content="이미지" IsEnabled="{Binding Path=IsCapturing, ElementName=webCameraControl}" /> </StackPanel> </Grid> </Window> |
▶ MainWindow.xaml.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 |
using Microsoft.Win32; using System.Windows; using System.Windows.Controls; using TestLibrary; namespace TestProject { /// <summary> /// 메인 윈도우 /// </summary> public partial class MainWindow { //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - MainWindow() /// <summary> /// 생성자 /// </summary> public MainWindow() { InitializeComponent(); this.videoCaptureDeviceComboBox.ItemsSource = this.webCameraControl.GetVideoCaptureDeviceList(); if(this.videoCaptureDeviceComboBox.Items.Count > 0) { this.videoCaptureDeviceComboBox.SelectedItem = this.videoCaptureDeviceComboBox.Items[0]; } this.videoCaptureDeviceComboBox.SelectionChanged += videoCaptureDeviceComboBox_SelectionChanged; this.startButton.Click += startButton_Click; this.stopButton.Click += stopButton_Click; this.imageButton.Click += imageButton_Click; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Private #region 비디오 캡처 장치 콤보 박스 선택 변경시 처리하기 - videoCaptureDeviceComboBox_SelectionChanged(sender, e) /// <summary> /// 비디오 캡처 장치 콤보 박스 선택 변경시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void videoCaptureDeviceComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { this.startButton.IsEnabled = e.AddedItems.Count > 0; } #endregion #region 시작하기 버튼 클릭시 처리하기 - startButton_Click(sender, e) /// <summary> /// 시작하기 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void startButton_Click(object sender, RoutedEventArgs e) { VideoCaptureDevice videoCaptureDevice = (VideoCaptureDevice)this.videoCaptureDeviceComboBox.SelectedItem; this.webCameraControl.StartCapture(videoCaptureDevice); this.startButton.IsEnabled = false; } #endregion #region 중단하기 버튼 클릭시 처리하기 - startButton_Click(sender, e) /// <summary> /// 중단하기 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void stopButton_Click(object sender, RoutedEventArgs e) { this.webCameraControl.StopCapture(); this.startButton.IsEnabled = true; } #endregion #region 이미지 버튼 클릭시 처리하기 - startButton_Click(sender, e) /// <summary> /// 이미지 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void imageButton_Click(object sender, RoutedEventArgs e) { SaveFileDialog saveFileDialog = new SaveFileDialog { Filter = "비트맵 이미지|*.bmp" }; if(saveFileDialog.ShowDialog() == true) { this.webCameraControl.GetCurrentImage().Save(saveFileDialog.FileName); } } #endregion } } |
■ 웹 카메라를 사용하는 방법을 보여준다. [TestProject 프로젝트] ▶ MainForm.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 |
using System; using System.Windows.Forms; using TestLibrary; namespace TestProject { /// <summary> /// 메인 폼 /// </summary> public partial class MainForm : Form { //////////////////////////////////////////////////////////////////////////////////////////////////// Class ////////////////////////////////////////////////////////////////////////////////////////// Private #region 콤보 박스 항목 - ComboBoxItem /// <summary> /// 콤보 박스 항목 /// </summary> private class ComboBoxItem { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 비디오 캡처 장치 /// </summary> private readonly VideoCaptureDevice videoCaptureDevice; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 비디오 캡처 장치 - VideoCaptureDevice /// <summary> /// 비디오 캡처 장치 /// </summary> public VideoCaptureDevice VideoCaptureDevice { get { return this.videoCaptureDevice; } } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - ComboBoxItem(videoCaptureDevice) /// <summary> /// 생성자 /// </summary> /// <param name="videoCaptureDevice">비디오 캡처 장치</param> public ComboBoxItem(VideoCaptureDevice videoCaptureDevice) { this.videoCaptureDevice = videoCaptureDevice; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 문자열 구하기 - ToString() /// <summary> /// 문자열 구하기 /// </summary> /// <returns>문자열</returns> public override string ToString() { return this.videoCaptureDevice.Name; } #endregion } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - MainForm() /// <summary> /// 생성자 /// </summary> public MainForm() { InitializeComponent(); Load += Form_Load; this.videoCaptureDeviceComboBox.SelectedIndexChanged += videoCaptureDeviceComboBox_SelectedIndexChanged; this.startButton.Click += startButton_Click; this.stopButton.Click += stopButton_Click; this.imageButton.Click += imageButton_Click; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Private //////////////////////////////////////////////////////////////////////////////// Event #region 폼 로드시 처리하기 - Form_Load(sender, e) /// <summary> /// 폼 로드시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void Form_Load(object sender, EventArgs e) { foreach(VideoCaptureDevice videoCaptureDevice in this.webCameraControl.GetVideoCaptureDeviceList()) { this.videoCaptureDeviceComboBox.Items.Add(new ComboBoxItem(videoCaptureDevice)); } if(this.videoCaptureDeviceComboBox.Items.Count > 0) { this.videoCaptureDeviceComboBox.SelectedItem = this.videoCaptureDeviceComboBox.Items[0]; } } #endregion #region 비디오 캡처 장치 콤보 박스 선택 인덱스 변경시 처리하기 - videoCaptureDeviceComboBox_SelectedIndexChanged(sender, e) /// <summary> /// 비디오 캡처 장치 콤보 박스 선택 인덱스 변경시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void videoCaptureDeviceComboBox_SelectedIndexChanged(object sender, EventArgs e) { SetButtonEnabled(); } #endregion #region 시작하기 버튼 클릭시 처리하기 - startButton_Click(sender, e) /// <summary> /// 시작하기 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void startButton_Click(object sender, EventArgs e) { ComboBoxItem item = (ComboBoxItem)this.videoCaptureDeviceComboBox.SelectedItem; try { this.webCameraControl.StartCapture(item.VideoCaptureDevice); } finally { SetButtonEnabled(); } } #endregion #region 중단하기 버튼 클릭시 처리하기 - stopButton_Click(sender, e) /// <summary> /// 중단하기 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void stopButton_Click(object sender, EventArgs e) { this.webCameraControl.StopCapture(); SetButtonEnabled(); } #endregion #region 이미지 버튼 클릭시 처리하기 - imageButton_Click(sender, e) /// <summary> /// 이미지 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void imageButton_Click(object sender, EventArgs e) { SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "비트맵 이미지|*.bmp"; saveFileDialog.Title = "이미지 저장"; if(saveFileDialog.ShowDialog() == DialogResult.OK) { this.webCameraControl.GetCurrentImage().Save(saveFileDialog.FileName); } } #endregion //////////////////////////////////////////////////////////////////////////////// Function #region 버튼 이용 가능 여부 설정하기 - SetButtonEnabled() /// <summary> /// 버튼 이용 가능 여부 설정하기 /// </summary> private void SetButtonEnabled() { this.startButton.Enabled = this.videoCaptureDeviceComboBox.SelectedItem != null; this.stopButton.Enabled = this.webCameraControl.IsCapturing; this.imageButton.Enabled = this.webCameraControl.IsCapturing; } #endregion } } |
TestSolution.zip
■ 카메라 사진 크기를 측정하는 방법을 보여준다. ▶ MainForm.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 |
using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.Globalization; using System.IO; using System.Text; using System.Windows.Forms; namespace TestProject { /// <summary> /// 메인 폼 /// </summary> public partial class MainForm : Form { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 카메라 정보 리스트 /// </summary> private List<CameraInfo> cameraInfoList = new List<CameraInfo>(); /// <summary> /// 축소/확대 /// </summary> private float zoom = 1; /// <summary> /// 시작 X 좌표 /// </summary> private int startX = 0; /// <summary> /// 시작 Y 좌표 /// </summary> private int startY = 0; /// <summary> /// 이동 X 좌표 /// </summary> private int moveX = 0; /// <summary> /// 이동 Y 좌표 /// </summary> private int moveY = 0; /// <summary> /// 측정 /// </summary> private double measure = 0; /// <summary> /// 객체 크기 /// </summary> private double objectSize = 0; /// <summary> /// 객체 거리 /// </summary> private double objectDistance = 0; /// <summary> /// 객체 크기 스케일 /// </summary> private double objectSizeScale = .01; /// <summary> /// 객체 거리 스케일 /// </summary> private double objectDistanceScale = 1; /// <summary> /// 측정 시작 X 좌표 /// </summary> private int measureStartX = 0; /// <summary> /// 측정 시작 Y 좌표 /// </summary> private int measureStartY = 0; /// <summary> /// 수평 여부 /// </summary> private bool horizontal = true; /// <summary> /// 비트맵 /// </summary> private Bitmap bitmap; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 메인 폼 - MainForm() /// <summary> /// 메인 폼 /// </summary> public MainForm() { InitializeComponent(); BuildCameraMenuItem(); #region 파일 열기 대화 상자를 설정한다. this.openFileDialog.FileName = ""; this.openFileDialog.Filter = "이미지 파일|*.*|JPG|*.jpg"; this.openFileDialog.RestoreDirectory = true; #endregion #region 이벤트를 설정한다. Load += Form_Load; Resize += Form_Resize; this.openImageMenuItem.Click += openImageMenuItem_Click; this.exitMenuItem.Click += exitMenuItem_Click; this.thumbnailPictureBox.MouseDown += thumbnailPictureBox_MouseDown; this.zoomTrackBar.Scroll += zoomTrackBar_Scroll; this.foscalLengthTextBox.TextChanged += foscalLengthTextBox_TextChanged; this.cameraFactoryTextBox.TextChanged += cameraFactoryTextBox_TextChanged; this.sensorWidthTextBox.TextChanged += foscalLengthTextBox_TextChanged; this.sensorHeightTextBox.TextChanged += foscalLengthTextBox_TextChanged; this.objectSizeTextBox.Click += objectSizeTextBox_Click; this.objectSizeTextBox.TextChanged += objectSizeTextBox_TextChanged; this.objectSizeScaleComboBox.TextChanged += objectSizeScaleComboBox_TextChanged; this.objectSizeScaleComboBox.DropDownClosed += objectSizeScaleComboBox_DropDownClosed; this.findDistanceButton.Click += findDistanceButton_Click; this.findSizeButton.Click += findSizeButton_Click; this.objectDistanceTextBox.Click += objectDistanceTextBox_Click; this.objectDistanceTextBox.TextChanged += objectDistanceTextBox_TextChanged; this.objectDistanceSacleComboBox.TextChanged += objectDistanceSacleComboBox_TextChanged; this.objectDistanceSacleComboBox.DropDownClosed += objectDistanceSacleComboBox_DropDownClosed; this.moveImageButton.Click += moveImageButton_Click; this.measureButton.Click += measureButton_Click; this.mainPictureBox.MouseDown += mainPictureBox_MouseDown; this.mainPictureBox.MouseMove += mainPictureBox_MouseMove; #endregion } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Private //////////////////////////////////////////////////////////////////////////////// Event #region 폼 로드시 처리하기 - Form_Load(sender, e) /// <summary> /// 폼 로드시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void Form_Load(object sender, EventArgs e) { UpdatePictureBox(); } #endregion #region 폼 크기 조정시 처리하기 - Form_Resize(sender, e) /// <summary> /// 폼 크기 조정시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void Form_Resize(object sender, EventArgs e) { UpdatePictureBox(); } #endregion #region 이미지 열기 메뉴 항목 클릭시 처리하기 - openImageMenuItem_Click(sender, e) /// <summary> /// 이미지 열기 메뉴 항목 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void openImageMenuItem_Click(object sender, EventArgs e) { if(this.openFileDialog.ShowDialog() == DialogResult.OK) { string imageFilePath = this.openFileDialog.FileName; try { Image image = Image.FromFile(imageFilePath); this.thumbnailPictureBox.Image = image; this.zoomTrackBar.Value = 50; this.startX = 0; this.startY = 0; this.objectSize = 0; this.objectDistance = 0; this.measure = 0; this.objectDistanceTextBox.Text = string.Empty; this.objectSizeTextBox.Text = string.Empty; this.locationOnFileLabel.Text = "파일상 위치 (pixel) : "; this.locationOnSenserLabel.Text = "센서상 위치 (mm) : "; this.sizeOnSensorLabel.Text = "센서상 크기 (mm) : "; this.imageWidthTextBox.Text = string.Empty; this.imageHeightTextBox.Text = string.Empty; this.foscalLengthTextBox.Text = string.Empty; this.cameraFactoryTextBox.Text = string.Empty; SetZoom(); PropertyItem propertyItem = image.GetPropertyItem(37386); byte[] lowByteArray = new byte[propertyItem.Len / 2]; byte[] highByteArray = new byte[propertyItem.Len / 2]; Array.Copy(propertyItem.Value, 0 , lowByteArray , 0, propertyItem.Len / 2); Array.Copy(propertyItem.Value, propertyItem.Len / 2, highByteArray, 0, propertyItem.Len / 2); this.foscalLengthTextBox.Text = Convert.ToString((float)GetUnsignedInteger(lowByteArray) / GetUnsignedInteger(highByteArray)); this.imageWidthTextBox.Text = image.PhysicalDimension.Width.ToString(); this.imageHeightTextBox.Text = image.PhysicalDimension.Height.ToString(); if(image.PhysicalDimension.Width > image.PhysicalDimension.Height) { this.horizontal = true; } else { this.horizontal = false; } Encoding encoding = Encoding.ASCII; string cameraFactory = encoding.GetString(image.GetPropertyItem(271).Value).Replace("\0", "\r\n"); cameraFactory += encoding.GetString(image.GetPropertyItem(272).Value); this.cameraFactoryTextBox.Text = cameraFactory; Text = "카메라 사진 크기 측정하기 " + " - " + openFileDialog.FileName; } catch { } } } #endregion #region 종료 메뉴 항목 클릭시 처리하기 - exitMenuItem_Click(sender, e) /// <summary> /// 종료 메뉴 항목 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void exitMenuItem_Click(object sender, EventArgs e) { Application.Exit(); } #endregion #region 썸네일 픽처 박스 마우스 DOWN 처리하기 - thumbnailPictureBox_MouseDown(sender, e) /// <summary> /// 썸네일 픽처 박스 마우스 DOWN 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void thumbnailPictureBox_MouseDown(object sender, MouseEventArgs e) { try { this.startX = this.thumbnailPictureBox.Image.Width * e.X / this.thumbnailPictureBox.Width; this.startY = this.thumbnailPictureBox.Image.Height * e.Y / this.thumbnailPictureBox.Height; UpdatePictureBox(); } catch { } } #endregion #region 축소/확대 트랙바 스크롤시 처리하기 - zoomTrackBar_Scroll(sender, e) /// <summary> /// 축소/확대 트랙바 스크롤시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void zoomTrackBar_Scroll(object sender, EventArgs e) { SetZoom(); } #endregion #region 초점 거리 텍스트 박스 텍스트 변경시 처리하기 - foscalLengthTextBox_TextChanged(sender, e) /// <summary> /// 초점 거리 텍스트 박스 텍스트 변경시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void foscalLengthTextBox_TextChanged(object sender, EventArgs e) { string equivalenceString = string.Empty; try { double equivalence = Math.Pow((Math.Pow(Convert.ToSingle(this.sensorWidthTextBox.Text), 2) + Math.Pow(Convert.ToSingle(this.sensorHeightTextBox.Text), 2)), 0.5); equivalence = Math.Round((43.2666153 / equivalence) * Convert.ToSingle(this.foscalLengthTextBox.Text)); equivalenceString = equivalence.ToString(); } catch { } this.equivalentTextBox.Text = equivalenceString; } #endregion #region 카메라 공장 텍스트 박스 텍스트 변경시 처리하기 - cameraFactoryTextBox_TextChanged(sender, e) /// <summary> /// 카메라 공장 텍스트 박스 텍스트 변경시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void cameraFactoryTextBox_TextChanged(object sender, EventArgs e) { SearchCamera(); } #endregion #region 객체 크기 텍스트 박스 클릭시 처리하기 - objectSizeTextBox_Click(sender, e) /// <summary> /// 객체 크기 텍스트 박스 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void objectSizeTextBox_Click(object sender, EventArgs e) { this.objectSizeTextBox.SelectionStart = 0; this.objectSizeTextBox.SelectionLength = this.objectSizeTextBox.Text.Length; } #endregion #region 객체 크기 텍스트 박스 텍스트 변경시 처리하기 - objectSizeTextBox_TextChanged(sender, e) /// <summary> /// 객체 크기 텍스트 박스 텍스트 변경시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void objectSizeTextBox_TextChanged(object sender, EventArgs e) { if(this.objectSizeTextBox.Selected) { try { SetFindButton(true); this.objectSize = Convert.ToDouble(this.objectSizeTextBox.Text) * this.objectSizeScale; SetObjectDistance(); } catch { } } } #endregion #region 객체 크기 스케일 콤보 박스 텍스트 변경시 처리하기 - objectSizeScaleComboBox_TextChanged(sender, e) /// <summary> /// 객체 크기 스케일 콤보 박스 텍스트 변경시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void objectSizeScaleComboBox_TextChanged(object sender, EventArgs e) { this.objectSizeScale = GetSize(this.objectSizeScaleComboBox.Text); this.objectSizeTextBox.Text = Convert.ToString(Math.Round(this.objectSize / this.objectSizeScale, 2)); } #endregion #region 객체 크기 스케일 콤보 박스 드롭 다운 닫은 경우 처리하기 - objectSizeScaleComboBox_DropDownClosed(sender, e) /// <summary> /// 객체 크기 스케일 콤보 박스 드롭 다운 닫은 경우 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void objectSizeScaleComboBox_DropDownClosed(object sender, EventArgs e) { this.zoomTrackBar.Select(); } #endregion #region 거리 찾기 버튼 클릭시 처리하기 - findDistanceButton_Click(sender, e) /// <summary> /// 거리 찾기 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void findDistanceButton_Click(object sender, EventArgs e) { SetFindButton(true); } #endregion #region 크기 찾기 버튼 클릭시 처리하기 - findSizeButton_Click(sender, e) /// <summary> /// 크기 찾기 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void findSizeButton_Click(object sender, EventArgs e) { SetFindButton(false ); } #endregion #region 객체 거리 텍스트 박스 클릭시 처리하기 - objectDistanceTextBox_Click(sender, e) /// <summary> /// 객체 거리 텍스트 박스 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void objectDistanceTextBox_Click(object sender, EventArgs e) { this.objectDistanceTextBox.SelectionStart = 0; this.objectDistanceTextBox.SelectionLength = this.objectDistanceTextBox.Text.Length; } #endregion #region 객체 거리 텍스트 박스 텍스트 변경시 처리하기 - objectDistanceTextBox_TextChanged(sender, e) /// <summary> /// 객체 거리 텍스트 박스 텍스트 변경시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void objectDistanceTextBox_TextChanged(object sender, EventArgs e) { if(this.objectDistanceTextBox.Selected) { try { SetFindButton(false); this.objectDistance = Convert.ToDouble(this.objectDistanceTextBox.Text) * this.objectDistanceScale; SetObjectSize(); } catch { } } } #endregion #region 객체 거리 스케일 콤보 박스 텍스트 변경시 처리하기 - objectDistanceSacleComboBox_TextChanged(sender, e) /// <summary> /// 객체 거리 스케일 콤보 박스 텍스트 변경시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void objectDistanceSacleComboBox_TextChanged(object sender, EventArgs e) { this.objectDistanceScale = GetSize(this.objectDistanceSacleComboBox.Text); this.objectDistanceTextBox.Text = Convert.ToString(Math.Round(this.objectDistance / this.objectDistanceScale, 2)); } #endregion #region 객체 거리 스케일 콤보 박스 드롭 다운 닫은 경우 처리하기 - objectDistanceSacleComboBox_DropDownClosed(sender, e) /// <summary> /// 객체 거리 스케일 콤보 박스 드롭 다운 닫은 경우 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void objectDistanceSacleComboBox_DropDownClosed(object sender, EventArgs e) { this.zoomTrackBar.Select(); } #endregion #region 이미지 이동 버튼 클릭시 처리하기 - moveImageButton_Click(sender, e) /// <summary> /// 이미지 이동 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void moveImageButton_Click(object sender, EventArgs e) { this.moveImageButton.Checked = true; this.measureButton.Checked = false; this.mainPictureBox.Cursor = Cursors.Hand; } #endregion #region 측정 버튼 클릭시 처리하기 - measureButton_Click(sender, e) /// <summary> /// 측정 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void measureButton_Click(object sender, EventArgs e) { this.moveImageButton.Checked = false; this.measureButton.Checked = true; this.mainPictureBox.Cursor = Cursors.Cross; } #endregion #region 메인 픽처 박스 마우스 DOWN 처리하기 - mainPictureBox_MouseDown(sender, e) /// <summary> /// 메인 픽처 박스 마우스 DOWN 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void mainPictureBox_MouseDown(object sender, MouseEventArgs e) { if(this.moveImageButton.Checked) { this.moveX = e.X; this.moveY = e.Y; } else { this.measureStartX = e.X; this.measureStartY = e.Y; } } #endregion #region 메인 픽처 박스 마우스 이동시 처리하기 - mainPictureBox_MouseMove(sender, e) /// <summary> /// 메인 픽처 박스 마우스 이동시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void mainPictureBox_MouseMove(object sender, MouseEventArgs e) { if(e.Button == MouseButtons.Left) { if(this.moveImageButton.Checked) { this.startX -= e.X - this.moveX; if(this.startX < 0) { this.startX = 0; } this.startY -= e.Y - this.moveY; if(this.startY < 0) { this.startY = 0; } this.moveX = e.X; this.moveY = e.Y; UpdatePictureBox(); } else { try { double differenceX = Math.Abs(this.measureStartX - e.X) * this.zoom * Convert.ToSingle(this.horizontal ? this.sensorWidthTextBox.Text : this.sensorHeightTextBox.Text) / Convert.ToSingle(this.imageWidthTextBox.Text ); double differenceY = Math.Abs(this.measureStartY - e.Y) * this.zoom * Convert.ToSingle(this.horizontal ? this.sensorHeightTextBox.Text : this.sensorWidthTextBox.Text ) / Convert.ToSingle(this.imageHeightTextBox.Text); this.measure = Math.Pow((Math.Pow(differenceX, 2) + Math.Pow(differenceY, 2)), 0.5); this.sizeOnSensorLabel.Text = "센서상 크기 (mm) : " + this.measure.ToString(); this.mainPictureBox.Refresh(); Graphics graphics = mainPictureBox.CreateGraphics(); graphics.ResetClip(); graphics.DrawLine(new Pen(Color.Red), this.measureStartX, this.measureStartY, e.X, e.Y); if(this.findDistanceButton.Checked) { SetObjectDistance(); } else { SetObjectSize(); } } catch { } } } try { float fileX = this.startX + e.X * this.zoom; float fileY = this.startY + e.Y * this.zoom; float sensorX = fileX * Convert.ToSingle(this.horizontal ? this.sensorWidthTextBox.Text : this.sensorHeightTextBox.Text) / Convert.ToSingle(this.imageWidthTextBox.Text ); float sensorY = fileY * Convert.ToSingle(this.horizontal ? this.sensorHeightTextBox.Text : this.sensorWidthTextBox.Text ) / Convert.ToSingle(this.imageHeightTextBox.Text); this.locationOnFileLabel.Text = "파일상 위치 (pixel) X :" + fileX.ToString() + " Y : " + fileY.ToString(); this.locationOnSenserLabel.Text= "센서상 위치 (mm) X : " + sensorX.ToString() + " Y : " + sensorY.ToString(); } catch { } } #endregion #region 카메라 메뉴 항목 클릭시 처리하기 - cameraMenuItem_Click(sender, e) /// <summary> /// 카메라 메뉴 항목 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void cameraMenuItem_Click(object sender, EventArgs e) { this.cameraFactoryTextBox.Text = ((ToolStripItem)sender).OwnerItem.Text; this.cameraFactoryTextBox.Text += "\r\n" + ((ToolStripItem)sender).OwnerItem.Text + " " + ((ToolStripItem)sender).Text; } #endregion //////////////////////////////////////////////////////////////////////////////// Function #region 카메라 메뉴 항목 구축하기 - BuildCameraMenuItem() /// <summary> /// 카메라 메뉴 항목 구축하기 /// </summary> private void BuildCameraMenuItem() { this.cameraInfoList.Clear(); this.cameraMenuItem.DropDownItems.Clear(); string cameraListFilePath = Path.Combine(Application.StartupPath, @"DATA\CameraList.info"); if(File.Exists(cameraListFilePath)) { string content = File.ReadAllText(cameraListFilePath); string[] lineArray = content.Split('\n'); CultureInfo cultureInfo = new CultureInfo("en-US"); foreach(string line in lineArray) { if(string.IsNullOrWhiteSpace(line)) { continue; } if(line.StartsWith("//")) { continue; } string[] tokenArray = line.Split(new string[] { "," }, StringSplitOptions.None); try { CameraInfo cameraInfo = new CameraInfo(); cameraInfo.Factory = tokenArray[0].Trim(); cameraInfo.Model = tokenArray[1].Trim(); cameraInfo.AliasName = tokenArray[2].Trim(); cameraInfo.SensorType = tokenArray[3].Trim(); cameraInfo.SensorWidth = Single.Parse(tokenArray[4], cultureInfo); cameraInfo.SensorHeight = Single.Parse(tokenArray[5], cultureInfo); this.cameraInfoList.Add(cameraInfo); bool newFactory = true; foreach(ToolStripMenuItem menuItem in this.cameraMenuItem.DropDownItems) { if(menuItem.Text.Contains(cameraInfo.Factory)) { newFactory = false; break; } } if(newFactory) { this.cameraMenuItem.DropDownItems.Add(cameraInfo.Factory); } foreach(ToolStripMenuItem menuItem in this.cameraMenuItem.DropDownItems) { if(menuItem.Text.Contains(cameraInfo.Factory)) { menuItem.DropDownItems.Add(cameraInfo.Model + (cameraInfo.AliasName == "" ? "" : " - " + cameraInfo.AliasName ), null, cameraMenuItem_Click); } } } catch { } } } } #endregion #region 픽처 박스 업데이트 하기 - UpdatePictureBox() /// <summary> /// 픽처 박스 업데이트 하기 /// </summary> private void UpdatePictureBox() { try { this.bitmap = new Bitmap(this.mainPictureBox.Width, this.mainPictureBox.Height); Graphics bitmapGraphics = Graphics.FromImage(this.bitmap); bitmapGraphics.SmoothingMode = SmoothingMode.AntiAlias; bitmapGraphics.DrawImage ( this.thumbnailPictureBox.Image, new Rectangle(0, 0, this.mainPictureBox.Width, this.mainPictureBox.Height), new Rectangle(this.startX, this.startY, (int)(this.mainPictureBox.Width * this.zoom), (int)(this.mainPictureBox.Height * this.zoom)), GraphicsUnit.Pixel ); this.mainPictureBox.Image = this.bitmap; } catch { } } #endregion #region 카메라 찾기 - SearchCamera() /// <summary> /// 카메라 찾기 /// </summary> private void SearchCamera() { this.sensorTypeTextBox.Text = string.Empty; this.sensorHeightTextBox.Text = string.Empty; this.sensorWidthTextBox.Text = string.Empty; this.cameraPictureBox.Image = null; this.toolTip.SetToolTip(this.cameraPictureBox, string.Empty); string searchControl = "MRK"; string camereName = this.cameraFactoryTextBox.Text.Replace(" ", "").Replace("-", "").ToLower() + searchControl; bool cameraFound = false; byte cameraLoop = 0; do { foreach(CameraInfo cameraInfo in this.cameraInfoList) { if(camereName.Contains(cameraInfo.Factory.Replace(" ", "").ToLower()) && !cameraFound) { if(camereName.Contains(cameraInfo.Model.Replace(" ", "").Replace("-", "").ToLower() + searchControl) || (camereName.Contains(cameraInfo.AliasName.Replace(" ", "").Replace("-", "").ToLower() + searchControl) && cameraInfo.AliasName != "")) { this.sensorTypeTextBox.Text = cameraInfo.SensorType; this.sensorWidthTextBox.Text = cameraInfo.SensorWidth.ToString(); this.sensorHeightTextBox.Text = cameraInfo.SensorHeight.ToString(); this.toolTip.SetToolTip(this.cameraPictureBox, cameraInfo.Factory + " " + cameraInfo.Model); string cameraImageFilePath = Application.StartupPath + "\\Data\\" + cameraInfo.Factory + "_" + cameraInfo.Model.Replace(" ", "").Replace("-", "") + ".gif"; if(File.Exists(cameraImageFilePath)) { this.cameraPictureBox.Image = Image.FromFile(cameraImageFilePath); } cameraFound = true; } } } searchControl = string.Empty; cameraLoop++; } while(!cameraFound && cameraLoop < 2); } #endregion #region 축소/확대 설정하기 - SetZoom() /// <summary> /// 축소/확대 설정하기 /// </summary> private void SetZoom() { this.zoom = 50 / (float)zoomTrackBar.Value; this.toolTip.SetToolTip(zoomTrackBar ,"줌 배율 : " + Convert.ToString((100 / this.zoom)) + "%"); UpdatePictureBox(); } #endregion #region 부호 없는 정수 구하기 - GetUnsignedInteger(sourceArray) /// <summary> /// 부호 없는 정수 구하기 /// </summary> /// <param name="sourceArray">소스 배열</param> /// <returns>부호 없는 정수</returns> private uint GetUnsignedInteger(byte[] sourceArray) { if(sourceArray.Length != 4) { return 0; } else { return Convert.ToUInt32(sourceArray[3] << 24 | sourceArray[2] << 16 | sourceArray[1] << 8 | sourceArray[0]); } } #endregion #region 객체 거리 설정하기 - SetObjectDistance() /// <summary> /// 객체 거리 설정하기 /// </summary> private void SetObjectDistance() { this.objectDistanceTextBox.Text = string.Empty; try { this.objectDistance = this.objectSize / (this.measure / Convert.ToDouble(this.foscalLengthTextBox.Text)); this.objectDistanceTextBox.Text = Convert.ToString(Math.Round(this.objectDistance / this.objectDistanceScale, 2)); } catch { } } #endregion #region 객체 크기 설정하기 - SetObjectSize() /// <summary> /// 객체 크기 설정하기 /// </summary> private void SetObjectSize() { this.objectSizeTextBox.Text = string.Empty; try { this.objectSize = this.objectDistance * (this.measure / Convert.ToDouble(this.foscalLengthTextBox.Text)); this.objectSizeTextBox.Text = Convert.ToString(Math.Round(this.objectSize / this.objectSizeScale, 2)); } catch { } } #endregion #region 찾기 버튼 설정하기 - SetFindButton(isChecked) /// <summary> /// 찾기 버튼 설정하기 /// </summary> /// <param name="isChecked">체크 여부</param> private void SetFindButton(bool isChecked) { this.findDistanceButton.Checked = isChecked; this.findSizeButton.Checked = !isChecked; if(isChecked) { SetObjectDistance(); } else { SetObjectSize(); } } #endregion #region 크기 구하기 - GetSize(sizeUnit) /// <summary> /// 크기 구하기 /// </summary> /// <param name="sizeUnit">크기 단위</param> /// <returns>크기</returns> private double GetSize(string sizeUnit) { switch(sizeUnit.Trim().ToLower()) { case "mm" : return .001; case "cm" : return .01; case "m" : return 1; case "km" : return 1000; case "inch" : return .0254; case "foot" : return .3048; case "mile" : return 1609.344; } return 0; } #endregion } } |
TestProject.zip
■ 카메라 컨트롤을 사용하는 방법을 보여준다. ▶ CameraControl.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 |
using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Windows.Forms; using DirectShowLib; namespace TestProject { /// <summary> /// 카메라 컨트롤 /// </summary> [Guid("43878F19-1E0E-42d2-B72B-88A94418A302")] [ComVisible(true)] public partial class CameraControl : UserControl { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// WM_GRAPHNOTIFY /// </summary> private int WM_GRAPHNOTIFY = Convert.ToInt32("0X8000", 16) + 1; /// <summary> /// 비디오 윈도우 /// </summary> private IVideoWindow vidoeWindow = null; /// <summary> /// 미디어 컨트롤 /// </summary> private IMediaControl mediaControl = null; /// <summary> /// 미디어 이벤트 확장 /// </summary> private IMediaEventEx mediaEventEx = null; /// <summary> /// 그래프 빌더 /// </summary> private IGraphBuilder graphBuilder = null; /// <summary> /// 캡처 그래프 빌더 2 /// </summary> private ICaptureGraphBuilder2 captureGraphBuilder2 = null; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - CameraControl() /// <summary> /// 생성자 /// </summary> public CameraControl() { InitializeComponent(); Load += UserControl_Load; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Protected //////////////////////////////////////////////////////////////////////////////// Event #region 윈도우 프로시저 처리하기 - WndProc(message) /// <summary> /// 윈도우 프로시저 처리하기 /// </summary> /// <param name="message">메시지</param> protected override void WndProc(ref Message message) { if(message.Msg == WM_GRAPHNOTIFY) { HandleGraphEvent(); } if(this.vidoeWindow != null) { this.vidoeWindow.NotifyOwnerMessage ( message.HWnd , message.Msg , message.WParam.ToInt32(), message.LParam.ToInt32() ); } base.WndProc(ref message); } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Private //////////////////////////////////////////////////////////////////////////////// Event #region 사용자 컨트롤 로드시 처리하기 - UserControl_Load(sender, e) /// <summary> /// 사용자컨트롤 로드시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void UserControl_Load(object sender, EventArgs e) { Resize += UserControl_Resize; } #endregion #region 사용자 컨트롤 크기 변경시 처리하기 - Control_Resize(sender, e) /// <summary> /// 사용자 컨트롤 크기 변경시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void UserControl_Resize(object sender, EventArgs e) { if(this.vidoeWindow != null) { this.vidoeWindow.SetWindowPosition(0, 0, Width, ClientSize.Height); } } #endregion //////////////////////////////////////////////////////////////////////////////// Function #region 인터페이스 설정하기 - SetInterfaces() /// <summary> /// 인터페이스 설정하기 /// </summary> private void SetInterfaces() { this.graphBuilder = (IGraphBuilder)(new FilterGraph()); this.captureGraphBuilder2 = (ICaptureGraphBuilder2)(new CaptureGraphBuilder2()); this.mediaControl = (IMediaControl)this.graphBuilder; this.vidoeWindow = (IVideoWindow)this.graphBuilder; this.mediaEventEx = (IMediaEventEx)this.graphBuilder; int resultHandle = this.mediaEventEx.SetNotifyWindow(Handle, WM_GRAPHNOTIFY, IntPtr.Zero); DsError.ThrowExceptionForHR(resultHandle); } #endregion #region 캡처 디바이스 찾기 - FindCaptureDevice() /// <summary> /// 캡처 디바이스 찾기 /// </summary> /// <returns>베이스 필터 인터페이스</returns> private IBaseFilter FindCaptureDevice() { UCOMIEnumMoniker ucomIEnumMoniker = null; UCOMIMoniker[] uconIMonikerArray = new UCOMIMoniker[1]; object source = null; ICreateDevEnum createDevEnum = (ICreateDevEnum)(new CreateDevEnum()); int resultHandle = createDevEnum.CreateClassEnumerator(FilterCategory.VideoInputDevice, out ucomIEnumMoniker, CDef.None); DsError.ThrowExceptionForHR(resultHandle); Marshal.ReleaseComObject(createDevEnum); if(ucomIEnumMoniker == null) { throw new ApplicationException ( "No video capture device was detected.\\r\\n\\r\\n" + "This sample requires a video capture device, such as a USB WebCam,\\r\\n" + "to be installed and working properly. The sample will now close." ); } int none = 0; if(ucomIEnumMoniker.Next(uconIMonikerArray.Length, uconIMonikerArray, out none) == 0) { Guid guid = typeof(IBaseFilter).GUID; uconIMonikerArray[0].BindToObject(null, null, ref guid, out source); } else { throw new ApplicationException("Unable to access video capture device!"); } Marshal.ReleaseComObject(uconIMonikerArray[0]); Marshal.ReleaseComObject(ucomIEnumMoniker); return (IBaseFilter)source; } #endregion #region 비디오 윈도우 셋업하기 - SetupVideoWindow() /// <summary> /// 비디오 윈도우 셋업하기 /// </summary> private void SetupVideoWindow() { int resultHandle = 0; resultHandle = this.vidoeWindow.put_Owner(Handle); DsError.ThrowExceptionForHR(resultHandle); resultHandle = this.vidoeWindow.put_WindowStyle(WindowStyle.Child | WindowStyle.ClipChildren); DsError.ThrowExceptionForHR(resultHandle); UserControl_Resize(this, null); resultHandle = this.vidoeWindow.put_Visible(OABool.True); DsError.ThrowExceptionForHR(resultHandle); } #endregion #region 비디오 캡처하기 - CaptureVideo() /// <summary> /// 비디오 캡처하기 /// </summary> public void CaptureVideo() { int resultHandle = 0; IBaseFilter sourceBaseFilter = null; try { SetInterfaces(); resultHandle = this.captureGraphBuilder2.SetFiltergraph(this.graphBuilder); DsError.ThrowExceptionForHR(resultHandle); sourceBaseFilter = FindCaptureDevice(); resultHandle = this.graphBuilder.AddFilter(sourceBaseFilter, "WebCamControl Video"); DsError.ThrowExceptionForHR(resultHandle); resultHandle = this.captureGraphBuilder2.RenderStream ( PinCategory.Preview, MediaType.Video, sourceBaseFilter, null, null ); Debug.WriteLine(DsError.GetErrorText(resultHandle)); DsError.ThrowExceptionForHR(resultHandle); Marshal.ReleaseComObject(sourceBaseFilter); SetupVideoWindow(); resultHandle = this.mediaControl.Run(); DsError.ThrowExceptionForHR(resultHandle); } catch(Exception exception) { MessageBox.Show("An unrecoverable error has occurred.\r\n" + exception.ToString()); } } #endregion #region 그래프 이벤트 처리하기 - HandleGraphEvent() /// <summary> /// 그래프 이벤트 처리하기 /// </summary> private void HandleGraphEvent() { int resultHandle = 0; EventCode eventCode = 0; int eventParameter1 = 0; int eventParameter2 = 0; while(this.mediaEventEx != null && this.mediaEventEx.GetEvent(out eventCode, out eventParameter1, out eventParameter2, 0) == 0) { resultHandle = this.mediaEventEx.FreeEventParams(eventCode, eventParameter1, eventParameter2); DsError.ThrowExceptionForHR(resultHandle); } } #endregion #region 인터페이스 해제하기 - ReleaseInterfaces() /// <summary> /// 인터페이스 해제하기 /// </summary> public void ReleaseInterfaces() { if(this.mediaControl != null) { this.mediaControl.StopWhenReady(); } if(this.mediaEventEx != null) { this.mediaEventEx.SetNotifyWindow(IntPtr.Zero, WM_GRAPHNOTIFY, IntPtr.Zero); } if(this.vidoeWindow != null) { this.vidoeWindow.put_Visible(OABool.False); this.vidoeWindow.put_Owner(IntPtr.Zero); } Marshal.ReleaseComObject(this.mediaControl); this.mediaControl = null; Marshal.ReleaseComObject(this.mediaEventEx); this.mediaEventEx = null; Marshal.ReleaseComObject(this.vidoeWindow); this.vidoeWindow = null; Marshal.ReleaseComObject(this.graphBuilder); this.graphBuilder = null; Marshal.ReleaseComObject(this.captureGraphBuilder2); this.captureGraphBuilder2 = null; } #endregion } } |
▶ MainForm.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
using System; using System.Windows.Forms; namespace TestProject { /// <summary> /// 메인 폼 /// </summary> public partial class MainForm : Form { //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - MainForm() /// <summary> /// 생성자 /// </summary> public MainForm() { InitializeComponent(); } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Private //////////////////////////////////////////////////////////////////////////////// Event #region 재생 버튼 클릭시 처리하기 - playButton_Click(sender, e) /// <summary> /// 재생 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void playButton_Click(object sender, EventArgs e) { if(this.playButton.Text == "캡처 시작") { this.playButton.Text = "캡처 종료"; this.xWebCamControl.CaptureVideo(); } else { this.playButton.Text = "캡처 시작"; this.xWebCamControl.ReleaseInterfaces(); } } #endregion } } |
※ 윈도우즈 7에서만 실행된다. TestProject.zip
■ 웹 카메라를 사용하는 방법을 보여준다. ▶ MainPage.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 |
<Page x:Class="TestApplication.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:TestApplication" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"> <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> <Grid.ChildrenTransitions> <TransitionCollection> <EntranceThemeTransition /> </TransitionCollection> </Grid.ChildrenTransitions> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> </Grid.RowDefinitions> <TextBlock Grid.Row="0" Style="{StaticResource HeaderTextBlockStyle}" HorizontalAlignment="Center" VerticalAlignment="Center" IsHitTestVisible="false" TextWrapping="NoWrap" Text="웹 카메라 테스트" /> <StackPanel Grid.Row="1" HorizontalAlignment="Center" VerticalAlignment="Center" Orientation="Horizontal"> <Button x:Name="initializeVideoButton" HorizontalAlignment="Left" Margin="10" Width="180" Content="비디오 초기화" /> <Button x:Name="initializeAudioButton" Margin="10" Width="120" Content="오디오 초기화" /> <Button x:Name="closeCameraButton" Margin="10" Width="120" Content="카메라 닫기" /> </StackPanel> <StackPanel Grid.Row="2" HorizontalAlignment="Center" VerticalAlignment="Center" Orientation="Horizontal"> <Button x:Name="takePhotoButton" Margin="10" Width="120" IsEnabled="False" Content="사진 찍기" /> <Button x:Name="recordVideoButton" Margin="10" Width="150" IsEnabled="False" Content="비디오 기록 시작" /> <Button x:Name="recordAudioButton" Margin="10" Width="150" IsEnabled="False" Content="오디오 기록 시작" /> </StackPanel> <StackPanel Grid.Row="3" HorizontalAlignment="Center" VerticalAlignment="Center" Orientation="Horizontal"> <StackPanel Margin="10"> <TextBlock Name="previewTextBlock" HorizontalAlignment="Center" Height="30" Margin="10" Text="미리 보기" /> <Canvas Name="previewCanvas" Width="300" Height="300" Background="Gray" Visibility="Visible"> <CaptureElement x:Name="previewCaptureElement" HorizontalAlignment="Left" Width="{Binding ElementName=previewCanvas, Path=ActualWidth}" Height="{Binding ElementName=previewCanvas, Path=ActualHeight}" Visibility="Visible" /> </Canvas> </StackPanel> <StackPanel Margin="10"> <TextBlock Name="lastCapturedPhotoTextBlock" HorizontalAlignment="Center" Margin="10" Height="30" Visibility="Visible" Text="마지막 촬영 사진" /> <Canvas Name="lastCapturedPhotoCanvas" Width="300" Height="300" Background="Gray" Visibility="Visible"> <Image x:Name="lastCapturedPhotoImage" Width="{Binding ElementName=lastCapturedPhotoCanvas, Path=ActualWidth}" Height="{Binding ElementName=lastCapturedPhotoCanvas, Path=ActualHeight}" Visibility="Visible" /> </Canvas> </StackPanel> <StackPanel Margin="10"> <TextBlock Name="lastRecordedVideoTextBlock" HorizontalAlignment="Center" Margin="10" Height="30" Visibility="Visible" Text="마지막 기록 비디오" /> <Canvas Name="lastRecordedVideoCanvas" Width="300" Height="300" Background="Gray" Visibility="Visible"> <MediaElement x:Name="lastRecordedVideoMediaElement" Width="{Binding ElementName=lastRecordedVideoCanvas, Path=ActualWidth}" Height="{Binding ElementName=lastRecordedVideoCanvas, Path=ActualHeight}" Visibility="Visible" /> </Canvas> </StackPanel> <StackPanel> <Canvas Margin="0" Width="0" Height="0"> <MediaElement x:Name="playbackMediaElement" Width="0" Height="0" /> </Canvas> </StackPanel> </StackPanel> <TextBlock Grid.Row="4" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="10" Text="status" /> <TextBox x:Name="statusTextBlock" Grid.Row="5" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="10" Height="100" Width="600" TextWrapping="Wrap" IsReadOnly="True" /> </Grid> </Page> |
▶ MainPage.xaml.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 |
using System; using Windows.Media; using Windows.Media.Capture; using Windows.Media.MediaProperties; using Windows.Storage; using Windows.Storage.Streams; using Windows.UI.Core; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Media.Imaging; namespace TestApplication { /// <summary> /// 메인 페이지 /// </summary> public sealed partial class MainPage : Page { //////////////////////////////////////////////////////////////////////////////////////////////////// Enumeration ////////////////////////////////////////////////////////////////////////////////////////// Private #region 액션 - Action /// <summary> /// 액션 /// </summary> private enum Action { /// <summary> /// 활성화 /// </summary> ENABLED, /// <summary> /// 비활성화 /// </summary> DISABLED } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 미디어 캡처 파일 /// </summary> private MediaCapture mediaCapture; /// <summary> /// 사진 파일명 /// </summary> private readonly string PHOTO_FILE_NAME = "photo.png"; /// <summary> /// 비디오 파일명 /// </summary> private readonly string VIDEO_FILE_NAME = "video.mp4"; /// <summary> /// 오디오 파일명 /// </summary> private readonly string AUDIO_FILE_NAME = "audio.mp3"; /// <summary> /// 사진 저장소 파일 /// </summary> private StorageFile photoStorageFile; /// <summary> /// 비디오 저장소 파일 /// </summary> private StorageFile videoStorageFile; /// <summary> /// 오디오 저장소 파일 /// </summary> private StorageFile audioStorageFile; /// <summary> /// 미리보기 여부 /// </summary> private bool isPreviewing; /// <summary> /// 레코딩 여부 /// </summary> private bool isRecording; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - MainPage() /// <summary> /// 생성자 /// </summary> public MainPage() { this.InitializeComponent(); SetInitializeButtonVisibility(Action.ENABLED); SetVideoButtonVisibility(Action.DISABLED); SetAudioButtonVisibility(Action.DISABLED); this.isPreviewing = false; this.isRecording = false; this.initializeVideoButton.Click += initializeVideoButton_Click; this.initializeAudioButton.Click += initializeAudioButton_Click; this.closeCameraButton.Click += closeCameraButton_Click; this.takePhotoButton.Click += takePhotoButton_Click; this.recordVideoButton.Click += recordVideoButton_Click; this.recordAudioButton.Click += recordAudioButton_Click; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Private //////////////////////////////////////////////////////////////////////////////// Event #region 비디오 초기화 버튼 클릭시 처리하기 - initializeVideoButton_Click(sender, e) /// <summary> /// 비디오 초기화 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private async void initializeVideoButton_Click(object sender, RoutedEventArgs e) { SetInitializeButtonVisibility(Action.DISABLED); SetVideoButtonVisibility(Action.DISABLED); SetAudioButtonVisibility(Action.DISABLED); try { if(this.mediaCapture != null) { if(this.isPreviewing) { await this.mediaCapture.StopPreviewAsync(); this.lastCapturedPhotoImage.Source = null; this.lastRecordedVideoMediaElement.Source = null; this.isPreviewing = false; } if(isRecording) { await this.mediaCapture.StopRecordAsync(); this.isRecording = false; this.recordVideoButton.Content = "비디오 기록 시작"; this.recordAudioButton.Content = "오디오 기록 시작"; } this.mediaCapture.Dispose(); this.mediaCapture = null; } this.statusTextBlock.Text = "비디오 캡처를 위한 카메라 초기화 중..."; this.mediaCapture = new MediaCapture(); await this.mediaCapture.InitializeAsync(); this.statusTextBlock.Text = "비디오 기록을 위한 장치가 성공적으로 초기화되었습니다!"; this.mediaCapture.Failed += mediaCapture_Failed; this.mediaCapture.RecordLimitationExceeded += mediaCapture_RecordLimitExceeded; this.previewCaptureElement.Source = this.mediaCapture; await this.mediaCapture.StartPreviewAsync(); this.isPreviewing = true; this.statusTextBlock.Text = "카메라 미리보기가 성공했습니다."; SetVideoButtonVisibility(Action.ENABLED); this.initializeAudioButton.IsEnabled = true; } catch(Exception exception) { this.statusTextBlock.Text = "비디오 기록을 위한 카메라 초기화를 할 수 없습니다 : " + exception.Message; } } #endregion #region 오디오 초기화 버튼 클릭시 처리하기 - initializeAudioButton_Click(sender, e) /// <summary> /// 오디오 초기화 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private async void initializeAudioButton_Click(object sender, RoutedEventArgs e) { SetInitializeButtonVisibility(Action.DISABLED); SetVideoButtonVisibility(Action.DISABLED); SetAudioButtonVisibility(Action.DISABLED); try { if(this.mediaCapture != null) { if(this.isPreviewing) { await this.mediaCapture.StopPreviewAsync(); this.lastCapturedPhotoImage.Source = null; this.lastRecordedVideoMediaElement.Source = null; this.isPreviewing = false; } if(this.isRecording) { await this.mediaCapture.StopRecordAsync(); this.isRecording = false; this.recordVideoButton.Content = "비디오 기록 시작"; this.recordAudioButton.Content = "오디오 기록 시작"; } this.mediaCapture.Dispose(); this.mediaCapture = null; } this.statusTextBlock.Text = "오디오 캡처를 위한 카메라 초기화 중..."; this.mediaCapture = new MediaCapture(); MediaCaptureInitializationSettings mediaCaptureInitializationSettings = new MediaCaptureInitializationSettings(); mediaCaptureInitializationSettings.StreamingCaptureMode = StreamingCaptureMode.Audio; mediaCaptureInitializationSettings.MediaCategory = MediaCategory.Other; mediaCaptureInitializationSettings.AudioProcessing = AudioProcessing.Default; await this.mediaCapture.InitializeAsync(mediaCaptureInitializationSettings); this.statusTextBlock.Text = "오디오 기록을 위한 장치가 성공적으로 초기화되었습니다!" + "\n기록을 시작하기 위해 \'오디오 기록 시작\' 버튼을 누르시기 바랍니다."; this.mediaCapture.Failed += mediaCapture_Failed; this.mediaCapture.RecordLimitationExceeded += mediaCapture_RecordLimitExceeded; SetAudioButtonVisibility(Action.ENABLED); this.initializeVideoButton.IsEnabled = true; } catch(Exception exception) { this.statusTextBlock.Text = "오디오 기록을 위한 카메라 초기화를 할 수 없습니다 : " + exception.Message; } } #endregion #region 카메라 닫기 버튼 클릭시 처리하기 - closeCameraButton_Click(sender, e) /// <summary> /// 카메라 닫기 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void closeCameraButton_Click(object sender, RoutedEventArgs e) { SetInitializeButtonVisibility(Action.DISABLED); SetVideoButtonVisibility(Action.DISABLED); SetAudioButtonVisibility(Action.DISABLED); ProcessCloseCamera(); } #endregion #region 미디어 캡처 실패시 처리하기 - mediaCapture_Failed(mediaCapture, e) /// <summary> /// 미디어 캡처 실패시 처리하기 /// </summary> /// <param name="mediaCapture">미디어 캡처</param> /// <param name="e">이벤트 인자</param> private async void mediaCapture_Failed(MediaCapture mediaCapture, MediaCaptureFailedEventArgs e) { await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () => { try { this.statusTextBlock.Text = "미디어 캡처 실패 : " + e.Message; if(this.isRecording) { await this.mediaCapture.StopRecordAsync(); this.statusTextBlock.Text += "\n 기록이 중단되었습니다."; } } catch(Exception) { } finally { SetInitializeButtonVisibility(Action.DISABLED); SetVideoButtonVisibility(Action.DISABLED); SetAudioButtonVisibility(Action.DISABLED); this.statusTextBlock.Text += "\n카메라가 연결되어 있는지 체크하시기 바랍니다. 앱을 다시 시작해 주시기 바랍니다."; } }); } #endregion #region 미디어 캡처 기록 제한 초과시 처리하기 - mediaCapture_RecordLimitExceeded(mediaCapture) /// <summary> /// 미디어 캡처 기록 제한 초과시 처리하기 /// </summary> /// <param name="mediaCapture">미디어 캡처</param> public async void mediaCapture_RecordLimitExceeded(MediaCapture mediaCapture) { try { if(this.isRecording) { await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () => { try { this.statusTextBlock.Text = "최대 기록 시간을 초과해 기록을 중단하고 있습니다."; await this.mediaCapture.StopRecordAsync(); this.isRecording = false; this.recordVideoButton.Content = "비디오 기록 시작"; this.recordAudioButton.Content = "오디오 기록 시작"; if(this.mediaCapture.MediaCaptureSettings.StreamingCaptureMode == StreamingCaptureMode.Audio) { this.statusTextBlock.Text = "최대 기록 시간을 초과해 기록을 중단했습니다 : " + this.audioStorageFile.Path; } else { this.statusTextBlock.Text = "최대 기록 시간을 초과해 기록을 중단했습니다 : " + this.videoStorageFile.Path; } } catch(Exception exception) { this.statusTextBlock.Text = exception.Message; } }); } } catch(Exception exception) { this.statusTextBlock.Text = exception.Message; } } #endregion #region 사진 찍기 버튼 클릭시 처리하기 - takePhotoButton_Click(sender, e) /// <summary> /// 사진 찍기 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private async void takePhotoButton_Click(object sender, RoutedEventArgs e) { try { this.takePhotoButton.IsEnabled = false; this.recordVideoButton.IsEnabled = false; this.lastCapturedPhotoImage.Source = null; this.photoStorageFile = await KnownFolders.PicturesLibrary.CreateFileAsync(PHOTO_FILE_NAME, CreationCollisionOption.GenerateUniqueName); ImageEncodingProperties imageEncodingProperties = ImageEncodingProperties.CreatePng(); await this.mediaCapture.CapturePhotoToStorageFileAsync(imageEncodingProperties, this.photoStorageFile); this.takePhotoButton.IsEnabled = true; this.statusTextBlock.Text = "사진 찍기가 성공했습니다 : " + this.photoStorageFile.Path; IRandomAccessStream randomAccessStream = await this.photoStorageFile.OpenReadAsync(); BitmapImage bitmapImage = new BitmapImage(); bitmapImage.SetSource(randomAccessStream); this.lastCapturedPhotoImage.Source = bitmapImage; } catch(Exception exception) { this.statusTextBlock.Text = exception.Message; ProcessCloseCamera(); } finally { this.takePhotoButton.IsEnabled = true; this.recordVideoButton.IsEnabled = true; } } #endregion #region 비디오 기록 버튼 클릭시 처리하기 - recordVideoButton_Click(sender, e) /// <summary> /// 비디오 기록 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private async void recordVideoButton_Click(object sender, RoutedEventArgs e) { try { this.takePhotoButton.IsEnabled = false; this.recordVideoButton.IsEnabled = false; this.lastRecordedVideoMediaElement.Source = null; if(this.recordVideoButton.Content.ToString() == "비디오 기록 시작") { this.takePhotoButton.IsEnabled = false; this.statusTextBlock.Text = "비디오 기록을 초기화 합니다."; this.videoStorageFile = await KnownFolders.VideosLibrary.CreateFileAsync(VIDEO_FILE_NAME, CreationCollisionOption.GenerateUniqueName); this.statusTextBlock.Text = "비디오 저장소 파일이 성공적으로 준비되었습니다."; MediaEncodingProfile mediaEncodingProfile = null; mediaEncodingProfile = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Auto); await this.mediaCapture.StartRecordToStorageFileAsync(mediaEncodingProfile, this.videoStorageFile); this.recordVideoButton.IsEnabled = true; this.recordVideoButton.Content = "비디오 기록 중단"; this.isRecording = true; this.statusTextBlock.Text = "비디오 기록 진행중... 중단하기 위해 \'비디오 기록 중단\' 버튼을 누르시기 바랍니다."; } else { this.takePhotoButton.IsEnabled = true; this.statusTextBlock.Text = "비디오 기록 중단중..."; await this.mediaCapture.StopRecordAsync(); this.isRecording = false; IRandomAccessStreamWithContentType randomAccessStreamWithContentType = await this.videoStorageFile.OpenReadAsync(); this.lastRecordedVideoMediaElement.AutoPlay = true; this.lastRecordedVideoMediaElement.SetSource(randomAccessStreamWithContentType, this.videoStorageFile.FileType); this.lastRecordedVideoMediaElement.Play(); this.statusTextBlock.Text = "기록된 비디오 재생 : " + this.videoStorageFile.Path; this.recordVideoButton.Content = "비디오 기록 시작"; } } catch(Exception exception) { if(exception is UnauthorizedAccessException) { this.statusTextBlock.Text = "기록된 비디오를 재생할 수 없습니다; \'" + this.videoStorageFile.Path + "\'에 비디오가 성공적으로 기록되었습니다."; this.recordVideoButton.Content = "비디오 기록 시작"; } else { this.statusTextBlock.Text = exception.Message; ProcessCloseCamera(); } } finally { this.recordVideoButton.IsEnabled = true; } } #endregion #region 오디오 기록 버튼 클릭시 처리하기 - recordAudioButton_Click(sender, e) /// <summary> /// 오디오 기록 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private async void recordAudioButton_Click(object sender, RoutedEventArgs e) { this.recordAudioButton.IsEnabled = false; this.playbackMediaElement.Source = null; try { if(this.recordAudioButton.Content.ToString() == "오디오 기록 시작") { this.audioStorageFile = await KnownFolders.VideosLibrary.CreateFileAsync(AUDIO_FILE_NAME, CreationCollisionOption.GenerateUniqueName); this.statusTextBlock.Text = "오디오 저장소 파일이 성공적으로 준비되었습니다."; MediaEncodingProfile mediaEncodingProfile = MediaEncodingProfile.CreateM4a(AudioEncodingQuality.Auto); await this.mediaCapture.StartRecordToStorageFileAsync(mediaEncodingProfile, this.audioStorageFile); this.isRecording = true; this.recordAudioButton.IsEnabled = true; this.recordAudioButton.Content = "오디오 기록 중단"; this.statusTextBlock.Text = "오디오 기록 진행중... 중단하기 위해 \'오디오 기록 중단\' 버튼을 누르시기 바랍니다."; } else { this.statusTextBlock.Text = "오디오 기록 중단중..."; await this.mediaCapture.StopRecordAsync(); this.isRecording = false; this.recordAudioButton.IsEnabled = true; this.recordAudioButton.Content = "오디오 기록 시작"; IRandomAccessStream randomAccessStream = await this.audioStorageFile.OpenAsync(FileAccessMode.Read); this.statusTextBlock.Text = "기록된 오디오 재생 : " + this.audioStorageFile.Path; this.playbackMediaElement.AutoPlay = true; this.playbackMediaElement.SetSource(randomAccessStream, this.audioStorageFile.FileType); this.playbackMediaElement.Play(); } } catch(Exception exception) { this.statusTextBlock.Text = exception.Message; ProcessCloseCamera(); } finally { this.recordAudioButton.IsEnabled = true; } } #endregion //////////////////////////////////////////////////////////////////////////////// Function #region 초기화 버튼 표시 여부 설정하기 - SetInitializeButtonVisibility(action) /// <summary> /// 초기화 버튼 표시 여부 설정하기 /// </summary> /// <param name="action">액션</param> private void SetInitializeButtonVisibility(Action action) { if(action == Action.ENABLED) { this.initializeVideoButton.IsEnabled = true; this.initializeAudioButton.IsEnabled = true; } else { this.initializeVideoButton.IsEnabled = false; this.initializeAudioButton.IsEnabled = false; } } #endregion #region 비디오 버튼 표시 여부 설정하기 - SetVideoButtonVisibility(action) /// <summary> /// 비디오 버튼 표시 여부 설정하기 /// </summary> /// <param name="action">액션</param> private void SetVideoButtonVisibility(Action action) { if(action == Action.ENABLED) { this.takePhotoButton.IsEnabled = true; this.takePhotoButton.Visibility = Visibility.Visible; this.recordVideoButton.IsEnabled = true; this.recordVideoButton.Visibility = Visibility.Visible; } else { this.takePhotoButton.IsEnabled = false; this.takePhotoButton.Visibility = Visibility.Collapsed; this.recordVideoButton.IsEnabled = false; this.recordVideoButton.Visibility = Visibility.Collapsed; } } #endregion #region 오디오 버튼 표시 여부 설정하기 - SetAudioButtonVisibility(action) /// <summary> /// 오디오 버튼 표시 여부 설정하기 /// </summary> /// <param name="action">액션</param> private void SetAudioButtonVisibility(Action action) { if(action == Action.ENABLED) { this.recordAudioButton.IsEnabled = true; this.recordAudioButton.Visibility = Visibility.Visible; } else { this.recordAudioButton.IsEnabled = false; this.recordAudioButton.Visibility = Visibility.Collapsed; } } #endregion #region 카메라 닫기 처리하기 - ProcessCloseCamera() /// <summary> /// 카메라 닫기 처리하기 /// </summary> private async void ProcessCloseCamera() { if(this.mediaCapture != null) { if(this.isPreviewing) { await this.mediaCapture.StopPreviewAsync(); this.lastCapturedPhotoImage.Source = null; this.lastRecordedVideoMediaElement.Source = null; this.isPreviewing = false; } if(this.isRecording) { await this.mediaCapture.StopRecordAsync(); this.isRecording = false; this.recordVideoButton.Content = "비디오 기록 시작"; this.recordAudioButton.Content = "오디오 기록 시작"; } this.mediaCapture.Dispose(); this.mediaCapture = null; } SetInitializeButtonVisibility(Action.ENABLED); } #endregion } } |
TestApplication.zip