private async void Img_Empleado_DoubleTapped(object sender, DoubleTappedRoutedEventArgs e) { var memoryStream = new MemoryStream(); var picker = new Windows.Storage.Pickers.FileOpenPicker(); picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail; picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary; picker.FileTypeFilter.Add(".jpg"); picker.FileTypeFilter.Add(".jpeg"); picker.FileTypeFilter.Add(".png"); Windows.Storage.StorageFile file = await picker.PickSingleFileAsync(); if (file != null) { var bitmap = new BitmapImage(); using (var stream = await file.OpenReadAsync()) { await bitmap.SetSourceAsync(stream); Stream stream2 = await file.OpenStreamForReadAsync(); stream2.CopyTo(memoryStream); Empleado_Actual.Photo = memoryStream.ToArray(); } Img_Empleado.Source = bitmap; // Empleado_Actual.Photo = await ImageToBytes (bitmap); } }
private async void button1_Click(object sender, RoutedEventArgs e) { var openFile = new Windows.Storage.Pickers.FileOpenPicker(); openFile.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail; openFile.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary; openFile.FileTypeFilter.Add(".ods"); Windows.Storage.StorageFile file = await openFile.PickSingleFileAsync(); if (file != null) { // Application now has read/write access to the picked file var fileStream = file.OpenStreamForReadAsync(); var TheDictionary = (VocabularyDictionary.MasterDictionary)App.Current.Resources["TheDictionary"]; var t = System.Threading.Tasks.Task.Run(() => TheDictionary.LoadODS(fileStream.Result)); t.Wait(); VocabularyDictionary.DataManagement.Save("DataFile", TheDictionary); App.Current.Resources["TheDictionary"] = TheDictionary; } else { //this.textBlock.Text = "Operation cancelled."; } }
private async void GetFile(Context cxt, Mutex m) { try { String file = Prefix + cxt.PathArgs[1].Replace("/", "\\"); String type = file.LastIndexOf('.') > 0 ? file.Substring(file.LastIndexOf('.') + 1) : "*"; Debug.WriteLine("file: " + file); Windows.Storage.StorageFile sf = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(file); Stream st = await sf.OpenStreamForReadAsync(); MemoryStream ms = new MemoryStream(); st.CopyTo(ms); st.Close(); byte[] dt = new byte[ms.Length]; System.Array.Copy(ms.GetBuffer(), dt, dt.Length); ms.Close(); if (MIMEs.ContainsKey(type)) { cxt.Response.Header["Content-Type"] = MIMEs[type]; } else { cxt.Response.Header["Content-Type"] = MIMEs["*"]; } cxt.Response.Body = dt; } catch (Exception e) { Debug.WriteLine(e); cxt.Response.ResponseError(404, "Not Found"); } }
async Task <bool> UploadDB() { try { ServiceReference1.IService1 s = new ServiceReference1.Service1Client(); Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder; Windows.Storage.StorageFile sampleFile = await storageFolder.GetFileAsync("SQLITEV2.sqlite"); byte[] result; using (Stream stream = await sampleFile.OpenStreamForReadAsync()) { using (var memoryStream = new MemoryStream()) { stream.CopyTo(memoryStream); result = memoryStream.ToArray(); } } await s.UploadFileAsync(result); return(true); } catch (Exception) { return(false); throw; } }
private async Task <List <ST_CSV_ROW> > GetCsvData(Windows.Storage.StorageFile file) { // csvファイルを開く List <ST_CSV_ROW> tempcsvFile = new List <ST_CSV_ROW>(); using (StreamReader sr = new System.IO.StreamReader(await file.OpenStreamForReadAsync())) { // ストリームの末尾まで繰り返す while (!sr.EndOfStream) { // ファイルから一行読み込む var line = sr.ReadLine(); // 読み込んだ一行をカンマ毎に分けて配列に格納する var values = line.Split(','); if (values.Length >= 3) { try { ST_CSV_ROW csvRow; csvRow.time = double.Parse(values[0].ToString()) * 100;/*msで格納*/ csvRow.direction = byte.Parse(values[1].ToString()); csvRow.speed = byte.Parse(values[2].ToString()); // 出力する tempcsvFile.Add(csvRow); } catch { /*変換できない文字などがあればスキップ*/ } } } } return(tempcsvFile); }
private async void LoadBoundingBoxesButton_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e) { Windows.Storage.Pickers.FileOpenPicker picker = new Windows.Storage.Pickers.FileOpenPicker(); picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.List; picker.FileTypeFilter.Add(".txt"); Windows.Storage.StorageFile storageFile = await picker.PickSingleFileAsync(); System.IO.Stream stream = await storageFile.OpenStreamForReadAsync(); using (System.IO.StreamReader streamReader = new System.IO.StreamReader(stream)) { while (!streamReader.EndOfStream) { string line = streamReader.ReadLine(); string[] values = line.Split(' '); Windows.UI.Xaml.Shapes.Rectangle rectangle = new Windows.UI.Xaml.Shapes.Rectangle(); rectangle.Fill = this.GetColor(values[0]); rectangle.Opacity = 0.1; rectangle.Width = System.Convert.ToDouble(values[3]) * this.ImageToAnalyze.Width; rectangle.Height = System.Convert.ToDouble(values[4]) * this.ImageToAnalyze.Height; Windows.UI.Xaml.Controls.Canvas.SetLeft(rectangle, this.PositionOfLeftEdgeOfImageRelativeToLeftEdgeOfImageCanvas + (System.Convert.ToDouble(values[1]) * this.ImageToAnalyze.Width) - (rectangle.Width / 2)); Windows.UI.Xaml.Controls.Canvas.SetTop(rectangle, this.PositionOfTopEdgeOfImageRelativeToTopEdgeOfImageCanvas + (System.Convert.ToDouble(values[2]) * this.ImageToAnalyze.Height) - (rectangle.Height / 2)); this.ImageCanvas.Children.Add(rectangle); } } }
private async void Button_Click(object sender, RoutedEventArgs e) { var picker = new Windows.Storage.Pickers.FileOpenPicker(); picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail; picker.FileTypeFilter.Add(".jpg"); picker.FileTypeFilter.Add(".jpeg"); picker.FileTypeFilter.Add(".png"); picker.FileTypeFilter.Add(".gif"); picker.FileTypeFilter.Add(".bmp"); Windows.Storage.StorageFile file = await picker.PickSingleFileAsync(); if (file == null) { return; } ClearResult(); // 選択された画像ファイルを読み込んでバイト配列に変換する byte[] data; using (var stream = await file.OpenStreamForReadAsync()) { data = new byte[(int)stream.Length]; stream.Read(data, 0, (int)stream.Length); } // バイト配列からSoftwareBitmapを作る // https://docs.microsoft.com/ja-jp/windows/uwp/audio-video-camera/imaging SoftwareBitmap softwareBitmap; using (IRandomAccessStream stream = new MemoryStream(data).AsRandomAccessStream()) { BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream); softwareBitmap = await decoder.GetSoftwareBitmapAsync(); } // Image コントロールは、BGRA8 エンコードを使用し、プリマルチプライ処理済みまたはアルファ チャネルなしの画像しか受け取れない // 異なるフォーマットの場合は変換する☟ if (softwareBitmap.BitmapPixelFormat != BitmapPixelFormat.Bgra8 || softwareBitmap.BitmapAlphaMode == BitmapAlphaMode.Straight) { softwareBitmap = SoftwareBitmap.Convert(softwareBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied); } // ImageコントロールにはSoftwareBitmapSourceを渡す var source = new SoftwareBitmapSource(); await source.SetBitmapAsync(softwareBitmap); this.Image1.Source = source; // バーコード読み取り var result = await StdLib.ZXingBarcodeReader.DecodeAsync(data); if (result != null) { ShowResult(result); } }
private async Task <NetworkStatus> VerifyFile() { Status = NetworkStatus.Networking; OnProgressChanged(0, 1); if (cloudFile.Name != windowsFile.Name) { OnMessageAppended($"Name not consistent, Cloud: {cloudFile.Name}, Local: {windowsFile.Name}"); return(NetworkStatus.ErrorNeedRestart); } var stream = await windowsFile.OpenStreamForReadAsync(); OnMessageAppended("Getting local MD5 checksum..."); var localCheckSum = await Libraries.GetSha256ForWindowsStorageFile(stream); OnMessageAppended("Getting cloud MD5 checksum..."); var cloudCheckSum = await Libraries.GetSha256ForCloudFileById(cloudFile.Id); if (localCheckSum != cloudCheckSum) { OnMessageAppended($"Content not consistent, Cloud: {cloudCheckSum}, Local: {localCheckSum}"); return(NetworkStatus.ErrorNeedRestart); } else { OnMessageAppended($"Verification succeeded, Name: {cloudFile.Name}, Local: {cloudCheckSum}"); OnProgressChanged(1, 1); return(NetworkStatus.Completed); } }
private async void Init() { //this.button.Content = "adsdas"; Windows.Storage.StorageFolder storageFolder = Windows.ApplicationModel.Package.Current.InstalledLocation; //b1.Content = storageFolder.Path; string Filename = @"Assets\" + "dengue_data.csv"; Windows.Storage.StorageFile file = await storageFolder.GetFileAsync(Filename); Stream Countries = await file.OpenStreamForReadAsync(); //this.button.Content = "adsdas"; using (var streamReader = new StreamReader(Countries)) { //this.button.Content = "adsdas"; p_num = int.Parse(streamReader.ReadLine()); i1 = 0; while (streamReader.Peek() >= 0) { cx[i1] = double.Parse(streamReader.ReadLine()); cy[i1] = double.Parse(streamReader.ReadLine()); clusno[i1] = new int(); i1++; } //streamReader.Dispose(); //this.button.Content = "adsdas" + i1.ToString() + " " + p_num.ToString(); } }
public async Task <bool> SendEscalationEmail() { bool result = false; SmtpClient client = new SmtpClient("smtp-mail.outlook.com", 587, false, "*****@*****.**", "Password01!"); try { EmailMessage emailMessage = new EmailMessage(); //emailMessage.To.Add(new EmailRecipient("*****@*****.**")); //emailMessage.CC.Add(new EmailRecipient("*****@*****.**")); emailMessage.To.Add(new EmailRecipient("*****@*****.**")); emailMessage.CC.Add(new EmailRecipient("*****@*****.**")); emailMessage.Subject = "[Thread Escalation][Barry Wang]Can not connect ot the BLE device after creators update in UWP"; emailMessage.Body = "Please check the attachment for more detailed information about this Escalation Thread."; Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder; Windows.Storage.StorageFile sampleFile = await storageFolder.CreateFileAsync("EscalationDetails.txt", Windows.Storage.CreationCollisionOption.ReplaceExisting); //Windows.Storage.StorageFile sampleFile =await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///test.txt")); List <string> lines = new List <string>(); lines.Add("Thread Title:"); lines.Add("[RS2:1703]Can not connect ot the BLE device after creators update"); lines.Add("----------------------------------------------------------------------------------------------------------------------"); lines.Add("Thread URL:"); lines.Add("https://social.msdn.microsoft.com/Forums/en-US/winforms/thread/fda7e9db-d2e0-411c-8f4f-75efa7f0af53/"); lines.Add("----------------------------------------------------------------------------------------------------------------------"); lines.Add("Issue Description:"); lines.Add("eeeeeeeeeeeeeeeeeee"); lines.Add("----------------------------------------------------------------------------------------------------------------------"); lines.Add("Escalation Reason:"); lines.Add("dffffffffff"); await Windows.Storage.FileIO.WriteLinesAsync(sampleFile, lines); var stream = await sampleFile.OpenStreamForReadAsync(); IRandomAccessStream randomAccessStream = stream.AsRandomAccessStream(); var streamReference = Windows.Storage.Streams.RandomAccessStreamReference.CreateFromStream(randomAccessStream); emailMessage.Attachments.Add(new EmailAttachment(sampleFile.Name, streamReference)); await client.SendMailAsync(emailMessage); MessageDialog dialog = new MessageDialog("Send the Escalation Email Successuflly!"); await dialog.ShowAsync(); //Task<bool> tk = AddEscalationAndStatusThread(); //bool a = await tk; // new MessageDialog(a.ToString()).ShowAsync(); result = true; } catch (Exception ex) { result = false; } return(await Task.FromResult(result)); }
public static async System.Threading.Tasks.Task <string> Read_Data_To_String() { string text = ""; Windows.Storage.StorageFile file = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(new Uri(@"ms-appx:///Files/data.txt")); using (StreamReader sRead = new StreamReader(await file.OpenStreamForReadAsync())) text = await sRead.ReadToEndAsync(); return(text); }
/// <summary> /// Get Byte From Pixel /// </summary> /// <param name="fileNameOfImage"></param> /// <returns></returns> public static async Task <byte[]> GetByteFromPixel(string fileNameOfImage) { Windows.Storage.StorageFile imageFile = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(fileNameOfImage); // Bild laden Stream imagestream = await imageFile.OpenStreamForReadAsync(); // Bild in Stream umwandeln BitmapDecoder imageDecoder = await BitmapDecoder.CreateAsync(imagestream.AsRandomAccessStream()); // Stream dekodieren PixelDataProvider imagePixelData = await imageDecoder.GetPixelDataAsync(); // Informationen über Pixel erhalten return(imagePixelData.DetachPixelData()); // Pixel Daten bekommen }
/// <summary> /// Reads a StorageFile into a Byte array. /// </summary> /// <param name="storageFile">StorageFile to read.</param> /// <returns></returns> public static async Task <byte[]> ReadStorageFileIntoBuffer(Windows.Storage.StorageFile storageFile) { byte[] result; using (var stream = await storageFile.OpenStreamForReadAsync()) { using (var memoryStream = new MemoryStream()) { stream.CopyTo(memoryStream); result = memoryStream.ToArray(); } } return(result); }
public override async Task ResetAsync() { try { Status = NetworkStatus.NotStarted; if (fileStream != null) { fileStream.Dispose(); fileStream = null; } fileStream = await windowsFile.OpenStreamForReadAsync(); uploader = new RestRequests.Uploader(new List <string> { CloudFolder.Id }, fileStream, fileName); } catch (Exception error) { OnMessageAppended($"Unexpected: {error}"); Status = NetworkStatus.ErrorNeedRestart; } }
public static async System.Threading.Tasks.Task <string> Read_Data_To_String(string uri) { try { Windows.Storage.StorageFile file = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(new Uri(uri)); using (StreamReader sRead = new StreamReader(await file.OpenStreamForReadAsync())) { return(await sRead.ReadToEndAsync()); } } catch (Exception ex) { return(ex.Message); } }
private async void OpenButton_Click(object sender, RoutedEventArgs e) { var picker = new FileOpenPicker(); picker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary; picker.FileTypeFilter.Add(".xml"); picker.FileTypeFilter.Add(".zip"); Windows.Storage.StorageFile file = await picker.PickSingleFileAsync(); if (file == null) { return; } var mru = Windows.Storage.AccessCache.StorageApplicationPermissions.MostRecentlyUsedList; _ = mru.Add(file, file.Name); var stream = await file.OpenStreamForReadAsync(); switch (Path.GetExtension(file.Name)) { case ".xml": // Read the file var docXml = CopticInterpreter.ReadDocXml(stream); Docs.Add(docXml); MainTabControl.SelectedIndex = Docs.Count - 1; return; case ".zip": // Read the set var set = CopticInterpreter.ReadSet(stream, file.Name, Windows.Storage.ApplicationData.Current.TemporaryFolder.Path); Docs.Clear(); set.IncludedDocs.ForEach(d => Docs.Add(d)); MainTabControl.SelectedIndex = 0; CurrentStanza = (set.IncludedDocs[0].Translations[0].Content[0] as Stanza)?.Text; return; } }
private async void LoadLyricButtonClick(object sender, RoutedEventArgs e) { var picker = new Windows.Storage.Pickers.FileOpenPicker(); picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.MusicLibrary; picker.FileTypeFilter.Add(".lrc"); Windows.Storage.StorageFile file = await picker.PickSingleFileAsync(); if (file != null) { LogPrint($"Load lyric {file.Path}"); LogPrint($"Lyric will load."); var stream = await file.OpenStreamForReadAsync(); byte[] ret = new byte[stream.Length]; int over = 0; while (over != ret.Length) { int r = await stream.ReadAsync(ret, over, ret.Length - over); if (r >= 0) { over += r; } else { LogPrint("Read file REACH TO END"); byte[] narr = new byte[over]; Array.Copy(ret, narr, over); ret = narr; break; } } LogPrint($"Lyric file read over.len = {ret.Length}"); LoadLyric(ret); } }
private async Task <ObservableCollection <T> > ReadWebInfo <T>() where T : class, new() { ObservableCollection <T> list = null; Windows.Storage.StorageFile file = null; try { file = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync("webinfo"); if (file != null) { using (Stream stream = await file.OpenStreamForReadAsync()) { DataContractSerializer ser = new DataContractSerializer(typeof(ObservableCollection <T>)); list = ser.ReadObject(stream) as ObservableCollection <T>; } } } catch { } return(list); }
private async void Init() { Windows.Storage.StorageFolder storageFolder = Windows.ApplicationModel.Package.Current.InstalledLocation; //b1.Content = storageFolder.Path; string Filename = @"Assets\" + "cholera_data.csv"; Windows.Storage.StorageFile file = await storageFolder.GetFileAsync(Filename); Stream Countries = await file.OpenStreamForReadAsync(); using (var streamReader = new StreamReader(Countries)) { p_num = int.Parse(streamReader.ReadLine()); int i = 0; while (streamReader.Peek() >= 0) { cx[i] = double.Parse(streamReader.ReadLine()); cy[i] = double.Parse(streamReader.ReadLine()); clusno[i] = new int(); i++; } } }
public async static Task<DecryptionResult> DecryptFile(Windows.Storage.StorageFile inputFile, string password) { DecryptionResult decryptionResult = null; try { byte[] FileContentBytes = null; using (Stream stream = await inputFile.OpenStreamForReadAsync()) { using (var memoryStream = new MemoryStream()) { stream.CopyTo(memoryStream); FileContentBytes = memoryStream.ToArray(); } } int ctr = 0; for (int i = 999; i >= 0; i--) { if (FileContentBytes[i] != 0) { ctr = i; break; } } int ctr2 = 1000; for (int i = 1999; i >= 1000; i--) { if (FileContentBytes[i] != 0) { ctr2 = i; break; } } int FileNameBytesLength = ctr + 1; int ExtensionBytesLength = ctr2 + 1 - 1000; byte[] passwordBytes = SHA256.Create().ComputeHash(System.Text.Encoding.ASCII.GetBytes(password)); byte[] SaltedHashedPassword = SHA256.Create().ComputeHash(System.Text.Encoding.ASCII.GetBytes(password + "CryptoApp")); byte[] FileNameBytes = new byte[FileNameBytesLength]; byte[] ExtensionBytes = new byte[ExtensionBytesLength]; byte[] StoredHashedPassword = new byte[32]; byte[] EncryptedBytes = new byte[FileContentBytes.Length - 2032]; System.Buffer.BlockCopy(FileContentBytes, 2000, StoredHashedPassword, 0, 32); bool ArePasswordsSame = true; for (int i = 0; i < 32; i++) { if (SaltedHashedPassword[i] != StoredHashedPassword[i]) { ArePasswordsSame = false; break; } } if (ArePasswordsSame == false) { decryptionResult = new DecryptionResult() { Result = false, Error = "Password", DecryptedString = null }; return decryptionResult; } System.Buffer.BlockCopy(FileContentBytes, 0, FileNameBytes, 0, FileNameBytesLength); System.Buffer.BlockCopy(FileContentBytes, 1000, ExtensionBytes, 0, ExtensionBytesLength); System.Buffer.BlockCopy(FileContentBytes, 2032, EncryptedBytes, 0, EncryptedBytes.Length); int Blocks128000Size = EncryptedBytes.Length / 128000; int LastBlockSize = EncryptedBytes.Length % 128000; ctr = 0; byte[] DecryptedBytes = new byte[EncryptedBytes.Length]; for (long i = 0; i < Blocks128000Size; i++) { byte[] input = new byte[128000]; System.Buffer.BlockCopy(EncryptedBytes, ctr, input, 0, 128000); byte[] result = DecryptionService.GetDecryptedByteArray(input, passwordBytes); System.Buffer.BlockCopy(result, 0, DecryptedBytes, ctr, 128000); ctr = ctr + 128000; } if (LastBlockSize > 0) { byte[] input = new byte[LastBlockSize]; System.Buffer.BlockCopy(EncryptedBytes, ctr, input, 0, LastBlockSize); byte[] result = DecryptionService.GetDecryptedByteArray(input, passwordBytes); System.Buffer.BlockCopy(result, 0, DecryptedBytes, ctr, LastBlockSize); } string CurrentDirectoryPath = System.IO.Path.GetDirectoryName(inputFile.Path); string CurrentFileName = System.Text.Encoding.ASCII.GetString(FileNameBytes) + "_1"; string CurrentFileExtension = System.Text.Encoding.ASCII.GetString(ExtensionBytes); string WritePath = System.IO.Path.Combine(CurrentDirectoryPath, CurrentFileName + CurrentFileExtension); decryptionResult = new DecryptionResult() { Result = true, Error = null, DecryptedString = null, DecryptedContents = DecryptedBytes, WritePath = WritePath }; } catch (Exception ex) { decryptionResult = new DecryptionResult() { Result = false, Error = ex.Message, DecryptedString = null }; } return decryptionResult; }
private async void loadButton_Click(object sender, RoutedEventArgs e) { var openPicker = new Windows.Storage.Pickers.FileOpenPicker(); openPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary; openPicker.FileTypeFilter.Add(".eqn"); openPicker.FileTypeFilter.Add(".txt"); Windows.Storage.StorageFile file = await openPicker.PickSingleFileAsync(); if (file != null) { Stream stream = await file.OpenStreamForReadAsync(); StreamReader streamreader = new StreamReader(stream); textBox.Text = streamreader.ReadToEnd(); if (showNotifications) { var toastContent = new ToastContent() { Visual = new ToastVisual() { BindingGeneric = new ToastBindingGeneric() { Children = { new AdaptiveText() { Text = "Easy Quick Note" }, new AdaptiveText() { Text = "Opened note." }, new AdaptiveGroup() { Children = { new AdaptiveSubgroup() { Children = { new AdaptiveText() { Text = "Note name: " + file.Name }, new AdaptiveText() { Text = "Note file path: " + file.Path } } } } } } } } }; // Create the toast notification var toastNotif = new ToastNotification(toastContent.GetXml()); // And send the notification ToastNotificationManager.CreateToastNotifier().Show(toastNotif); } } }
///// <summary> ///// ///// </summary> ///// <param name="assetUri"></param> ///// <param name="backgroundImageFormatConverter"></param> ///// <param name="backgroundImageSize"></param> //public void LoadAsset( // SharpDX.WIC.ImagingFactory2 wicFactory, // string assetUri, // out SharpDX.WIC.FormatConverter backgroundImageFormatConverter, // out DrawingSize backgroundImageSize) //{ // //var path = Windows.ApplicationModel.Package.Current.InstalledLocation.Path; // SharpDX.WIC.BitmapDecoder bitmapDecoder = new SharpDX.WIC.BitmapDecoder( // wicFactory, // assetUri, // SharpDX.IO.NativeFileAccess.Read, // SharpDX.WIC.DecodeOptions.CacheOnDemand // ); // SharpDX.WIC.BitmapFrameDecode bitmapFrameDecode = bitmapDecoder.GetFrame(0); // SharpDX.WIC.BitmapSource bitmapSource = new SharpDX.WIC.BitmapSource(bitmapFrameDecode.NativePointer); // SharpDX.WIC.FormatConverter formatConverter = new SharpDX.WIC.FormatConverter(wicFactory); // //formatConverter.Initialize( bitmapSource, SharpDX.WIC.PixelFormat.Format32bppBGRA); // formatConverter.Initialize( // bitmapSource, // SharpDX.WIC.PixelFormat.Format32bppBGRA, // SharpDX.WIC.BitmapDitherType.None, // null, // 0.0f, // SharpDX.WIC.BitmapPaletteType.Custom // ); // backgroundImageSize = formatConverter.Size; // backgroundImageFormatConverter = formatConverter; //} /// <summary> /// Loads bitmap asynchronously and injects into global variables. I need to work out how to NOT make them global /// </summary> /// <param name="assetNativeUri"></param> /// <returns></returns> public async Task <Tuple <SharpDX.WIC.FormatConverter, Size2, Stream> > LoadAssetAsync( SharpDX.WIC.ImagingFactory2 wicFactory, string assetNativeUri, string cacheId, string path = "" ) { if (_listOfAssets.ContainsKey(cacheId)) { return(_listOfAssets[cacheId]); } SharpDX.WIC.FormatConverter _backgroundImageFormatConverter = null; Size2 _backgroundImageSize = new Size2(0, 0); Windows.Storage.StorageFile storageFile = null; if (path == string.Empty) { path = Windows.ApplicationModel.Package.Current.InstalledLocation.Path; storageFile = await Windows.Storage.StorageFile.GetFileFromPathAsync(path + assetNativeUri); } else if (path == "PicturesLibrary") { var assetNativeUriParts = assetNativeUri.Split("\\".ToCharArray()); var foundFolder = await Windows.Storage.KnownFolders.PicturesLibrary.GetFolderAsync(assetNativeUriParts[0]); storageFile = await foundFolder.GetFileAsync(assetNativeUriParts[1]); } else if (path == "PublicPicturesLibrary") { var assetNativeUriParts = assetNativeUri.Split("\\".ToCharArray()); var foundFolder = await Windows.Storage.KnownFolders.PicturesLibrary.GetFolderAsync(assetNativeUriParts[0]); storageFile = await foundFolder.GetFileAsync(assetNativeUriParts[1]); } if (storageFile == null) { return(null); } Stream ms = await storageFile.OpenStreamForReadAsync(); //ras.GetResults().AsStreamForRead()) //var data = SharpDX.IO.NativeFile.ReadAllBytes(assetNativeUri); //using (System.IO.MemoryStream ms = new System.IO.MemoryStream(data)) { if (ms != null) { SharpDX.WIC.BitmapDecoder bitmapDecoder = new SharpDX.WIC.BitmapDecoder( wicFactory, ms, SharpDX.WIC.DecodeOptions.CacheOnDemand ); { using (SharpDX.WIC.BitmapFrameDecode bitmapFrameDecode = bitmapDecoder.GetFrame(0)) { using (SharpDX.WIC.BitmapSource bitmapSource = new SharpDX.WIC.BitmapSource(bitmapFrameDecode.NativePointer)) { SharpDX.WIC.FormatConverter formatConverter = new SharpDX.WIC.FormatConverter(wicFactory); //formatConverter.Initialize( bitmapSource, SharpDX.WIC.PixelFormat.Format32bppBGRA); formatConverter.Initialize( bitmapSource, SharpDX.WIC.PixelFormat.Format32bppBGRA, SharpDX.WIC.BitmapDitherType.None, null, 0.0f, SharpDX.WIC.BitmapPaletteType.Custom ); _backgroundImageSize = formatConverter.Size; _backgroundImageFormatConverter = formatConverter; //return Tuple.Create<SharpDX.WIC.FormatConverter, Size2>(_backgroundImageFormatConverter, _backgroundImageSize); } } } } } //ras.Close(); var ret = Tuple.Create <SharpDX.WIC.FormatConverter, Size2, Stream>(_backgroundImageFormatConverter, _backgroundImageSize, ms); _listOfAssets.Add(cacheId, ret); return(ret); }