public async static Task<WriteableBitmap> ToBitmapImageAsync(this byte[] imageBytes, Tuple<int, int> downscale) { if (imageBytes == null) return null; IRandomAccessStream image = imageBytes.AsBuffer().AsStream().AsRandomAccessStream(); if (downscale != null && (downscale.Item1 > 0 || downscale.Item2 > 0)) { image = await image.ResizeImage((uint)downscale.Item1, (uint)downscale.Item2); } using (image) { BitmapDecoder decoder = await BitmapDecoder.CreateAsync(image); image.Seek(0); WriteableBitmap bitmap = null; await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Low, () => { bitmap = new WriteableBitmap((int)decoder.PixelWidth, (int)decoder.PixelHeight); bitmap.SetSource(image); }); return bitmap; } }
public async Task<string> clipboard(DataPackageView con) { string str = string.Empty; //文本 if (con.Contains(StandardDataFormats.Text)) { str = await con.GetTextAsync(); return str; } //图片 if (con.Contains(StandardDataFormats.Bitmap)) { RandomAccessStreamReference img = await con.GetBitmapAsync(); var imgstream = await img.OpenReadAsync(); BitmapImage bitmap = new BitmapImage(); bitmap.SetSource(imgstream); WriteableBitmap src = new WriteableBitmap(bitmap.PixelWidth, bitmap.PixelHeight); src.SetSource(imgstream); BitmapDecoder decoder = await BitmapDecoder.CreateAsync(imgstream); PixelDataProvider pxprd = await decoder.GetPixelDataAsync(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, new BitmapTransform(), ExifOrientationMode.RespectExifOrientation, ColorManagementMode.DoNotColorManage); byte[] buffer = pxprd.DetachPixelData(); str = "image"; StorageFolder folder = await _folder.GetFolderAsync(str); StorageFile file = await folder.CreateFileAsync( DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + (ran.Next()%10000).ToString() + ".png", CreationCollisionOption.GenerateUniqueName); using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite)) { var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, fileStream); encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, decoder.PixelWidth, decoder.PixelHeight, decoder.DpiX, decoder.DpiY, buffer); await encoder.FlushAsync(); str = $"![这里写图片描述](image/{file.Name})\n"; } } //文件 if (con.Contains(StandardDataFormats.StorageItems)) { var filelist = await con.GetStorageItemsAsync(); StorageFile file = filelist.OfType<StorageFile>().First(); return await imgfolder(file); } return str; }
private async System.Threading.Tasks.Task <StorageFile> saveImageToFileAsync(RandomAccessStreamReference img) { var imgstream = await img.OpenReadAsync(); BitmapImage bitmap = new BitmapImage(); bitmap.SetSource(imgstream); Windows.UI.Xaml.Media.Imaging.WriteableBitmap src = new Windows.UI.Xaml.Media.Imaging.WriteableBitmap(bitmap.PixelWidth, bitmap.PixelHeight); src.SetSource(imgstream); Windows.Graphics.Imaging.BitmapDecoder decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(imgstream); Windows.Graphics.Imaging.PixelDataProvider pxprd = await decoder.GetPixelDataAsync(Windows.Graphics.Imaging.BitmapPixelFormat.Bgra8, Windows.Graphics.Imaging.BitmapAlphaMode.Straight, new Windows.Graphics.Imaging.BitmapTransform(), Windows.Graphics.Imaging.ExifOrientationMode.RespectExifOrientation, Windows.Graphics.Imaging.ColorManagementMode.DoNotColorManage); byte[] buffer = pxprd.DetachPixelData(); StorageFolder folder = ApplicationData.Current.LocalFolder; StorageFile file = await folder.CreateFileAsync(img.GetHashCode() + "clipboardSaved" + ".png", CreationCollisionOption.ReplaceExisting); using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite)) { var encoder = await Windows.Graphics.Imaging.BitmapEncoder.CreateAsync(Windows.Graphics.Imaging.BitmapEncoder.PngEncoderId, fileStream); encoder.SetPixelData(Windows.Graphics.Imaging.BitmapPixelFormat.Bgra8, Windows.Graphics.Imaging.BitmapAlphaMode.Straight, decoder.PixelWidth, decoder.PixelHeight, decoder.DpiX, decoder.DpiY, buffer); await encoder.FlushAsync(); } return(file); }
public async Task<BitmapSource> LoadImageAsync(Stream imageStream, Uri uri) { if (imageStream == null) { return null; } var stream = new InMemoryRandomAccessStream(); imageStream.CopyTo(stream.AsStreamForWrite()); stream.Seek(0); BitmapImage bitmap = new BitmapImage(); await bitmap.SetSourceAsync(stream); // convert to a writable bitmap so we can get the PixelBuffer back out later... // in case we need to edit and/or re-encode the image. WriteableBitmap bmp = new WriteableBitmap(bitmap.PixelHeight, bitmap.PixelWidth); stream.Seek(0); bmp.SetSource(stream); List<Byte> allBytes = new List<byte>(); byte[] buffer = new byte[4000]; int bytesRead = 0; while ((bytesRead = await imageStream.ReadAsync(buffer, 0, 4000)) > 0) { allBytes.AddRange(buffer.Take(bytesRead)); } DataContainerHelper.Instance.WriteableBitmapToStorageFile(bmp, uri); return bmp; }
/// <summary> /// Return WriteableBitmap object from a given path /// </summary> /// <param name="relativePath">file path</param> /// <returns>WriteableBitmap</returns> public static async Task<WriteableBitmap> LoadWriteableBitmap(string relativePath) { var storageFile = await Package.Current.InstalledLocation.GetFileAsync(relativePath.Replace('/', '\\')); var stream = await storageFile.OpenReadAsync(); var wb = new WriteableBitmap(1, 1); wb.SetSource(stream); return wb; }
public async Task<WriteableBitmap> RetrieveAndPutBitmapAsync(StorageFile file) { IRandomAccessStream contents = await file.OpenAsync(FileAccessMode.Read); WriteableBitmap bitmap = new WriteableBitmap(100, 100); bitmap.SetSource(contents); _cache.Add(new BitmapCacheItem() { StorageFile = file, Bitmap = bitmap }); Debug.WriteLine("Caching bitmap for file: " + file.Path + "::" + file.Name); return bitmap; }
private async Task LoadBitmap(IRandomAccessStream stream) { _writeableBitmap = new WriteableBitmap(1, 1); _writeableBitmap.SetSource(stream); _writeableBitmap.Invalidate(); await Dispatcher.RunAsync( Windows.UI.Core.CoreDispatcherPriority.Normal, () => ImageTarget.Source = _writeableBitmap); }
protected override async void OnNavigatedTo(NavigationEventArgs e) { try { var cameras = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture); if (cameras.Count < 1) { Error.Text = "No camera found, decoding static image"; await DecodeStaticResource(); return; } MediaCaptureInitializationSettings settings; if (cameras.Count == 1) { settings = new MediaCaptureInitializationSettings { VideoDeviceId = cameras[0].Id }; // 0 => front, 1 => back } else { settings = new MediaCaptureInitializationSettings { VideoDeviceId = cameras[1].Id }; // 0 => front, 1 => back } await _mediaCapture.InitializeAsync(settings); VideoCapture.Source = _mediaCapture; await _mediaCapture.StartPreviewAsync(); while (_result == null) { var photoStorageFile = await KnownFolders.PicturesLibrary.CreateFileAsync("scan.jpg", CreationCollisionOption.GenerateUniqueName); await _mediaCapture.CapturePhotoToStorageFileAsync(ImageEncodingProperties.CreateJpeg(), photoStorageFile); var stream = await photoStorageFile.OpenReadAsync(); // initialize with 1,1 to get the current size of the image var writeableBmp = new WriteableBitmap(1, 1); writeableBmp.SetSource(stream); // and create it again because otherwise the WB isn't fully initialized and decoding // results in a IndexOutOfRange writeableBmp = new WriteableBitmap(writeableBmp.PixelWidth, writeableBmp.PixelHeight); stream.Seek(0); writeableBmp.SetSource(stream); _result = ScanBitmap(writeableBmp); await photoStorageFile.DeleteAsync(StorageDeleteOption.PermanentDelete); } await _mediaCapture.StopPreviewAsync(); VideoCapture.Visibility = Visibility.Collapsed; CaptureImage.Visibility = Visibility.Visible; ScanResult.Text = _result.Text; } catch (Exception ex) { Error.Text = ex.Message; } }
LoadImageAsync(Windows.Storage.StorageFile file) { Windows.Storage.FileProperties.ImageProperties imgProp = await file.Properties.GetImagePropertiesAsync(); using (var imgStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read)) { var bitmap = new Windows.UI.Xaml.Media.Imaging.WriteableBitmap((int)imgProp.Width, (int)imgProp.Height); bitmap.SetSource(imgStream); return(bitmap); } }
private async Task LoadImage(StorageFile file) { ImageProperties imgProp = await file.Properties.GetImagePropertiesAsync(); using (var imgStream = await file.OpenAsync(FileAccessMode.Read)) { bitmap = new WriteableBitmap((int)imgProp.Width, (int)imgProp.Height); bitmap.SetSource(imgStream); PreviewImage.Source = bitmap; } }
private static async Task<BandIcon> LoadIcon(string uri) { var imageFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri(uri)); using (var fileStream = await imageFile.OpenAsync(FileAccessMode.Read)) { var bitmap = new WriteableBitmap(1, 1); bitmap.SetSource(fileStream); return bitmap.ToBandIcon(); } }
public static async Task<WriteableBitmap> LoadImage(StorageFile file) { ImageProperties imgProp = await file.Properties.GetImagePropertiesAsync(); using (var imgStream = await file.OpenAsync(FileAccessMode.Read)) { WriteableBitmap writeablebitmap = new WriteableBitmap((int)imgProp.Width, (int)imgProp.Height); writeablebitmap.SetSource(imgStream); return writeablebitmap; } }
async void Load(string filename) { var file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(filename); using (var stream = await file.OpenReadAsync()) { var bmp = new WriteableBitmap(width, height); bmp.SetSource(stream); internalBuffer = bmp.PixelBuffer.ToArray(); } }
protected override async void OnNavigatedTo(NavigationEventArgs e) { try { var cameras = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture); if (cameras.Count < 1) { await DecodeStaticResource(); return; } MediaCaptureInitializationSettings settings; settings = cameras.Count == 1 ? new MediaCaptureInitializationSettings { VideoDeviceId = cameras[0].Id } : new MediaCaptureInitializationSettings { VideoDeviceId = cameras[1].Id }; await _mediaCapture.InitializeAsync(settings); VideoCapture.Source = _mediaCapture; await _mediaCapture.StartPreviewAsync(); while (_result == null) { var photoStorageFile = await KnownFolders.PicturesLibrary.CreateFileAsync("scan.jpg", CreationCollisionOption.GenerateUniqueName); await _mediaCapture.CapturePhotoToStorageFileAsync(ImageEncodingProperties.CreateJpeg(), photoStorageFile); var stream = await photoStorageFile.OpenReadAsync(); // initialize with 1,1 to get the current size of the image var writeableBmp = new WriteableBitmap(1, 1); writeableBmp.SetSource(stream); // and create it again because otherwise the WB isn't fully initialized and decoding // results in a IndexOutOfRange writeableBmp = new WriteableBitmap(writeableBmp.PixelWidth, writeableBmp.PixelHeight); stream.Seek(0); writeableBmp.SetSource(stream); _result = ScanBitmap(writeableBmp); if (_result != null) { if (!_barcodeFound) { Messenger.Default.Send(new NotificationMessage(_result, "ResultFoundMsg")); _barcodeFound = true; } } await photoStorageFile.DeleteAsync(StorageDeleteOption.PermanentDelete); } await _mediaCapture.StopPreviewAsync(); } catch (Exception ex) { var s = ""; } }
private async void OnLoadImage(IRandomAccessStream imageStream) { var image = new WriteableBitmap(1, 1); image.SetSource(imageStream); ComicImage.Source = image; ComicImage.Width = 400; ComicImage.Height = 300; imageStream.Dispose(); }
public static async Task<WriteableBitmap> StorageFileToWriteableBitmap(StorageFile file) { if (file == null) return null; WriteableBitmap bmp; using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read)) { BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream); bmp = new WriteableBitmap((int)decoder.PixelWidth, (int)decoder.PixelHeight); bmp.SetSource(stream); } return bmp; }
private async Task<Mat> LoadImage(String imageUri) { StorageFile file = await Package.Current.InstalledLocation.GetFileAsync(imageUri); using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.Read)) { BitmapImage bmpImage = new BitmapImage(); bmpImage.SetSource(fileStream); WriteableBitmap bmp = new WriteableBitmap(bmpImage.PixelWidth, bmpImage.PixelHeight); bmp.SetSource(await file.OpenAsync(FileAccessMode.Read)); Mat img = new Mat(bmp); return img; } }
private async System.Threading.Tasks.Task DecodeStaticResource() { var file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(@"Assets\1.png"); var stream = await file.OpenReadAsync(); // initialize with 1,1 to get the current size of the image var writeableBmp = new WriteableBitmap(1, 1); writeableBmp.SetSource(stream); // and create it again because otherwise the WB isn't fully initialized and decoding // results in a IndexOutOfRange writeableBmp = new WriteableBitmap(writeableBmp.PixelWidth, writeableBmp.PixelHeight); stream.Seek(0); writeableBmp.SetSource(stream); var result = ScanBitmap(writeableBmp); if (result != null) { ScanResult.Text += result.Text; } return; }
async private void CameraCapture() { // Remember to set permissions in the manifest! // using Windows.Media.Capture; // using Windows.Storage; // using Windows.UI.Xaml.Media.Imaging; CameraCaptureUI cameraUI = new CameraCaptureUI(); cameraUI.PhotoSettings.AllowCropping = false; cameraUI.PhotoSettings.MaxResolution = CameraCaptureUIMaxPhotoResolution.MediumXga; Windows.Storage.StorageFile capturedMedia = await cameraUI.CaptureFileAsync(CameraCaptureUIMode.Photo); if (capturedMedia != null) { using (var streamCamera = await capturedMedia.OpenAsync(FileAccessMode.Read)) { BitmapImage bitmapCamera = new BitmapImage(); bitmapCamera.SetSource(streamCamera); // To display the image in a XAML image object, do this: // myImage.Source = bitmapCamera; // Convert the camera bitap to a WriteableBitmap object, // which is often a more useful format. int width = bitmapCamera.PixelWidth; int height = bitmapCamera.PixelHeight; WriteableBitmap wBitmap = new WriteableBitmap(width, height); using (var stream = await capturedMedia.OpenAsync(FileAccessMode.Read)) { wBitmap.SetSource(stream); } } } }
/// <summary> /// Loads image from file to bitmap and displays it in UI. /// </summary> public async Task LoadImage(StorageFile file) { ImageProperties imgProp = await file.Properties.GetImagePropertiesAsync(); bool sourceSet = false; using (var imgStream = await file.OpenAsync(FileAccessMode.Read)) { bitmap = new WriteableBitmap((int)imgProp.Width, (int)imgProp.Height); bitmap.SetSource(imgStream); if (imgProp.Width > 2600 || imgProp.Height > 2600) { double scale = 1.0; if (imgProp.Height > 2600) scale = 2600.0 / imgProp.Height; else if (imgProp.Width > 2600) scale = Math.Min(scale, 2600.0 / imgProp.Width); bitmap = bitmap.Resize((int)(imgProp.Width * scale), (int)(imgProp.Height * scale), WriteableBitmapExtensions.Interpolation.Bilinear); } } ExtractText(); }
private async void openMyCamera() { CameraCaptureUI cameraUI = new CameraCaptureUI(); cameraUI.PhotoSettings.AllowCropping = false; cameraUI.PhotoSettings.MaxResolution = CameraCaptureUIMaxPhotoResolution.MediumXga; Windows.Storage.StorageFile capturedMedia = await cameraUI.CaptureFileAsync(CameraCaptureUIMode.Photo); if (capturedMedia != null) { using (var streamCamera = await capturedMedia.OpenAsync(FileAccessMode.Read)) { bitmapCamera = new BitmapImage(); bitmapCamera.SetSource(streamCamera); //To display the image in a XAML image object, do this: imagePreivew.Source = bitmapCamera; // Convert the camera bitap to a WriteableBitmap object, // which is often a more useful format. int width = bitmapCamera.PixelWidth; int height = bitmapCamera.PixelHeight; WriteableBitmap wBitmap = new WriteableBitmap(width, height); using (var stream = await capturedMedia.OpenAsync(FileAccessMode.Read)) { wBitmap.SetSource(stream); } SaveImageAsJpeg(wBitmap); } } }
/// <summary> /// liest eine Bilddatei und gibt das ensprechande Bitmap-Objekt zurück /// </summary> /// <param name="fileName">Name der Bilddateie, welche geladen werden soll</param> /// <returns>fertig geladenes Bild</returns> public static async Task<WriteableBitmap> ReadBitmapAsync(string fileName) { var data = await ReadAllBytesAsync(fileName); var size = GetBildGröße(data); var memStream = new MemoryStream(); await memStream.WriteAsync(data, 0, data.Length); memStream.Position = 0; var result = new WriteableBitmap(size.w, size.h); result.SetSource(memStream.AsRandomAccessStream()); return result; }
async void LoadImage(string fileName,string option) { // Open the file StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx://" + fileName)); using (IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read)) { // We have to load the file in a BitmapImage first, so we can check the width and height.. BitmapImage bmp = new BitmapImage(); bmp.SetSource(fileStream); // Load the picture in a WriteableBitmap WriteableBitmap writeableBitmap = new WriteableBitmap(bmp.PixelWidth, bmp.PixelHeight); writeableBitmap.SetSource(await file.OpenAsync(Windows.Storage.FileAccessMode.Read)); // Now we have to extract the pixels from the writeablebitmap // Get all pixel colors from the buffer pixelColors = writeableBitmap.PixelBuffer.ToArray(); // passbyte = pixelColors; bytesAsInts = conversion1.GetIntArrayFromByteArray(pixelColors); // txtbox.Text += 0.5; if (option == Convert.ToString(1)) { if (check12) { resultbyte = passbyte; check12 = false; } bool check122 = false; if (resultbyte != null && check1) { bytesAsInts = conversion1.GetIntArrayFromByteArray(resultbyte); check122 = true; } else { bytesAsInts = conversion1.GetIntArrayFromByteArray(pixelColors); } resultarray = bg.Process(bytesAsInts, bmp.PixelWidth, bmp.PixelHeight); passbyte = conversion1.GetByteArrayFromIntArray(resultarray); if (check122) { check1 = true; } else { check1 = false; } check2 = true; check3 = true; check22 = true; check32 = true; check4 = true; check42 = true; // Now we have to write back our pixel colors to the writeable bitmap.. } else if (option == Convert.ToString(2)) { bool check222 = false; if (check22) { resultbyte = passbyte; check22 = false; } if (resultbyte != null && check2) { Saturation st = new Saturation(); passbyte = st.satura(resultbyte, bmp.PixelWidth, bmp.PixelHeight, sature); check222 = true; } else { Saturation st = new Saturation(); passbyte = st.satura(pixelColors, bmp.PixelWidth, bmp.PixelHeight, sature); } if (check222) { check2 = true; } else { check2 = false; } check12 = true; check32 = true; check3 = true; check1 = true; check4 = true; check42 = true; } else if (option == Convert.ToString(3)) { resultarray = Bitmap_Sharpen.sharpen(bytesAsInts, bmp.PixelWidth, bmp.PixelHeight, sharp); passbyte = conversion1.GetByteArrayFromIntArray(resultarray); resultbyte = passbyte; } else if (option == Convert.ToString(4)) { bool check333 = false; if (check32) { resultbyte = passbyte; check32 = false; } if (resultbyte != null && check3) { Gamma gam = new Gamma(); passbyte = gam.GammaChange(resultbyte, bmp.PixelWidth, bmp.PixelHeight, gamma); check333 = true; } else { check333 = false; Gamma gam = new Gamma(); passbyte = gam.GammaChange(pixelColors, bmp.PixelWidth, bmp.PixelHeight, gamma); } if (check333) { check3 = true; } else { check3 = false; } check12 = true; check22 = true; check2 = true; check1 = true; check4 = true; check42 = true; } else if (option == Convert.ToString(5)) { //hue code bool check444 = false; if (check42) { resultbyte = passbyte; check42 = false; } if (resultbyte != null && check4 == true) { writeableBitmap.PixelBuffer.AsStream().Write(passbyte, 0, passbyte.Length); writeableBitmap = ChangeHue.ChangeHue1(writeableBitmap, amount); check444 = true; } else { writeableBitmap = ChangeHue.ChangeHue1(writeableBitmap, amount); } resultbyte = writeableBitmap.PixelBuffer.ToArray(); passbyte = resultbyte; if (check444) { check4 = true; } else { check4 = false; } check12 = true; check22 = true; check2 = true; check1 = true; check3 = true; check32 = true; } writeableBitmap.PixelBuffer.AsStream().Write(passbyte, 0, passbyte.Length); // Set the source of our image to the WriteableBitmap img1.Source = writeableBitmap; //img1.Source = wb; // Tell the image it needs a redraw writeableBitmap.Invalidate(); } }
private async void DoImageProcessing() { var ps = new InMemoryRandomAccessStream(); while (processImage) { await capturePreview.Source.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), ps); await ps.FlushAsync(); ps.Seek(0); WriteableBitmap bitmap = new WriteableBitmap(424, 240); bitmap.SetSource(ps); int bitmapSize = bitmap.PixelHeight * bitmap.PixelWidth * 4; using (Stream imageStream = bitmap.PixelBuffer.AsStream()) { byte[] bitmapPixelArray = new byte[bitmapSize]; await imageStream.ReadAsync(bitmapPixelArray, 0, bitmapSize); for (int i = 0; i < bitmapSize; i += 4) { selectedPixelFunction(bitmapPixelArray, i); } imageStream.Seek(0, SeekOrigin.Begin); await imageStream.WriteAsync(bitmapPixelArray, 0, bitmapSize); } imageProcess.Source = bitmap; } selectedPixelFunction = null; }
/// <summary> /// Invoked when the user clicks on the Sample button. /// </summary> //private async void Sample_Click(object sender, RoutedEventArgs e) //{ // // Load sample "Hello World" image. // var file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync("sample\\sample.png"); // await LoadImage(file); //} /// <summary> /// Loads image from file to bitmap and displays it in UI. /// </summary> private async Task LoadImage(StorageFile file) { ImageProperties imgProp = await file.Properties.GetImagePropertiesAsync(); using (var imgStream = await file.OpenAsync(FileAccessMode.Read)) { bitmap = new WriteableBitmap((int)imgProp.Width, (int)imgProp.Height); bitmap.SetSource(imgStream); PreviewImage.Source = bitmap; } rootPage.NotifyUser( String.Format("Eklenen Görüntü Dosyası: {0} ({1}x{2}).", file.Name, imgProp.Width, imgProp.Height), NotifyType.StatusMessage); ClearResults(); }
/// <summary> /// Await loading an image from an external web site /// </summary> /// <param name="uri"></param> public async Task<WriteableBitmap> LoadImageWriteableBitmapFromWeb(Uri uri) { // From Petzold, Programming Windows, 6th edition pg. 692-3 /* This simple method will return before the file read is complete. As expected, this is a problem: RandomAccessStreamReference streamRef = RandomAccessStreamReference.CreateFromUri(uri); IRandomAccessStreamWithContentType fileStream = await streamRef.OpenReadAsync(); WriteableBitmap wb = new WriteableBitmap(1, 1); // dummy values wb.SetSource(fileStream); return wb; */ try { RandomAccessStreamReference streamRef = RandomAccessStreamReference.CreateFromUri(uri); // Create a buffer for reading the stream: Windows.Storage.Streams.Buffer buffer = null; // Read the entire file: using (IRandomAccessStreamWithContentType fileStream = await streamRef.OpenReadAsync()) { buffer = new Windows.Storage.Streams.Buffer((uint)fileStream.Size); await fileStream.ReadAsync(buffer, (uint)fileStream.Size, InputStreamOptions.None); } WriteableBitmap wb = new WriteableBitmap(1, 1); // dummy values // Create a memory stream for transferring the data using (InMemoryRandomAccessStream memoryStream = new InMemoryRandomAccessStream()) { await memoryStream.WriteAsync(buffer); memoryStream.Seek(0); // Use the memory stream as the Bitmap Source wb.SetSource(memoryStream); } return wb; } catch(Exception) { return null; // new Dec 2014. Probably bad, dangling uri. Let caller report & handle error. } }
private async Task<string> FindQRCodeAsync() { _isStreaming = true; RaisePropertyChanged(nameof(MediaCapture)); await _mediaCapture.StartPreviewAsync(); IsCameraInitialising = false; ShowCameraPreview = true; Result result = null; while (result == null && _isStreaming) { var photoStorageFile = await ApplicationData.Current.TemporaryFolder.CreateFileAsync(DateTime.UtcNow.ToString("yyyMMddHHmmssff"), CreationCollisionOption.GenerateUniqueName); await _mediaCapture.CapturePhotoToStorageFileAsync(ImageEncodingProperties.CreateJpeg(), photoStorageFile); var stream = await photoStorageFile.OpenReadAsync(); var writableBmp = new WriteableBitmap(1, 1); writableBmp.SetSource(stream); writableBmp = new WriteableBitmap(writableBmp.PixelWidth, writableBmp.PixelHeight); stream.Seek(0); writableBmp.SetSource(stream); var barcodeReader = new BarcodeReader { AutoRotate = true }; barcodeReader.Options.TryHarder = true; try { result = barcodeReader.Decode(writableBmp); } catch (IndexOutOfRangeException) { continue; } catch (UnauthorizedAccessException) { continue; } finally { await photoStorageFile.DeleteAsync(StorageDeleteOption.PermanentDelete); } } if (result != null) { return result.Text; } else { return ""; } }
/// <summary> /// 图片处理 获取中间代码区域部分 /// </summary> private async void PhotoHandle() { var focusSettings = new FocusSettings { Mode = FocusMode.Auto, AutoFocusRange = AutoFocusRange.Macro, Distance = ManualFocusDistance.Nearest }; Result _result = null; try { while (_result == null && _cancel != true) { //对焦 var autoFocusSupported = _mediaCapture.VideoDeviceController.FocusControl.SupportedFocusModes.Contains(FocusMode.Auto); if (autoFocusSupported) { _mediaCapture.VideoDeviceController.FocusControl.Configure(focusSettings); await _mediaCapture.VideoDeviceController.FocusControl.FocusAsync().AsTask(); } var photoStorageFile = await KnownFolders.PicturesLibrary.CreateFileAsync("scan.jpg", CreationCollisionOption.ReplaceExisting); await _mediaCapture.CapturePhotoToStorageFileAsync(ImageEncodingProperties.CreateJpeg(), photoStorageFile); var stream = await photoStorageFile.OpenReadAsync(); //stream.Seek(0); //await _mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreatePng(), stream); // initialize with 1,1 to get the current size of the image var writeableBmp = new WriteableBitmap(1, 1); writeableBmp.SetSource(stream); // and create it again because otherwise the WB isn't fully initialized and decoding // results in a IndexOutOfRange writeableBmp = new WriteableBitmap(writeableBmp.PixelWidth, writeableBmp.PixelHeight); stream.Seek(0); writeableBmp.SetSource(stream); _result =await ScanQRCodeAsync(writeableBmp); await photoStorageFile.DeleteAsync(StorageDeleteOption.PermanentDelete); //如果识别成功 if (null != _result) { // await new MessageDialog(res.Text).ShowAsync(); await StopPreviewAsync(); tip.Stop(); string result = _result.Text; if (IsInteger(result)) { string[] info = new string[2]; info[0] = "Barcode"; info[1] = result; SuppressNavigationTransitionInfo n = new SuppressNavigationTransitionInfo(); ((Frame)Window.Current.Content).Navigate(typeof(SearchPage_M), info, n); //获取导航然后清理上一个 var a = ((Frame)Window.Current.Content).BackStack; a.RemoveAt(a.Count - 1); } //如果为网页链接,跳转到网页中 else { ((Frame)Window.Current.Content).Navigate(typeof(WebView_M), result); //获取导航然后清理上一个 var a = ((Frame)Window.Current.Content).BackStack; a.RemoveAt(a.Count - 1); } break; } } } catch { //await new MessageDialog("相机出现问题,请退出该页面重新初始化相机").ShowAsync(); return; } //var file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(@"Assets\1.png"); //var stream = await file.OpenReadAsync(); //// initialize with 1,1 to get the current size of the image //var writeableBmp = new WriteableBitmap(1, 1); //writeableBmp.SetSource(stream); //// and create it again because otherwise the WB isn't fully initialized and decoding //// results in a IndexOutOfRange //writeableBmp = new WriteableBitmap(writeableBmp.PixelWidth, writeableBmp.PixelHeight); //stream.Seek(0); //writeableBmp.SetSource(stream); //var result = ScanQRCode(writeableBmp); //if (result != null) //{ // await new MessageDialog(result.Text).ShowAsync(); //} //return; #region MyRegion //while (true) //{ // if (_isInitialized && _isPreviewing) // { // //对焦 // var autoFocusSupported = _mediaCapture.VideoDeviceController.FocusControl.SupportedFocusModes.Contains(FocusMode.Auto); // if (autoFocusSupported) // { // var focusSettings = new FocusSettings // { // Mode = FocusMode.Auto, // AutoFocusRange = AutoFocusRange.Macro, // Distance = ManualFocusDistance.Nearest // }; // _mediaCapture.VideoDeviceController.FocusControl.Configure(focusSettings); // await _mediaCapture.VideoDeviceController.FocusControl.FocusAsync().AsTask(); // } // //拍照 // //获取照片方向 // var photoOrientation = ConvertOrientationToPhotoOrientation(GetCameraOrientation()); // //设置照片流 // var file = await KnownFolders.PicturesLibrary.CreateFileAsync("SimplePhoto.jpg", CreationCollisionOption.GenerateUniqueName); // using (var stream = new InMemoryRandomAccessStream()) // { // await _mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream); // var decoder = await BitmapDecoder.CreateAsync(stream); // using (var outputStream = await file.OpenAsync(FileAccessMode.ReadWrite)) // { // var encoder = await BitmapEncoder.CreateForTranscodingAsync(outputStream, decoder); // var properties = new BitmapPropertySet { { "System.Photo.Orientation", new BitmapTypedValue(photoOrientation, PropertyType.UInt16) } }; // await encoder.BitmapProperties.SetPropertiesAsync(properties); // await encoder.FlushAsync(); // } // } // using (var streamResult = await file.OpenAsync(FileAccessMode.Read)) // { // var writeableBmp = new WriteableBitmap(1, 1); // writeableBmp.SetSource(streamResult); // writeableBmp = new WriteableBitmap(writeableBmp.PixelWidth, writeableBmp.PixelHeight); // streamResult.Seek(0); // writeableBmp.SetSource(streamResult); // await file.DeleteAsync(StorageDeleteOption.PermanentDelete); // image.Source = writeableBmp; // } // ////截图获取图片 // var s = clipImage.TransformToVisual(root); // Point p = s.TransformPoint(new Point(0, 0)); // RectangleGeometry rect = new RectangleGeometry(); // rect.Rect = new Rect(p.X, p.Y, 300, 300); // image.Clip = rect; // await Task.Delay(TimeSpan.FromSeconds(0.1)); // RenderTargetBitmap ss = new RenderTargetBitmap(); // await ss.RenderAsync(clip); // //让显示图片区域为空 // image.Source = null; // var writeBmp = await ClipPhotoHandleAsync(ss); // // i.Source = writeBmp; // var res = ScanQRCode(writeBmp); // //如果识别成功 // if (null != res) // { // // await new MessageDialog(res.Text).ShowAsync(); // await StopPreviewAsync(); // tip.Stop(); // string result = res.Text; // if (IsInteger(result)) // { // string[] info = new string[2]; // info[0] = "Barcode"; // info[1] = result; // SuppressNavigationTransitionInfo n = new SuppressNavigationTransitionInfo(); // ((Frame)Window.Current.Content).Navigate(typeof(SearchPage_M), info, n); // //获取导航然后清理上一个 // var a = ((Frame)Window.Current.Content).BackStack; // a.RemoveAt(a.Count - 1); // } // //如果为网页链接,跳转到网页中 // else // { // ((Frame)Window.Current.Content).Navigate(typeof(WebView_M), result); // //获取导航然后清理上一个 // var a = ((Frame)Window.Current.Content).BackStack; // a.RemoveAt(a.Count - 1); // } // break; // } // } // else // { // return; // } //} #endregion }
public static async void ImagetoIsolatedStorageSaver(IRandomAccessStreamWithContentType stream, string filename) { try { //WriteableBitmap is used to save our image to our desired location, which in this case is the LocalStorage of app var image = new WriteableBitmap(50, 50); image.SetSource(stream); //Saving to roaming folder so that it can sync the profile pic to other devices var saveAsTarget = await ApplicationData.Current.RoamingFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting); //Encoding with Bitmap Encoder to jpeg format var encoder = await BitmapEncoder.CreateAsync( BitmapEncoder.JpegEncoderId, await saveAsTarget.OpenAsync(FileAccessMode.ReadWrite)); //Saving as a stream var pixelStream = image.PixelBuffer.AsStream(); var pixels = new byte[pixelStream.Length]; await pixelStream.ReadAsync(pixels, 0, pixels.Length); encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint) image.PixelWidth, (uint) image.PixelHeight, 96.0, 96.0, pixels); await encoder.FlushAsync(); await pixelStream.FlushAsync(); pixelStream.Dispose(); } catch (Exception e) { Debug.Write(e); } }
private async void SelectImageButton_Click(object sender, RoutedEventArgs e) { await _photoCaptureManager.StopPreviewAsync(); var openPicker = new Windows.Storage.Pickers.FileOpenPicker { SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary, ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail }; // Filter to include a sample subset of file types openPicker.FileTypeFilter.Clear(); foreach (string postfix in _supportedImageFilePostfixes) { openPicker.FileTypeFilter.Add(postfix); } // Open the file picker Windows.Storage.StorageFile file = await openPicker.PickSingleFileAsync(); // File is null if user cancels the file picker if (file != null) { var fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read); // Reset the streams _dataContext.ResetStreams(); var image = new BitmapImage(); image.SetSource(fileStream); int width = image.PixelWidth; int height = image.PixelHeight; var bitmap = new WriteableBitmap(width, height); _dataContext.SetFullResolution(width, height); int previewWidth = (int)FilterEffects.DataContext.DefaultPreviewResolutionWidth; int previewHeight = 0; AppUtils.CalculatePreviewResolution(width, height, ref previewWidth, ref previewHeight); _dataContext.SetPreviewResolution(previewWidth, previewHeight); bool success = false; try { // Jpeg images can be used as such. Stream stream = fileStream.AsStream(); stream.Position = 0; stream.CopyTo(_dataContext.FullResolutionStream); success = true; } catch (Exception ex) { Debug.WriteLine(DebugTag + "Cannot use stream as such (not probably jpeg): " + ex.Message); } if (!success) { // TODO: Test this part! It may not work. // // Image format is not jpeg. Can be anything, so first // load it into a bitmap image and then write as jpeg. bitmap.SetSource(fileStream); var inStream = (IRandomAccessStream)_dataContext.FullResolutionStream.AsInputStream(); BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, inStream); Stream outStream = bitmap.PixelBuffer.AsStream(); var pixels = new byte[outStream.Length]; await outStream.ReadAsync(pixels, 0, pixels.Length); encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)width, (uint)height, 96.0, 96.0, pixels); await encoder.FlushAsync(); } await AppUtils.ScaleImageStreamAsync( _dataContext.FullResolutionStream, _dataContext.FullResolution, _dataContext.PreviewResolutionStream, _dataContext.PreviewResolution); _dataContext.WasCaptured = false; Frame.Navigate(typeof(PreviewPage)); } // if (file != null) }
private async Task<WriteableBitmap> ClipPhotoHandleAsync(RenderTargetBitmap renderTargetBitmap) { IBuffer buffer = await renderTargetBitmap.GetPixelsAsync(); //创建程序文件存储 var appData = ApplicationData.Current.LocalFolder; IStorageFile saveFile = await appData.CreateFileAsync("QRCode.png", CreationCollisionOption.ReplaceExisting); //把图片存进去 using (var fileStream = await saveFile.OpenAsync(FileAccessMode.ReadWrite)) { var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, fileStream); encoder.SetPixelData( BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)renderTargetBitmap.PixelWidth, (uint)renderTargetBitmap.PixelHeight, DisplayInformation.GetForCurrentView().LogicalDpi, DisplayInformation.GetForCurrentView().LogicalDpi, buffer.ToArray()); await encoder.FlushAsync(); } var writeableBmp = new WriteableBitmap(1, 1); using (var streamResult = await saveFile.OpenAsync(FileAccessMode.Read)) { writeableBmp.SetSource(streamResult); writeableBmp = new WriteableBitmap(writeableBmp.PixelWidth, writeableBmp.PixelHeight); streamResult.Seek(0); writeableBmp.SetSource(streamResult); await saveFile.DeleteAsync(StorageDeleteOption.PermanentDelete); } return writeableBmp; }
protected async override void OnLaunched(LaunchActivatedEventArgs e) { List<MyLine> listLines = new List<MyLine>(); //int minSize = 40; //int maxSize = 2600; int wordTopRange = 25; StorageFolder folder = Windows.Storage.ApplicationData.Current.LocalFolder; StorageFile file = null; if (!string.IsNullOrEmpty(e.Arguments)) { try { OcrEngine ocrEngine = new OcrEngine(OcrLanguage.English); file = await folder.GetFileAsync(e.Arguments); ImageProperties imgProp = await file.Properties.GetImagePropertiesAsync(); //if (imgProp.Height < minSize || imgProp.Height > maxSize || imgProp.Width < minSize || imgProp.Width > maxSize) //{ // await WriteToFile(folder, file.Name + ".txt", "Image size must be > 40 and < 2600 pixel"); //} //else //{ WriteableBitmap bitmap = null; using (IRandomAccessStream imgStream = await file.OpenAsync(FileAccessMode.Read)) { bitmap = new WriteableBitmap((int)imgProp.Width, (int)imgProp.Height); bitmap.SetSource(imgStream); } // This main API call to extract text from image. OcrResult ocrResult = await ocrEngine.RecognizeAsync((uint)bitmap.PixelHeight, (uint)bitmap.PixelWidth, bitmap.PixelBuffer.ToArray()); // If there is text. if (ocrResult.Lines != null) { StringBuilder builder = new StringBuilder(); // loop over recognized text. foreach (OcrLine line in ocrResult.Lines) { // Iterate over words in line. foreach (OcrWord word in line.Words) { // sort the word line by line bool isBelongToLine = false; foreach (MyLine myLine in listLines) { // if line exist, add word to line if (Between(myLine.lineNumber, word.Top - wordTopRange, word.Top + wordTopRange, true)) { myLine.listWords.Add(word); isBelongToLine = true; break; } } // if line does not exist, create new line, add word to line if (isBelongToLine == false) { MyLine myLine = new MyLine(); myLine.lineNumber = word.Top; myLine.listWords.Add(word); listLines.Add(myLine); } // sort the word line by line } } // sort the lines base on top position listLines.Sort(); // return data line by line foreach (MyLine myLine in listLines) { builder.Append(myLine.ToString()); } await WriteToFile(folder, file.Name + ".txt", builder.ToString()); } else // if no text { await WriteToFile(folder, file.Name + ".txt", "No Text"); } //} } catch (Exception ex) { await WriteToFile(folder, file.Name + ".txt", "Exception"); } App.Current.Exit(); } }