using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.Media.Capture;
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.UI.Xaml.Media.Imaging;
using Windows.Storage.Streams;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
/*
*
* 作者:李天鹏
* 功能:调用PC上自带的camera实现拍照的功能,并保存在相应的文件夹下
* */
namespace Camera
{
///
/// An empty page that can be used on its own or navigated to within a Frame.
///
public sealed partial class MainPage : Page
{
private StorageFile file = null;
public MainPage()
{
this.InitializeComponent();
}
private async void btnCamera_Click(object sender, RoutedEventArgs e)
{
CameraCaptureUI dialog = new CameraCaptureUI();
dialog.PhotoSettings.CroppedAspectRatio = new Size(16, 9);
file = await dialog.CaptureFileAsync(CameraCaptureUIMode.Photo);
if (file != null)
{
BitmapImage bitmapImage = new BitmapImage();
using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.Read))
{
bitmapImage.SetSource(fileStream);
}
img1.Source = bitmapImage;
}
}
private async void btnSave_Click(object sender, RoutedEventArgs e)
{
if (img1.Source == null)
return;
else
{
FileSavePicker picker = new FileSavePicker();
picker.CommitButtonText = "保存";
picker.SuggestedFileName = "hello";
picker.FileTypeChoices.Add("图片",new string[]{".jpg",".jpeg",".bmp",".png"});
picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
StorageFile filePath = await picker.PickSaveFileAsync();
if (filePath != null)
{
//打开通过摄像头拍摄的照片,并返回流,以流的形式读取文件
var streamRandom = await file.OpenAsync(FileAccessMode.Read);
//将拍摄的照片以流的形式读取到缓冲区
IBuffer buffer = RandomAccessStreamToBuffer(streamRandom);
//将缓冲区内容写入相应的文件夹中
await FileIO.WriteBufferAsync(filePath, buffer);
}
}
}
//将图片写入到缓冲区
private IBuffer RandomAccessStreamToBuffer(IRandomAccessStream randomstream)
{
Stream stream = WindowsRuntimeStreamExtensions.AsStreamForRead(randomstream.GetInputStreamAt(0));
MemoryStream memoryStream = new MemoryStream();
if (stream != null)
{
byte[] bytes = ConvertStreamTobyte(stream); //将流转化为字节型数组
if (bytes != null)
{
var binaryWriter = new BinaryWriter(memoryStream);
binaryWriter.Write(bytes);
}
}
IBuffer buffer = WindowsRuntimeBufferExtensions.GetWindowsRuntimeBuffer(memoryStream, 0, (int)memoryStream.Length);
return buffer;
}
//将流转换成二进制
public static byte[] ConvertStreamTobyte(Stream input)
{
byte[] buffer = new byte[16 * 1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
}
}