async private void AppBarButton_Click_4(object sender, RoutedEventArgs e) { //Uri uri = new Uri("http://www.charlespetzold.com/pw6/PetzoldJersey.jpg"); Uri uri = new Uri("ms-appx:///PetzoldJersey.jpg"); 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); } // Create WriteableBitmap with unknown size WriteableBitmap bitmap = new WriteableBitmap(1, 1); // 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 bitmap.SetSource(memoryStream); } // Now get the pixels from the bitmap byte[] pixels = new byte[4 * bitmap.PixelWidth * bitmap.PixelHeight]; int index = 0; using (Stream pixelStream = bitmap.PixelBuffer.AsStream()) { await pixelStream.ReadAsync(pixels, 0, pixels.Length); // Apply opacity to the pixels for (int y = 0; y < bitmap.PixelHeight; y++) { double opacity = (double)y / bitmap.PixelHeight; for (int x = 0; x < bitmap.PixelWidth; x++) { for (int i = 0; i < 4; i++) { pixels[index] = (byte)(opacity * pixels[index]); index++; } } } // Put the pixels back in the bitmap pixelStream.Seek(0, SeekOrigin.Begin); await pixelStream.WriteAsync(pixels, 0, pixels.Length); } bitmap.Invalidate(); reflectedImage.Source = bitmap; }
public async Task TakePicture() { CameraCaptureUI captureUI = new CameraCaptureUI(); captureUI.PhotoSettings.Format = CameraCaptureUIPhotoFormat.Jpeg; // captureUI.PhotoSettings.CroppedSizeInPixels = new Size(200, 200); StorageFile photoFile = await captureUI.CaptureFileAsync(CameraCaptureUIMode.Photo); if (photoFile != null) { IRandomAccessStreamWithContentType stream = await photoFile.OpenReadAsync(); var buffer = new byte[stream.Size]; await stream.ReadAsync(buffer.AsBuffer(), (uint)stream.Size, InputStreamOptions.None); var photo = new Photo { Content = buffer, Description = "My photo" }; await _PhotosService.AddAsync(photo); } }
public async static Task <byte[]> ImageToBytes(BitmapImage image) { RandomAccessStreamReference streamRef = RandomAccessStreamReference.CreateFromUri(image.UriSource); IRandomAccessStreamWithContentType streamWithContent = await streamRef.OpenReadAsync(); byte[] buffer = new byte[streamWithContent.Size]; await streamWithContent.ReadAsync(buffer.AsBuffer(), (uint)streamWithContent.Size, InputStreamOptions.None); return(buffer); }
async static Task <byte[]> fileToBytesAsync(StorageFile file) { RandomAccessStreamReference streamRef = RandomAccessStreamReference.CreateFromFile(file); IRandomAccessStreamWithContentType streamWithContent = await streamRef.OpenReadAsync(); byte[] buffer = new byte[streamWithContent.Size]; await streamWithContent.ReadAsync(buffer.AsBuffer(), (uint)streamWithContent.Size, InputStreamOptions.None); return(buffer); }
public async Task <byte[]> ConvertPictureToBinary(Image picture) { BitmapImage source = picture.Source as BitmapImage; RandomAccessStreamReference streamReference = RandomAccessStreamReference.CreateFromUri(source.UriSource); IRandomAccessStreamWithContentType streamWithContent = await streamReference.OpenReadAsync(); byte[] buffer = new byte[streamWithContent.Size]; await streamWithContent.ReadAsync(buffer.AsBuffer(), (uint)streamWithContent.Size, InputStreamOptions.None); return(buffer); }
/// <summary> /// Loads the byte data from a StorageFile /// </summary> /// <param name="file">The file to read</param> public async Task <byte[]> ReadFile(StorageFile file) { using (IRandomAccessStreamWithContentType stream = await file.OpenReadAsync()) { stream.Seek((ulong)0); byte[] fileBytes = new byte[stream.Size]; var buffer = CryptographicBuffer.CreateFromByteArray(fileBytes); IBuffer rd = await stream.ReadAsync(buffer, (uint)fileBytes.Length, InputStreamOptions.None); rd.CopyTo(fileBytes); return(fileBytes); } }
private static async Task <string> toBase64Async(RandomAccessStreamReference imageStream) { //FileStream fs = new FileStream(image.Path,FileMode.); IRandomAccessStreamWithContentType a = await imageStream.OpenReadAsync(); byte[] bytes = new byte[a.Size]; var buffer = await a.ReadAsync(bytes.AsBuffer(), (uint)a.Size, InputStreamOptions.None); bytes = buffer.ToArray(); //buffer.ToArray(); String base64 = Convert.ToBase64String(bytes); //base64 = HttpUtility.UrlEncode(base64); return(base64); }
private static async Task <uint> BlobReadStreamSeekAndCompareAsync(IRandomAccessStreamWithContentType blobStream, byte[] bufferToCompare, ulong offset, uint readSize, uint expectedReadCount) #endif { byte[] testBuffer = new byte[readSize]; #if ASPNET_K int actualReadSize = await blobStream.ReadAsync(testBuffer, 0, (int)readSize); Assert.AreEqual(expectedReadCount, actualReadSize); #else IBuffer testBufferAsIBuffer = testBuffer.AsBuffer(); await blobStream.ReadAsync(testBufferAsIBuffer, readSize, InputStreamOptions.None); Assert.AreEqual(expectedReadCount, testBufferAsIBuffer.Length); #endif long bufferOffset = (long)offset; for (int i = 0; i < expectedReadCount; i++, bufferOffset++) { Assert.AreEqual(bufferToCompare[bufferOffset], testBuffer[i]); } return(expectedReadCount); }
private static async Task <uint> FileReadStreamSeekAndCompareAsync(IRandomAccessStreamWithContentType fileStream, byte[] bufferToCompare, ulong offset, uint readSize, uint expectedReadCount) { byte[] testBuffer = new byte[readSize]; IBuffer testBufferAsIBuffer = testBuffer.AsBuffer(); await fileStream.ReadAsync(testBufferAsIBuffer, readSize, InputStreamOptions.None); Assert.AreEqual(expectedReadCount, testBufferAsIBuffer.Length); long bufferOffset = (long)offset; for (int i = 0; i < expectedReadCount; i++, bufferOffset++) { Assert.AreEqual(bufferToCompare[bufferOffset], testBuffer[i]); } return(expectedReadCount); }
private async void btn_Random_Click(object sender, RoutedEventArgs e) { try { pr_Load.Visibility = Visibility.Visible; Uri uri = new Uri("ms-appx:///Assets/avatar/ic_avatar" + new Random().Next(1, 12) + ".jpg"); RandomAccessStreamReference streamRef = RandomAccessStreamReference.CreateFromUri(uri); Windows.Storage.Streams.Buffer buffer = null; using (IRandomAccessStreamWithContentType fileStream = await streamRef.OpenReadAsync()) { buffer = new Windows.Storage.Streams.Buffer((uint)fileStream.Size); await fileStream.ReadAsync(buffer, (uint)fileStream.Size, InputStreamOptions.None); } Stream stream = WindowsRuntimeBufferExtensions.AsStream(buffer); string resutls = ""; // resutls = await WebClientClass.PostResults(new Uri(string.Format("https://account.bilibili.com/pendant/updateFace?type=jpg&size=s")), stream.AsInputStream(), "https://account.bilibili.com/site/updateface.html?type=face"); // resutls = await WebClientClass.PostResults(new Uri(string.Format("https://account.bilibili.com/pendant/updateFace?type=jpg&size=m")), stream.AsInputStream(), "https://account.bilibili.com/site/updateface.html?type=face"); resutls = await WebClientClass.PostResults(new Uri(string.Format("https://account.bilibili.com/pendant/updateFace?type=jpg&size=l")), stream.AsInputStream(), "https://account.bilibili.com/site/updateface.html?type=face"); JObject obj = JObject.Parse(resutls); if (obj["state"].ToString() == "OK") { MessageCenter.SendLogined(); messShow.Show("头像更换成功", 3000); } else { messShow.Show("头像更换失败", 3000); } } catch (Exception ex) { messShow.Show("头像更换失败\r\n" + ex.Message, 3000); } finally { pr_Load.Visibility = Visibility.Collapsed; GetProfile(); } }
private static async Task<uint> FileReadStreamSeekAndCompareAsync(IRandomAccessStreamWithContentType fileStream, byte[] bufferToCompare, ulong offset, uint readSize, uint expectedReadCount) { byte[] testBuffer = new byte[readSize]; IBuffer testBufferAsIBuffer = testBuffer.AsBuffer(); await fileStream.ReadAsync(testBufferAsIBuffer, readSize, InputStreamOptions.None); Assert.AreEqual(expectedReadCount, testBufferAsIBuffer.Length); long bufferOffset = (long)offset; for (int i = 0; i < expectedReadCount; i++, bufferOffset++) { Assert.AreEqual(bufferToCompare[bufferOffset], testBuffer[i]); } return expectedReadCount; }
private async Task StartDownloadAndReadContentsAsync() { try { // Retrieve a random access stream from the download operation. Every OpenReadAsync() operation returns // a new stream instance that is independent of previous ones (i.e., the seek position of one stream // isn't affected by calls on another stream). // // This sample demonstrates the direct usage of a DownloadOperation's random access stream and its // effects on the ongoing transfer. However, bear in mind that there are a variety of operations // that can manage the stream on the app's behalf for specific scenarios. For instance, a // DownloadOperation pointing to a video URL can be consumed by the MediaPlayer class in four easy // steps: // // var randomAccessStreamReference = download.GetResultRandomAccessStreamReference(); // stream = await randomAccessStreamReference.OpenReadAsync(); // var mediaPlayer = new Windows.Media.Playback.MediaPlayer(); // mediaPlayer.Source = Windows.Media.Core.MediaSource.CreateFromStream(stream, stream.ContentType); var randomAccessStreamReference = download.GetResultRandomAccessStreamReference(); randomAccessStream = await randomAccessStreamReference.OpenReadAsync(); // Start the download. If the server doesn't support random access, the download will fail // with WebErrorStatus.InsufficientRangeSupport or WebErrorStatus.MissingContentLengthSupport. IAsyncOperationWithProgress <DownloadOperation, DownloadOperation> downloadOperation = download.StartAsync(); downloadOperation.Progress += OnDownloadProgress; Task downloadTask = downloadOperation.AsTask(); startDownloadButton.IsEnabled = false; pauseDownloadButton.IsEnabled = true; // Read data while the download is still ongoing. Use a 1 MB read buffer for that purpose. var readBuffer = new Windows.Storage.Streams.Buffer(BytesPerMegaByte); while (!downloadTask.IsCompleted) { ulong readOffsetInBytes = randomAccessStream.Position; PreviousReadText.Text = CurrentReadText.Text; CurrentReadText.Text = $"Reading from offset {readOffsetInBytes:n0}"; readOperation = randomAccessStream.ReadAsync( readBuffer, readBuffer.Capacity, InputStreamOptions.None). AsTask(readCancellationTokenSource.Token); // Update the UI to show the current read's position. currentPositionSlider.Value = readOffsetInBytes / BytesPerMegaByte; try { // Wait for the read to complete. IBuffer bytesRead = await readOperation; CurrentReadText.Text += $", completed with {bytesRead.Length:n0} bytes"; // At this point, a real app would process the 'bytesRead' data to do something interesting // with it (e.g., display video and/or play audio). if (randomAccessStream.Position >= randomAccessStream.Size) { // We have reached EOF. Wrap around to the beginning while we wait for the download to complete. randomAccessStream.Seek(0); } } catch (OperationCanceledException) { // The ongoing read was canceled by SeekDownload_Click(...) in order for a new download // position to take effect immediately. CurrentReadText.Text += ", cancelled."; } } // Wait for the download to complete. await downloadTask; rootPage.NotifyUser("Download completed successfully", NotifyType.StatusMessage); } catch (Exception ex) when(IsWebException("Execution error", ex)) { // Abandon the operation if a web exception occurs. } finally { download = null; randomAccessStream = null; readOperation = null; startDownloadButton.IsEnabled = true; pauseDownloadButton.IsEnabled = false; resumeDownloadButton.IsEnabled = false; } }
private static async Task<uint> BlobReadStreamSeekAndCompareAsync(IRandomAccessStreamWithContentType blobStream, byte[] bufferToCompare, ulong offset, uint readSize, uint expectedReadCount) #endif { byte[] testBuffer = new byte[readSize]; #if ASPNET_K int actualReadSize = await blobStream.ReadAsync(testBuffer, 0, (int) readSize); Assert.AreEqual(expectedReadCount, actualReadSize); #else IBuffer testBufferAsIBuffer = testBuffer.AsBuffer(); await blobStream.ReadAsync(testBufferAsIBuffer, readSize, InputStreamOptions.None); Assert.AreEqual(expectedReadCount, testBufferAsIBuffer.Length); #endif long bufferOffset = (long)offset; for (int i = 0; i < expectedReadCount; i++, bufferOffset++) { Assert.AreEqual(bufferToCompare[bufferOffset], testBuffer[i]); } return expectedReadCount; }
async void Save_Contacts(IReadOnlyList <Contact> cntctsList) { try { StorageFolder localFolderStorage = await globalStorageFolder.CreateFolderAsync("WPLogical_" + todayDateTime, CreationCollisionOption.OpenIfExists); StorageFile contactHtmlFile = await localFolderStorage.CreateFileAsync("contacts_" + todayDateTime + ".html", CreationCollisionOption.OpenIfExists); var streamHTML = await contactHtmlFile.OpenAsync(FileAccessMode.ReadWrite); var writerHTML = new DataWriter(streamHTML.GetOutputStreamAt(0)); StringBuilder htmlBuilder = new StringBuilder(); StringBuilder tempStringBuilder = new StringBuilder(); //Generate HTML table headers htmlBuilder.AppendLine("<html>"); htmlBuilder.AppendLine("<head>"); htmlBuilder.AppendLine("<style type=\"text/css\">"); htmlBuilder.AppendLine(".tg {border-collapse:collapse;border-spacing:0;}"); htmlBuilder.AppendLine(".tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;}"); htmlBuilder.AppendLine(".tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;}"); htmlBuilder.AppendLine(".tg .tg-qk49{font-weight:bold;background-color:#306f98;color:#ffffff;vertical-align:top}"); htmlBuilder.AppendLine(".tg .tg-yw4l{vertical-align:top}"); htmlBuilder.AppendLine("</style>"); htmlBuilder.AppendLine("<meta charset=\"UTF-8\">"); htmlBuilder.AppendLine("</head>"); htmlBuilder.AppendLine("<body>"); //Table details starts htmlBuilder.AppendLine("<table class=\"tg\">"); htmlBuilder.AppendLine(" <tr>"); htmlBuilder.AppendLine(" <th class=\"tg-qk49\">Acquisition details</th>"); htmlBuilder.AppendLine(" </tr>"); htmlBuilder.AppendLine(" <tr>"); htmlBuilder.AppendLine(" <td class=\"tg-yw4l\">" + getdeviceInfo(cntctsList.Count) + "</td>"); htmlBuilder.AppendLine(" </tr>"); //Table details ends htmlBuilder.AppendLine("</table>"); htmlBuilder.AppendLine("<table class=\"tg\">"); htmlBuilder.AppendLine(" <tr>"); htmlBuilder.AppendLine(" <th class=\"tg-qk49\">Display Name</th>"); htmlBuilder.AppendLine(" <th class=\"tg-qk49\">First Name</th>"); htmlBuilder.AppendLine(" <th class=\"tg-qk49\">Middle Name</th>"); htmlBuilder.AppendLine(" <th class=\"tg-qk49\">Last Name</th>"); htmlBuilder.AppendLine(" <th class=\"tg-qk49\">Phones</th>"); htmlBuilder.AppendLine(" <th class=\"tg-qk49\">Important Dates</th>"); htmlBuilder.AppendLine(" <th class=\"tg-qk49\">Emails</th>"); htmlBuilder.AppendLine(" <th class=\"tg-qk49\">Websites</th>"); htmlBuilder.AppendLine(" <th class=\"tg-qk49\">Job Info</th>"); htmlBuilder.AppendLine(" <th class=\"tg-qk49\">Adresses</th>"); htmlBuilder.AppendLine(" <th class=\"tg-qk49\">Notes</th>"); htmlBuilder.AppendLine(" <th class=\"tg-qk49\">Thumbnail</th>"); htmlBuilder.AppendLine(" </tr>"); foreach (Contact cntct in cntctsList) { if (cntct.Thumbnail != null) { IRandomAccessStream fileStream = await cntct.Thumbnail.OpenReadAsync(); } //Save acquired contact details to a formatted HTML table htmlBuilder.AppendLine(" <tr>"); htmlBuilder.AppendLine(" <td class=\"tg-yw4l\">" + (cntct.DisplayName != null ? cntct.DisplayName : "NULL") + "</td>"); htmlBuilder.AppendLine(" <td class=\"tg-yw4l\">" + (cntct.FirstName != null ? cntct.FirstName : "NULL") + "</td>"); htmlBuilder.AppendLine(" <td class=\"tg-yw4l\">" + (cntct.MiddleName != null ? cntct.MiddleName : "NULL") + "</td>"); htmlBuilder.AppendLine(" <td class=\"tg-yw4l\">" + (cntct.LastName != null ? cntct.LastName : "NULL") + "</td>"); if (cntct.Phones != null) { foreach (ContactPhone item in cntct.Phones) { tempStringBuilder.AppendLine("Kind: " + item.Kind + " Number: " + item.Number); } } htmlBuilder.AppendLine(" <td class=\"tg-yw4l\">" + (tempStringBuilder.ToString() != null ? tempStringBuilder.ToString() : "NULL") + "</td>"); if (cntct.ImportantDates != null) { tempStringBuilder.Clear(); foreach (ContactDate item in cntct.ImportantDates) { tempStringBuilder.AppendLine("Kind: " + item.Kind + " D: " + item.Day + "M: " + item.Month + "Y: " + item.Year + " Description: " + item.Description); } } htmlBuilder.AppendLine(" <td class=\"tg-yw4l\">" + (tempStringBuilder.ToString() != null ? tempStringBuilder.ToString() : "NULL") + "</td>"); if (cntct.Emails != null) { tempStringBuilder.Clear(); foreach (ContactEmail item in cntct.Emails) { tempStringBuilder.AppendLine("Kind: " + item.Kind + " Email: " + item.Address + " Description: " + item.Description); } } htmlBuilder.AppendLine(" <td class=\"tg-yw4l\">" + (tempStringBuilder.ToString() != null ? tempStringBuilder.ToString() : "NULL") + "</td>"); if (cntct.Websites != null) { tempStringBuilder.Clear(); foreach (ContactWebsite item in cntct.Websites) { tempStringBuilder.AppendLine("URL: " + item.Uri.AbsoluteUri.ToString() + " Description: " + item.Description); } } htmlBuilder.AppendLine(" <td class=\"tg-yw4l\">" + (tempStringBuilder.ToString() != null ? tempStringBuilder.ToString() : "NULL") + "</td>"); if (cntct.JobInfo != null) { tempStringBuilder.Clear(); foreach (ContactJobInfo item in cntct.JobInfo) { tempStringBuilder.AppendLine("Title: " + item.Title + " Office" + item.Office + " CompanyName: " + item.CompanyName + " Description: " + item.Description); } } htmlBuilder.AppendLine(" <td class=\"tg-yw4l\">" + (tempStringBuilder.ToString() != null ? tempStringBuilder.ToString() : "NULL") + "</td>"); if (cntct.Addresses != null) { tempStringBuilder.Clear(); foreach (ContactAddress item in cntct.Addresses) { tempStringBuilder.AppendLine("Kind: " + item.Kind + " Locality" + item.Locality + " PostalCode: " + item.PostalCode + " Region: " + item.Region + " StreetAddress: " + item.StreetAddress + " Description: " + item.Description); } } htmlBuilder.AppendLine(" <td class=\"tg-yw4l\">" + (tempStringBuilder.ToString() != null ? tempStringBuilder.ToString() : "NULL") + "</td>"); htmlBuilder.AppendLine(" <td class=\"tg-yw4l\">" + (cntct.Notes != null ? cntct.Notes : "NULL") + "</td>"); try { IRandomAccessStreamWithContentType streamThumb = await cntct.Thumbnail.OpenReadAsync(); if (streamThumb != null && streamThumb.Size > 0) { byte[] buffer = new byte[streamThumb.Size]; IBuffer test = await streamThumb.ReadAsync(buffer.AsBuffer(), (uint)streamThumb.Size, InputStreamOptions.None); var thumbB64 = System.Convert.ToBase64String(test.ToArray()); htmlBuilder.AppendLine(" <td class=\"tg-yw4l\"><a href=\"data: image / jpeg; base64," + thumbB64 + "\" download =\"" + filename + (cntct.FirstName != null ? cntct.FirstName : "NULL") + "_" + (cntct.LastName != null ? cntct.LastName : "NULL") + ".jpg\" ><img src=\"data: image / jpeg; base64," + thumbB64 + "\" height=\"256\" width=\"256\" > </a></td>"); } } catch (Exception) { htmlBuilder.AppendLine(" <td class=\"tg-yw4l\"> N/A </td>"); } //htmlBuilder.AppendLine(" <td class=\"tg-yw4l\">"Thumbnail"</td>"); htmlBuilder.AppendLine(" </tr>"); listLog.Items.Add("Contacts saved: " + cntct.FirstName + " " + cntct.LastName); listLog.SelectedIndex = listLog.Items.Count - 1; } htmlBuilder.AppendLine("</table>"); htmlBuilder.AppendLine("</body> "); htmlBuilder.AppendLine("</html>"); writerHTML.WriteString(htmlBuilder.ToString()); await writerHTML.StoreAsync(); await writerHTML.FlushAsync(); listLog.SelectedIndex = listLog.Items.Count - 1; ShowMessageFinished("Contacts"); } catch (Exception ee) { MessageDialog msgbox = new MessageDialog(ee.Message); await msgbox.ShowAsync(); } }