/// <summary> /// Decrypts the specified input stream. /// </summary> /// <param name="input">The input stream.</param> /// <param name="masterKey">The master key.</param> /// <param name="masterSeed">The master seed.</param> /// <param name="encryptionIV">The encryption initialization vector.</param> /// <returns>The decrypted buffer.</returns> /// <exception cref="ArgumentNullException"> /// The <paramref name="input"/>, <paramref name="masterSeed"/>, <paramref name="masterKey"/> /// and <paramref name="encryptionIV"/> cannot be <c>null</c>. /// </exception> public static async Task<IInputStream> Decrypt(IRandomAccessStream input, IBuffer masterKey, IBuffer masterSeed, IBuffer encryptionIV) { if (input == null) throw new ArgumentNullException("input"); if (masterSeed == null) throw new ArgumentNullException("masterSeed"); if (masterKey == null) throw new ArgumentNullException("masterKey"); if (encryptionIV == null) throw new ArgumentNullException("encryptionIV"); var sha = HashAlgorithmProvider .OpenAlgorithm(HashAlgorithmNames.Sha256) .CreateHash(); sha.Append(masterSeed); sha.Append(masterKey); var seed = sha.GetValueAndReset(); var aes = SymmetricKeyAlgorithmProvider .OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7) .CreateSymmetricKey(seed); var buffer = WindowsRuntimeBuffer.Create( (int)(input.Size - input.Position)); buffer = await input.ReadAsync(buffer, buffer.Capacity); buffer = CryptographicEngine.Decrypt(aes, buffer, encryptionIV); var stream = new InMemoryRandomAccessStream(); await stream.WriteAsync(buffer); stream.Seek(0); return stream; }
public async Task <ImagePackage> InitializeAsync(CoreDispatcher dispatcher, Image image, Uri uriSource, IRandomAccessStream streamSource, CancellationTokenSource cancellationTokenSource) { byte[] bytes = new byte[streamSource.Size]; await streamSource.ReadAsync(bytes.AsBuffer(), (uint)streamSource.Size, InputStreamOptions.None).AsTask(cancellationTokenSource.Token); int width, height; WriteableBitmap writeableBitmap = null; if (WebpCodec.GetInfo(bytes, out width, out height)) { writeableBitmap = new WriteableBitmap(width, height); await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { var uri = image.Tag as Uri; if (uri == uriSource) { image.Source = writeableBitmap; } }); WebpCodec.Decode(writeableBitmap, bytes); } return(new ImagePackage(this, writeableBitmap, writeableBitmap.PixelWidth, writeableBitmap.PixelHeight)); }
public async Task<ImageSource> InitializeAsync(CoreDispatcher dispatcher, IRandomAccessStream streamSource, CancellationTokenSource cancellationTokenSource) { byte[] bytes = new byte[streamSource.Size]; await streamSource.ReadAsync(bytes.AsBuffer(), (uint)streamSource.Size, InputStreamOptions.None).AsTask(cancellationTokenSource.Token); var imageSource = WebpCodec.Decode(bytes); return imageSource; }
private async void AppBar_LoadDefault_Button_Click(object sender, RoutedEventArgs e) { string currentDirectory = Directory.GetCurrentDirectory(); //$"C:\\Users\\steve\\Documents"; // // Load the XML file from our project directory containing the purchase orders string potentialdata_filename = "SeawaterPotentialData.xml"; string galvPotentialFilepath = Path.Combine(currentDirectory, potentialdata_filename); StorageFile temp_file = await StorageFile.GetFileFromPathAsync(galvPotentialFilepath); string alloytreatment_filename = "AlloyTreatmentRecommendations.xml"; string treatmentFilepath = Path.Combine(currentDirectory, alloytreatment_filename); StorageFile temp_file_2 = await StorageFile.GetFileFromPathAsync(treatmentFilepath); if (temp_file != null) { sampleFile = temp_file; } if (sampleFile != null) { try { using (IRandomAccessStream readstream = await sampleFile.OpenAsync(FileAccessMode.Read)) { ulong size64 = readstream.Size; if (size64 <= uint.MaxValue) { uint size32 = (uint)size64; IBuffer buffer = new Windows.Storage.Streams.Buffer(size32); buffer = await readstream.ReadAsync(buffer, size32, InputStreamOptions.None); string filecontent = GetStringFromBuffer(buffer); XElement xmlroot = XElement.Parse(filecontent); IEnumerable <XElement> MaterialNames = from el in xmlroot.Elements("Data") select el; foreach (XElement el in MaterialNames) { ListOfAnodes.Items.Add(el.Element("Name").Value); ListOfCathodes.Items.Add(el.Element("Name").Value); } ListOfAnodes.IsEnabled = true; } else { await displayMessageAsync("Alert message", "Your data file is too large. It needs to be < 4 GB.", "notification"); } } } catch { await displayMessageAsync("Fail message", "The default data file did not load correctly.", "notification"); } } if (temp_file_2 != null) { treatmentFile = temp_file_2; } }
private async void GetImage() { FileOpenPicker picker = new FileOpenPicker(); picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary; picker.FileTypeFilter.Add(".png"); picker.FileTypeFilter.Add(".jpg"); picker.FileTypeFilter.Add(".jpeg"); StorageFile file = await picker.PickSingleFileAsync(); if (file != null) { IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read); BitmapImage image = new BitmapImage(); await image.SetSourceAsync(stream.CloneStream()); image.UriSource = new Uri(file.Path); MyBuffer buffer = new MyBuffer(new byte[stream.Size]); await stream.ReadAsync(buffer.Buffer, (uint)stream.Size, InputStreamOptions.None); var newAvatar = buffer.AsByteArray(); Database_Service.SchedServiceClient client = new Database_Service.SchedServiceClient(); account.avatarImage = newAvatar; Application.Current.Resources["User"] = account; await client.UpdateUserAsync(account.clientID, account.phoneNumber, account.address, account.username, newAvatar); EventViewModel e = this.DataContext as EventViewModel; e.newAvatar(newAvatar); DataContext = e; } }
/// <summary> /// Parses the "fmt" and "data" headers /// </summary> /// <param name="source">The IRandomAccessStream source to parse from</param> private async void ParseHeaders(IRandomAccessStream source) { source.Seek(0); var streamContent = new byte[Math.Min(1000, source.Size)]; await source.ReadAsync(streamContent.AsBuffer(), (uint)Math.Min(1000, source.Size), InputStreamOptions.None); var riffText = System.Text.Encoding.ASCII.GetString(streamContent, 0, 4); var waveText = System.Text.Encoding.ASCII.GetString(streamContent, 8, 4); var offset = 12; while (offset < streamContent.Length) { try { var chunkName = System.Text.Encoding.ASCII.GetString(streamContent, offset, 4).ToLower(); if (chunkName.StartsWith("fmt")) { ParseFormatChunk(streamContent, offset); } if (chunkName.StartsWith("data")) { DataChunkPosition = (ulong)offset; ReadingData = true; break; } offset += 8 + BitConverter.ToInt32(streamContent, offset + 4); } catch { break; } } }
private async System.Threading.Tasks.Task ReadFromFile() { using (IRandomAccessStream sessionRandomAccess = await this.sampleFile.OpenAsync(FileAccessMode.Read)) { if (sessionRandomAccess.Size > 0) { byte[] array3 = new byte[sessionRandomAccess.Size]; IBuffer output = await sessionRandomAccess.ReadAsync( array3.AsBuffer(0, (int)sessionRandomAccess.Size), (uint)sessionRandomAccess.Size, InputStreamOptions.Partial); string reRead = Encoding.UTF8.GetString(output.ToArray(), 0, (int)output.Length); StatusTextBlock.Text = "The following text was read from '" + this.sampleFile.Name + "' using a stream:" + Environment.NewLine + Environment.NewLine + reRead; } else { StatusTextBlock.Text = "File is empty"; } } }
public static async Task<IBuffer> ReadIntoBuffer(IRandomAccessStream stream) { stream.Seek(0); var buffer = new Buffer((uint) stream.Size); await stream.ReadAsync(buffer, buffer.Capacity, InputStreamOptions.None); return buffer; }
/// <summary> /// 用于上传拖拽的文件,每次可上传多个文件 /// </summary> /// <param name="cts"></param> /// <param name="files"></param> /// <param name="beforeUpload"></param> /// <param name="afterUpload"></param> /// <returns></returns> public static async Task <List <string>[]> UploadFileAsync(CancellationTokenSource cts, IReadOnlyList <IStorageItem> files, Action <int, int, string> beforeUpload, Action <int> afterUpload) { var fileNameList = new List <string>(); // 用于与其他文本内容一起POST var fileCodeList = new List <string>(); // 用于插入内容文本框 if (files != null && files.Count > 0) { int fileIndex = 1; foreach (var file in files) { string fileName = file.Name; beforeUpload?.Invoke(fileIndex, files.Count, fileName); fileNameList.Add(fileName); //byte[] imageBuffer; //if (deviceFamily.Equals("Windows.Mobile")) //{ // imageBuffer = await ImageHelper.LoadAsync(file); //} //else //{ IRandomAccessStream stream = await((StorageFile)file).OpenAsync(FileAccessMode.Read); IBuffer buffer = new Windows.Storage.Streams.Buffer((uint)stream.Size); buffer = await stream.ReadAsync(buffer, buffer.Capacity, InputStreamOptions.None); //} var data = new Dictionary <string, object>(); data.Add("uid", AccountService.UserId); data.Add("hash", AccountService.Hash); try { string url = "http://www.hi-pda.com/forum/misc.php?action=swfupload&operation=upload&simple=1"; string result = await _httpClient.PostFileAsync(url, data, fileName, "Filedata", buffer, cts); if (result.Contains("DISCUZUPLOAD|")) { string value = result.Split('|')[2]; value = $"[attachimg]{value}[/attachimg]"; fileCodeList.Add(value); fileIndex++; } } catch (Exception ex) { Debug.WriteLine(ex.Message); } } afterUpload?.Invoke(files.Count); } return(new List <string>[] { fileNameList, fileCodeList }); }
/// <summary> /// Updates the Samples array with new data from the source stream. Assumes that data fills up to the end of the stream. /// </summary> /// <param name="source">The source stream to read the data from</param> /// <returns></returns> private async Task ParseRollingData(IRandomAccessStream source) { var bytesLeft = source.Size - Position; var offsetSample = TotalSamples; var bytesPerSample = (ulong)SampleBitWidth / 8; var samplesToParse = bytesLeft / (bytesPerSample * (ulong)Channels); TotalSamples += (int)samplesToParse; if (Samples[0].Length < TotalSamples + (int)samplesToParse) { for (var c = 0; c < Channels; c++) { Array.Resize(ref Samples[c], Samples[0].Length + ((int)samplesToParse) + 4800); //Throw in an extra second for kicks } } var rawData = new byte[(int)samplesToParse * Channels * (int)bytesPerSample]; source.Seek(Position); await source.ReadAsync(rawData.AsBuffer(), (uint)rawData.Length, InputStreamOptions.None); for (ulong s = 0; s < samplesToParse; s++) { for (var c = 0; c < Channels; c++) { var sourceOffset = (int)((s * bytesPerSample * (ulong)Channels) + ((ulong)c * bytesPerSample)); if (sourceOffset >= rawData.Length) { break; } var sampleIndex = offsetSample + (int)s; switch (SampleBitWidth) { case 8: Samples[c][sampleIndex] = (long)rawData[sourceOffset]; continue; case 16: Samples[c][sampleIndex] = BitConverter.ToInt16(rawData, sourceOffset); continue; case 32: Samples[c][sampleIndex] = BitConverter.ToInt32(rawData, sourceOffset); continue; case 64: Samples[c][sampleIndex] = BitConverter.ToInt64(rawData, sourceOffset); continue; default: throw new NotImplementedException(); } } } Position += samplesToParse * (ulong)Channels * bytesPerSample; }
public static async Task <IBuffer> ReadIntoBuffer(IRandomAccessStream stream) { stream.Seek(0); var buffer = new Buffer((uint)stream.Size); await stream.ReadAsync(buffer, buffer.Capacity, InputStreamOptions.None); return(buffer); }
public static async Task <IBuffer> ToBuffer(this IRandomAccessStream stream) { stream.Seek(0); var buffer = new Windows.Storage.Streams.Buffer((uint)stream.Size); await stream.ReadAsync(buffer, buffer.Capacity, InputStreamOptions.None); return(buffer); }
public static async Task <bool> TryWriteStreamAsync(this StorageFile storageFile, IRandomAccessStream stream) { stream.Seek(0); IBuffer buffer = new byte[stream.Size].AsBuffer(); await stream.ReadAsync(buffer, buffer.Length, InputStreamOptions.None); return(await TryWriteBufferAsync(storageFile, buffer)); }
public IAsyncOperationWithProgress <IBuffer, uint> ReadAsync(IBuffer buffer, uint count, InputStreamOptions options) { lock (stream) { bytesRead += (int)count; } return(stream.ReadAsync(buffer, count, options)); }
public async static void SendPackage() { ulong currentOffset = 0; while (isCalling) { if (sendingStream.Size > currentOffset + (ulong)_bufferSize) { Debug.WriteLine(currentOffset); sendingStream.Seek(currentOffset); byte[] tempBuffer = new byte[_bufferSize]; await sendingStream.ReadAsync(tempBuffer.AsBuffer(), (uint)_bufferSize, InputStreamOptions.None); UdpService.Instance.SendMessage(tempBuffer, tempBuffer.Length); Debug.WriteLine(BitConverter.ToString(tempBuffer)); currentOffset += (ulong)_bufferSize; Debug.WriteLine(""); } Thread.Sleep(20); } //int currentOffset = 0; //while (isCalling) //{ // byte[] tempBuffer = new byte[_bufferSize]; // if ((int)_memoryBuffer.Size - currentOffset > _bufferSize) // { // var bytesRead = await _memoryBuffer.AsStream().ReadAsync(tempBuffer, currentOffset, _bufferSize); // Debug.WriteLine(currentOffset); // Debug.WriteLine(BitConverter.ToString(tempBuffer)); // UdpService.Instance.SendMessage(tempBuffer, tempBuffer.Length); // currentOffset += bytesRead; // Debug.WriteLine(""); // } //} //while (isCalling) //{ // byte[] arrayByteBuffer = new byte[_bufferSize]; // //IRandomAccessStream audioStream = _memoryBuffer.CloneStream(); // // arrayByteBuffer = await ToBytesArray(_memoryBuffer, _bufferSize); // //var byteWrite = await _memoryBuffer.WriteAsync(arrayByteBuffer.AsBuffer()); // var byteRead = await _memoryBuffer.ReadAsync(arrayByteBuffer.AsBuffer(), (uint)_bufferSize, Windows.Storage.Streams.InputStreamOptions.None); // // Debug.WriteLine("Sending package, arraylength: " + arrayByteBuffer.Length + "Byte array: " + arrayByteBuffer); // if (arrayByteBuffer.GetLength(0) == _bufferSize) // { // Debug.WriteLine("Sending" + arrayByteBuffer.Length); // UdpService.Instance.SendMessage(arrayByteBuffer, arrayByteBuffer.Length); // await _memoryBuffer.FlushAsync(); // } // Thread.Sleep(100); //} }
public async Task <ImageSource> InitializeAsync(CoreDispatcher dispatcher, IRandomAccessStream streamSource, CancellationTokenSource cancellationTokenSource) { byte[] bytes = new byte[streamSource.Size]; await streamSource.ReadAsync(bytes.AsBuffer(), (uint)streamSource.Size, InputStreamOptions.None).AsTask(cancellationTokenSource.Token); var imageSource = WebpCodec.Decode(bytes); return(imageSource); }
/// <summary> /// Reads a binary file, returning a byte array. /// </summary> /// <param name="file">File to read</param> /// <returns>Returns Task as a result of asynchronous operation. /// Task result is full file content</returns> public static async Task <byte[]> ReadAllBytes(StorageFile file) { IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read); byte[] buffBytes = new byte[stream.Size]; IBuffer buffer = buffBytes.AsBuffer(); await stream.ReadAsync(buffer, (uint)stream.Size, InputStreamOptions.ReadAhead); return(buffBytes); }
public static async Task <string> ToBase64StringAsync(this IRandomAccessStream randomAccessStream) { var array = ArrayPool <byte> .Shared.Rent((int)randomAccessStream.Size); var buffer = await randomAccessStream.ReadAsync(array.AsBuffer(), (uint)randomAccessStream.Size, InputStreamOptions.None); ArrayPool <byte> .Shared.Return(array); return(Convert.ToBase64String(buffer.ToArray())); }
private static async Task <byte[]> GetFileContent(IRandomAccessStream stream) { // This is where the byteArray to be stored. var bytes = new byte[stream.Size]; // This returns IAsyncOperationWithProgess, so you can add additional progress handling await stream.ReadAsync(bytes.AsBuffer(), (uint)stream.Size, InputStreamOptions.ReadAhead); return(bytes); }
public static async Task <byte[]> AsByteArray(this IRandomAccessStream stream) { // Reset stream position stream.Seek(0); var bytes = new byte[stream.Size]; await stream.ReadAsync(bytes.AsBuffer(), (uint)stream.Size, InputStreamOptions.None); return(bytes); }
public EventViewModel() { Chat = ""; StorageFile file = StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/weather/01d.png")).AsTask().GetAwaiter().GetResult(); IRandomAccessStream stream = file.OpenAsync(FileAccessMode.Read).AsTask().GetAwaiter().GetResult(); MyBuffer buffer = new MyBuffer(new byte[stream.Size]); stream.ReadAsync(buffer.Buffer, (uint)stream.Size, InputStreamOptions.None).AsTask().GetAwaiter().GetResult(); newAvatar(buffer.AsByteArray()); }
public async Task <byte[]> ReadAsync(string fullPath) { StorageFile file = await StorageFile.GetFileFromPathAsync(fullPath); using (IRandomAccessStream input = await file.OpenReadAsync()) { byte[] bytes = new byte[input.Size]; await input.ReadAsync(bytes.AsBuffer(), (uint)input.Size, InputStreamOptions.None); return(bytes); } }
public static IAsyncOperation<SHA1Value> ComputeAsync(IRandomAccessStream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); return Task.Run(async () => { stream.Seek(0); var buf = new Windows.Storage.Streams.Buffer((uint)stream.Size); await stream.ReadAsync(buf, (uint)stream.Size, InputStreamOptions.None); return new SHA1Value(sha1compute.HashData(buf)); }).AsAsyncOperation(); }
/// <summary> /// Loads the specified key file. /// </summary> /// <param name="input">The input.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException"> /// The <paramref name="input"/> parameter cannot be <c>null</c>. /// </exception> private static async Task <IBuffer> LoadKeyFile(IRandomAccessStream input) { if (input == null) { throw new ArgumentNullException("input"); } var buffer = WindowsRuntimeBuffer.Create(1024); switch (input.Size) { case 32: // Binary key file return(await input.ReadAsync(buffer, 32)); case 64: // Hex text key file buffer = await input.ReadAsync(buffer, 64); var hex = CryptographicBuffer.ConvertBinaryToString( BinaryStringEncoding.Utf8, buffer); if (IsHexString(hex)) { return(CryptographicBuffer.DecodeFromHexString(hex)); } break; } // XML input.Seek(0); var xml = LoadXmlKeyFile(input); if (xml != null) { return(xml); } // Random keyfile input.Seek(0); return(await GetFileHash(input, buffer)); }
/// <summary> /// /// </summary> /// <param name="fileName"></param> /// <param name="stream"></param> /// <returns></returns> public static async Task<StorageFile> SaveToTemporary(string fileName, IRandomAccessStream stream) { // IRandomAccessStreamのストリームを保存する var file = await StorageFile.CreateStreamedFileAsync(fileName, async writeStream => { var imageBuffer = new byte[stream.Size]; var ibuffer = imageBuffer.AsBuffer(); await stream.ReadAsync(ibuffer, (uint)stream.Size, InputStreamOptions.None); await writeStream.WriteAsync(ibuffer); }, null); return file; }
private async void LoadCompatibilityFile() { string filename = "TableI_Data.csv"; string currentDirectory = Directory.GetCurrentDirectory(); //$"C:\\Users\\steve\\Documents"; // string CompatibilityFilepath = Path.Combine(currentDirectory, filename); //StorageFolder storageFolder = await StorageFolder.GetFolderFromPathAsync(currentDirectory); StorageFile temp_file = await StorageFile.GetFileFromPathAsync(CompatibilityFilepath); if (temp_file != null) { try { using (IRandomAccessStream readstream = await temp_file.OpenAsync(FileAccessMode.Read)) { ulong size64 = readstream.Size; if (size64 <= uint.MaxValue) { uint size32 = (uint)size64; IBuffer buffer = new Windows.Storage.Streams.Buffer(size32); buffer = await readstream.ReadAsync(buffer, size32, InputStreamOptions.None); string filecontent = GetStringFromBuffer(buffer); string[] data_from_comp_file = filecontent.Split(new char[] { ',', '\r', '\n' }, StringSplitOptions.None); int start_of_table = 63; int num_rows_of_table = CompatibilityTable.GetLength(0); int num_cols_of_table = CompatibilityTable.GetLength(1); int array_index = 0; int start_index = start_of_table, end_index = start_of_table + num_cols_of_table; for (int i = 0; i <= num_rows_of_table - 1; i++) { array_index = start_index; for (int j = 0; j <= num_cols_of_table - 1; j++) { CompatibilityTable[i, j] = data_from_comp_file[array_index]; array_index++; } start_index = end_index + 1; end_index = start_index + num_cols_of_table; } } } } catch { await displayMessageAsync("Fail message", "The compatibility data file did not load correctly.", "notification"); } } }
/// <summary> /// Computes the SHA1 hash of the given IRandomAccessStream /// </summary> /// <param name="stream">IRandomAccessStream</param> /// <returns>Hashed string</returns> private static async Task <string> ComputeHashAsync(IRandomAccessStream stream) { // Copy the stream to IBuffer IBuffer buffer = new Windows.Storage.Streams.Buffer((uint)stream.Size); buffer = await stream.ReadAsync(buffer, buffer.Capacity, InputStreamOptions.None); // Calculate the hash var bufferHash = AlgorithmProvider.HashData(buffer); // Encode to hexadecimal lowercase characters var hash = CryptographicBuffer.EncodeToHexString(bufferHash).ToLower(); return(hash); }
private async Task <byte[]> getByteArrayFromStream(IRandomAccessStream stream, bool swap = false) { var result = new byte[stream.Size]; if (swap) { using (var output = new InMemoryRandomAccessStream()) { using (var reader = new DataReader(stream.GetInputStreamAt(0))) { //reader.ByteOrder = ByteOrder.LittleEndian; using (var writer = new DataWriter(output)) { //writer.ByteOrder = ByteOrder.BigEndian; await reader.LoadAsync((uint)stream.Size); while (0 < reader.UnconsumedBufferLength) { var number = reader.ReadUInt16(); var bytes_number = BitConverter.GetBytes(number); writer.WriteBytes(bytes_number); } await writer.StoreAsync(); await writer.FlushAsync(); writer.DetachStream(); output.Seek(0); } reader.DetachStream(); } await output.ReadAsync(result.AsBuffer(), (uint)stream.Size, InputStreamOptions.None); var folder = await DownloadsFolder.CreateFileAsync(DateTime.UtcNow.Ticks + ".out"); using (var file = await folder.OpenStreamForWriteAsync()) { await file.WriteAsync(result, 0, result.Length); await file.FlushAsync(); } } } else { await stream.ReadAsync(result.AsBuffer(), (uint)stream.Size, InputStreamOptions.None); } return(result); }
public async Task<ExtendImageSource> InitializeAsync(CoreDispatcher dispatcher, IRandomAccessStream streamSource, CancellationTokenSource cancellationTokenSource) { byte[] bytes = new byte[streamSource.Size]; await streamSource.ReadAsync(bytes.AsBuffer(), (uint)streamSource.Size, InputStreamOptions.None).AsTask(cancellationTokenSource.Token); WriteableBitmap writeableBitmap = WebpCodec.Decode(bytes); ExtendImageSource imageSource = new ExtendImageSource(); if (writeableBitmap != null) { imageSource.PixelWidth = writeableBitmap.PixelWidth; imageSource.PixelHeight = writeableBitmap.PixelHeight; imageSource.ImageSource = writeableBitmap; } return imageSource; }
internal static async Task <byte[]> ToByteArrayAsync(this StorageFile file) { if (file == null) { return(null); } using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.Read)) { var bytes = new byte[fileStream.Size]; await fileStream.ReadAsync(bytes.AsBuffer(), (uint)fileStream.Size, InputStreamOptions.None); return(bytes); } }
/// <summary> /// Set an image to this class by specifying an input stream that contains image data /// in one of the supported MIME types (e.g., JPEG or PNG file contents). /// </summary> /// <remarks> /// The stream has to contain one of the supported MIME types - e.g., /// a JPEG or PNG image. The stream contents are set as the payload of this record. /// This method will try to find out the MIME type of the referenced /// stream contents automatically and adapt the type of the NDEF record accordingly. /// </remarks> /// <returns>Task to await completion of the asynchronous image loading / parsing.</returns> public async Task LoadStream(IRandomAccessStream imgStream) { if (imgStream == null) { throw new ArgumentNullException("imgStream"); } var decoder = await BitmapDecoder.CreateAsync(imgStream); var fileCodecId = decoder.DecoderInformation.CodecId; Payload = new byte[imgStream.Size]; await imgStream.ReadAsync(Payload.AsBuffer(), (uint)imgStream.Size, InputStreamOptions.None); Type = ImageMimeTypes[GetMimeTypeForBitmapDecoderId(fileCodecId)]; }
async public static Task <IRandomAccessStream> DecryptMedia(StorageFile file) { IRandomAccessStream ras = await file.OpenAsync(FileAccessMode.Read); IBuffer ibuf = new Windows.Storage.Streams.Buffer((uint)ras.Size); ibuf = await ras.ReadAsync(ibuf, (uint)ras.Size, InputStreamOptions.None); IBuffer ibuf2 = EncryptionProvider.Decrypt(ibuf); InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream(); await ms.WriteAsync(ibuf2); ms.Seek(0); return(ms); }
/// <summary> /// ストリームを保存する /// </summary> /// <param name="file">ファイルストレージ</param> /// <param name="stream">保存するデータのストリーム</param> /// <returns>ファイル</returns> public static async Task <StorageFile> SaveAsync(this StorageFile file, IRandomAccessStream stream) { using (var outputStrm = await file.OpenAsync(FileAccessMode.ReadWrite)) { // 書き込むファイルからデータを読み込む var imageBuffer = new byte[stream.Size]; var ibuffer = imageBuffer.AsBuffer(); stream.Seek(0); await stream.ReadAsync(ibuffer, (uint)stream.Size, InputStreamOptions.None); // データをファイルに書き出す await outputStrm.WriteAsync(ibuffer); } return(file); }
private async void UploadImage(StorageFile file) { try { pr_Upload.Visibility = Visibility.Visible; var url = "http://api.vc.bilibili.com/api/v1/image/upload?access_key={0}&appkey={1}&build=5250000&platform=android&src=bilih5&ts={2}"; url = string.Format(url, ApiHelper.access_key, ApiHelper.AndroidKey.Appkey, ApiHelper.GetTimeSpan_2); url += "&sign=" + ApiHelper.GetSign(url); IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.Read); var bytes = new byte[fileStream.Size]; await fileStream.ReadAsync(bytes.AsBuffer(), (uint)fileStream.Size, Windows.Storage.Streams.InputStreamOptions.None); var client = new RestClient(url); var request = new RestRequest(Method.POST); request.AddFile("file_up", bytes, file.Name); IRestResponse response = await client.Execute(request); var content = response.Content; UploadImagesModel uploadImagesModel = JsonConvert.DeserializeObject <UploadImagesModel>(content); if (uploadImagesModel.code == 0) { uploadImagesModel.data.image_size = (await file.GetBasicPropertiesAsync()).Size / 1024; imgs.Add(uploadImagesModel.data); } else { Utils.ShowMessageToast(uploadImagesModel.message); } } catch (Exception) { Utils.ShowMessageToast("图片上传失败"); } finally { pr_Upload.Visibility = Visibility.Collapsed; if (gv_Pics.Items.Count != 0) { pics.Visibility = Visibility.Visible; } else { pics.Visibility = Visibility.Collapsed; } txt_PicCount.Text = gv_Pics.Items.Count.ToString(); } }
/// <summary> /// Save the stream to a file in the local folder /// </summary> /// <param name="remoteStream">Stream to save</param> /// <param name="fileName">File's name</param> /// <returns>Task to support await of async call.</returns> public static async Task SaveToLocalFolder(IRandomAccessStream remoteStream, string fileName) { var localFolder = ApplicationData.Current.LocalFolder; byte[] buffer = new byte[remoteStream.Size]; var localBuffer = await remoteStream.ReadAsync(buffer.AsBuffer(), (uint)remoteStream.Size, InputStreamOptions.ReadAhead); var myLocalFile = await localFolder.CreateFileAsync(fileName, CreationCollisionOption.GenerateUniqueName); using (var localStream = await myLocalFile.OpenAsync(FileAccessMode.ReadWrite)) { await localStream.WriteAsync(localBuffer); await localStream.FlushAsync(); } }
public async Task<ImagePackage> InitializeAsync(CoreDispatcher dispatcher, Image image, Uri uriSource, IRandomAccessStream streamSource, CancellationTokenSource cancellationTokenSource) { byte[] bytes = new byte[streamSource.Size]; await streamSource.ReadAsync(bytes.AsBuffer(), (uint)streamSource.Size, InputStreamOptions.None).AsTask(cancellationTokenSource.Token); int width, height; WriteableBitmap writeableBitmap = null; if (WebpCodec.GetInfo(bytes, out width, out height)) { writeableBitmap = new WriteableBitmap(width, height); await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { var uri = image.Tag as Uri; if (uri == uriSource) { image.Source = writeableBitmap; } }); WebpCodec.Decode(writeableBitmap, bytes); } return new ImagePackage(this, writeableBitmap, writeableBitmap.PixelWidth, writeableBitmap.PixelHeight); }
public static async Task<bool> TryWriteStreamAsync(this StorageFile storageFile, IRandomAccessStream stream) { stream.Seek(0); IBuffer buffer = new byte[stream.Size].AsBuffer(); await stream.ReadAsync(buffer, buffer.Length, InputStreamOptions.None); return await TryWriteBufferAsync(storageFile, buffer); }
private async Task<IRandomAccessStream> ResizeStreamAsync(IRandomAccessStream stream, Size size, PhotoOrientation orientation) { var rotation = 0; switch (orientation) { case PhotoOrientation.Rotate180: { rotation = -180; }; break; case PhotoOrientation.Rotate270: { rotation = -270; }; break; case PhotoOrientation.Rotate90: { rotation = -90; }; break; } using (var resizedStream = new InMemoryRandomAccessStream()) { var buffer = new byte[stream.Size].AsBuffer(); stream.Seek(0); await stream.ReadAsync(buffer, buffer.Length, InputStreamOptions.None); var resizeConfiguration = new AutoResizeConfiguration( (uint)(size.Width * size.Height * 4 * 2), size, new Size(0, 0), AutoResizeMode.Automatic, 0.7, ColorSpace.Yuv420); buffer = await JpegTools.AutoResizeAsync(buffer, resizeConfiguration); await resizedStream.WriteAsync(buffer); await resizedStream.FlushAsync(); if (rotation != 0) { resizedStream.Seek(0); var filters = new List<IFilter>() { new RotationFilter(rotation) }; using (var source = new RandomAccessStreamImageSource(resizedStream)) using (var effect = new FilterEffect(source) { Filters = filters }) using (var renderer = new JpegRenderer(effect)) { buffer = await renderer.RenderAsync(); using (var rotatedResizedStream = new InMemoryRandomAccessStream()) { await rotatedResizedStream.WriteAsync(buffer); await rotatedResizedStream.FlushAsync(); return rotatedResizedStream.CloneStream(); } } } else { return resizedStream.CloneStream(); } } }
/// <summary> /// Loads the specified key file. /// </summary> /// <param name="input">The input.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException"> /// The <paramref name="input"/> parameter cannot be <c>null</c>. /// </exception> private static async Task<IBuffer> LoadKeyFile(IRandomAccessStream input) { if (input == null) throw new ArgumentNullException("input"); var buffer = WindowsRuntimeBuffer.Create(1024); switch (input.Size) { case 32: // Binary key file return await input.ReadAsync(buffer, 32); case 64: // Hex text key file buffer = await input.ReadAsync(buffer, 64); var hex = CryptographicBuffer.ConvertBinaryToString( BinaryStringEncoding.Utf8, buffer); if (IsHexString(hex)) return CryptographicBuffer.DecodeFromHexString(hex); break; } // XML input.Seek(0); var xml = LoadXmlKeyFile(input); if (xml != null) return xml; // Random keyfile input.Seek(0); return await GetFileHash(input, buffer); }
/// <summary> /// Computes the SHA1 hash of the given IRandomAccessStream /// </summary> /// <param name="stream">IRandomAccessStream</param> /// <returns>Hashed string</returns> private static async Task<string> ComputeHashAsync(IRandomAccessStream stream) { // Copy the stream to IBuffer IBuffer buffer = new Windows.Storage.Streams.Buffer((uint)stream.Size); buffer = await stream.ReadAsync(buffer, buffer.Capacity, InputStreamOptions.None); // Calculate the hash var bufferHash = AlgorithmProvider.HashData(buffer); // Encode to hexadecimal lowercase characters var hash = CryptographicBuffer.EncodeToHexString(bufferHash).ToLower(); return hash; }
/// <summary> /// ストリームを保存する /// </summary> /// <param name="file">ファイルストレージ</param> /// <param name="stream">保存するデータのストリーム</param> /// <returns>ファイル</returns> public static async Task<StorageFile> SaveAsync(this StorageFile file, IRandomAccessStream stream) { using (var outputStrm = await file.OpenAsync(FileAccessMode.ReadWrite)) { // 書き込むファイルからデータを読み込む var imageBuffer = new byte[stream.Size]; var ibuffer = imageBuffer.AsBuffer(); stream.Seek(0); await stream.ReadAsync(ibuffer, (uint)stream.Size, InputStreamOptions.None); // データをファイルに書き出す await outputStrm.WriteAsync(ibuffer); } return file; }
/// <summary> /// 指定されたフォルダーへファイルを保存する /// 既存の同名ファイルが存在している場合はファイルを上書きする /// </summary> /// <param name="folder">フォルダー</param> /// <param name="fileName">拡張子を含むファイル名</param> /// <param name="stream">保存するデータのストリーム</param> /// <returns>ファイル</returns> public static async Task<StorageFile> SaveFileAsync(this IStorageFolder folder, string fileName, IRandomAccessStream stream) { var file = await folder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting); using (var outputStrm = await file.OpenAsync(FileAccessMode.ReadWrite)) { // 書き込むファイルからデータを読み込む var imageBuffer = new byte[stream.Size]; var ibuffer = imageBuffer.AsBuffer(); stream.Seek(0); await stream.ReadAsync(ibuffer, (uint)stream.Size, InputStreamOptions.None); // データをファイルに書き出す await outputStrm.WriteAsync(ibuffer); } return file; }
/// <summary> /// Set an image to this class by specifying an input stream that contains image data /// in one of the supported MIME types (e.g., JPEG or PNG file contents). /// </summary> /// <remarks> /// The stream has to contain one of the supported MIME types - e.g., /// a JPEG or PNG image. The stream contents are set as the payload of this record. /// This method will try to find out the MIME type of the referenced /// stream contents automatically and adapt the type of the NDEF record accordingly. /// </remarks> /// <returns>Task to await completion of the asynchronous image loading / parsing.</returns> public async Task LoadStream(IRandomAccessStream imgStream) { if (imgStream == null) throw new ArgumentNullException("imgStream"); var decoder = await BitmapDecoder.CreateAsync(imgStream); var fileCodecId = decoder.DecoderInformation.CodecId; Payload = new byte[imgStream.Size]; await imgStream.ReadAsync(Payload.AsBuffer(), (uint)imgStream.Size, InputStreamOptions.None); Type = ImageMimeTypes[GetMimeTypeForBitmapDecoderId(fileCodecId)]; }