CamView.xaml.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Windows;
  6. using System.Windows.Controls;
  7. using System.Windows.Documents;
  8. using System.Windows.Input;
  9. using System.Windows.Media;
  10. using System.Windows.Media.Animation;
  11. using System.Windows.Shapes;
  12. using Microsoft.Phone.Controls;
  13. using Microsoft.Devices;
  14. using System.IO;
  15. using System.IO.IsolatedStorage;
  16. using Microsoft.Xna.Framework.Media;
  17. namespace CameraApp.Views
  18. {
  19. public partial class MainView : PhoneApplicationPage
  20. {
  21. // Variables
  22. private int savedCounter = 0;
  23. PhotoCamera cam;
  24. MediaLibrary library = new MediaLibrary();
  25. public MainView()
  26. {
  27. InitializeComponent();
  28. }
  29. //Code for initialization, capture completed, image availability events; also setting the source for the viewfinder.
  30. protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
  31. {
  32. // Check to see if the camera is available on the device.
  33. if ((PhotoCamera.IsCameraTypeSupported(CameraType.Primary) == true) ||
  34. (PhotoCamera.IsCameraTypeSupported(CameraType.FrontFacing) == true))
  35. {
  36. // Initialize the camera, when available.
  37. if (PhotoCamera.IsCameraTypeSupported(CameraType.FrontFacing))
  38. {
  39. // Use front-facing camera if available.
  40. cam = new Microsoft.Devices.PhotoCamera(CameraType.FrontFacing);
  41. }
  42. else
  43. {
  44. // Otherwise, use standard camera on back of device.
  45. cam = new Microsoft.Devices.PhotoCamera(CameraType.Primary);
  46. }
  47. // Event is fired when the PhotoCamera object has been initialized.
  48. cam.Initialized += new EventHandler<Microsoft.Devices.CameraOperationCompletedEventArgs>(cam_Initialized);
  49. // Event is fired when the capture sequence is complete.
  50. cam.CaptureCompleted += new EventHandler<CameraOperationCompletedEventArgs>(cam_CaptureCompleted);
  51. // Event is fired when the capture sequence is complete and an image is available.
  52. cam.CaptureImageAvailable += new EventHandler<Microsoft.Devices.ContentReadyEventArgs>(cam_CaptureImageAvailable);
  53. // Event is fired when the capture sequence is complete and a thumbnail image is available.
  54. cam.CaptureThumbnailAvailable += new EventHandler<ContentReadyEventArgs>(cam_CaptureThumbnailAvailable);
  55. //Set the VideoBrush source to the camera.
  56. viewfinderBrush.SetSource(cam);
  57. }
  58. else
  59. {
  60. // The camera is not supported on the device.
  61. this.Dispatcher.BeginInvoke(delegate()
  62. {
  63. // Write message.
  64. txtDebug.Text = "A Camera is not available on this device.";
  65. });
  66. // Disable UI.
  67. ShutterButton.IsEnabled = false;
  68. }
  69. }
  70. protected override void OnNavigatingFrom(System.Windows.Navigation.NavigatingCancelEventArgs e)
  71. {
  72. if (cam != null)
  73. {
  74. // Dispose camera to minimize power consumption and to expedite shutdown.
  75. cam.Dispose();
  76. // Release memory, ensure garbage collection.
  77. cam.Initialized -= cam_Initialized;
  78. cam.CaptureCompleted -= cam_CaptureCompleted;
  79. cam.CaptureImageAvailable -= cam_CaptureImageAvailable;
  80. cam.CaptureThumbnailAvailable -= cam_CaptureThumbnailAvailable;
  81. }
  82. }
  83. // Update the UI if initialization succeeds.
  84. void cam_Initialized(object sender, Microsoft.Devices.CameraOperationCompletedEventArgs e)
  85. {
  86. if (e.Succeeded)
  87. {
  88. this.Dispatcher.BeginInvoke(delegate()
  89. {
  90. // Write message.
  91. txtDebug.Text = "Camera initialized.";
  92. });
  93. }
  94. }
  95. // Ensure that the viewfinder is upright in LandscapeRight.
  96. protected override void OnOrientationChanged(OrientationChangedEventArgs e)
  97. {
  98. if (cam != null)
  99. {
  100. // LandscapeRight rotation when camera is on back of device.
  101. int landscapeRightRotation = 180;
  102. // Change LandscapeRight rotation for front-facing camera.
  103. if (cam.CameraType == CameraType.FrontFacing) landscapeRightRotation = -180;
  104. // Rotate video brush from camera.
  105. if (e.Orientation == PageOrientation.LandscapeRight)
  106. {
  107. // Rotate for LandscapeRight orientation.
  108. viewfinderBrush.RelativeTransform =
  109. new CompositeTransform() { CenterX = 0.5, CenterY = 0.5, Rotation = landscapeRightRotation };
  110. }
  111. else
  112. {
  113. // Rotate for standard landscape orientation.
  114. viewfinderBrush.RelativeTransform =
  115. new CompositeTransform() { CenterX = 0.5, CenterY = 0.5, Rotation = 0 };
  116. }
  117. }
  118. base.OnOrientationChanged(e);
  119. }
  120. private void ShutterButton_Click(object sender, RoutedEventArgs e)
  121. {
  122. }
  123. void cam_CaptureCompleted(object sender, CameraOperationCompletedEventArgs e)
  124. {
  125. // Increments the savedCounter variable used for generating JPEG file names.
  126. savedCounter++;
  127. }
  128. //isolated storage
  129. // Informs when full resolution picture has been taken, saves to local media library and isolated storage.
  130. void cam_CaptureImageAvailable(object sender, Microsoft.Devices.ContentReadyEventArgs e)
  131. {
  132. string fileName = savedCounter + ".jpg";
  133. try
  134. { // Write message to the UI thread.
  135. Deployment.Current.Dispatcher.BeginInvoke(delegate()
  136. {
  137. txtDebug.Text = "Captured image available, saving picture.";
  138. });
  139. // Save picture to the library camera roll.
  140. library.SavePictureToCameraRoll(fileName, e.ImageStream);
  141. // Write message to the UI thread.
  142. Deployment.Current.Dispatcher.BeginInvoke(delegate()
  143. {
  144. txtDebug.Text = "Picture has been saved to camera roll.";
  145. });
  146. // Set the position of the stream back to start
  147. e.ImageStream.Seek(0, SeekOrigin.Begin);
  148. // Save picture as JPEG to isolated storage.
  149. using (IsolatedStorageFile isStore = IsolatedStorageFile.GetUserStoreForApplication())
  150. {
  151. using (IsolatedStorageFileStream targetStream = isStore.OpenFile(fileName, FileMode.Create, FileAccess.Write))
  152. {
  153. // Initialize the buffer for 4KB disk pages.
  154. byte[] readBuffer = new byte[4096];
  155. int bytesRead = -1;
  156. // Copy the image to isolated storage.
  157. while ((bytesRead = e.ImageStream.Read(readBuffer, 0, readBuffer.Length)) > 0)
  158. {
  159. targetStream.Write(readBuffer, 0, bytesRead);
  160. }
  161. }
  162. }
  163. // Write message to the UI thread.
  164. Deployment.Current.Dispatcher.BeginInvoke(delegate()
  165. {
  166. txtDebug.Text = "Picture has been saved to isolated storage.";
  167. });
  168. }
  169. finally
  170. {
  171. // Close image stream
  172. e.ImageStream.Close();
  173. }
  174. }
  175. // Informs when thumbnail picture has been taken, saves to isolated storage
  176. // User will select this image in the pictures application to bring up the full-resolution picture.
  177. public void cam_CaptureThumbnailAvailable(object sender, ContentReadyEventArgs e)
  178. {
  179. string fileName = savedCounter + "_th.jpg";
  180. try
  181. {
  182. // Write message to UI thread.
  183. Deployment.Current.Dispatcher.BeginInvoke(delegate()
  184. {
  185. txtDebug.Text = "Captured image available, saving thumbnail.";
  186. });
  187. // Save thumbnail as JPEG to isolated storage.
  188. using (IsolatedStorageFile isStore = IsolatedStorageFile.GetUserStoreForApplication())
  189. {
  190. using (IsolatedStorageFileStream targetStream = isStore.OpenFile(fileName, FileMode.Create, FileAccess.Write))
  191. {
  192. // Initialize the buffer for 4KB disk pages.
  193. byte[] readBuffer = new byte[4096];
  194. int bytesRead = -1;
  195. // Copy the thumbnail to isolated storage.
  196. while ((bytesRead = e.ImageStream.Read(readBuffer, 0, readBuffer.Length)) > 0)
  197. {
  198. targetStream.Write(readBuffer, 0, bytesRead);
  199. }
  200. }
  201. }
  202. // Write message to UI thread.
  203. Deployment.Current.Dispatcher.BeginInvoke(delegate()
  204. {
  205. txtDebug.Text = "Thumbnail has been saved to isolated storage.";
  206. });
  207. }
  208. finally
  209. {
  210. // Close image stream
  211. e.ImageStream.Close();
  212. }
  213. }
  214. private void ApplicationBarIconButton_Click(object sender, EventArgs e)
  215. {
  216. if (cam != null)
  217. {
  218. try
  219. {
  220. // Start image capture.
  221. cam.CaptureImage();
  222. }
  223. catch (Exception ex)
  224. {
  225. this.Dispatcher.BeginInvoke(delegate()
  226. {
  227. // Cannot capture an image until the previous capture has completed.
  228. txtDebug.Text = ex.Message;
  229. });
  230. }
  231. }
  232. }
  233. Point origPoint;
  234. Rectangle rect;
  235. void draw_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
  236. {
  237. viewfinderCanvas.Children.Clear();
  238. rect = new Rectangle();
  239. origPoint = e.GetPosition(viewfinderCanvas);
  240. Canvas.SetLeft(rect, origPoint.X);
  241. Canvas.SetTop(rect, origPoint.Y);
  242. rect.Stroke = new SolidColorBrush(Colors.Black);
  243. rect.StrokeThickness = 2;
  244. viewfinderCanvas.Children.Add(rect);
  245. viewfinderCanvas.MouseMove += draw_MouseMove;
  246. viewfinderCanvas.MouseLeftButtonUp += draw_MouseLeftButtonUp;
  247. }
  248. void draw_MouseMove(object sender, MouseEventArgs e)
  249. {
  250. if (rect != null)
  251. {
  252. Point curPoint = e.GetPosition(viewfinderCanvas);
  253. if (curPoint.X > origPoint.X)
  254. {
  255. rect.Width = curPoint.X - origPoint.X;
  256. }
  257. else if (curPoint.X < origPoint.X)
  258. {
  259. Canvas.SetLeft(rect, curPoint.X);
  260. rect.Width = origPoint.X - curPoint.X;
  261. }
  262. if (curPoint.Y > origPoint.Y)
  263. {
  264. rect.Height = curPoint.Y - origPoint.Y;
  265. }
  266. else if (curPoint.Y < origPoint.Y)
  267. {
  268. Canvas.SetTop(rect, curPoint.Y);
  269. rect.Height = origPoint.Y - curPoint.Y;
  270. }
  271. }
  272. }
  273. void draw_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
  274. {
  275. if (rect != null)
  276. {
  277. viewfinderCanvas.MouseMove -= draw_MouseMove;
  278. viewfinderCanvas.MouseLeftButtonUp -= draw_MouseLeftButtonUp;
  279. rect = null;
  280. }
  281. }
  282. }
  283. }