protected async override void OnNavigatedTo(NavigationEventArgs e) { this.ConPPT.IsEnabled = false; Client = Connect.Client; changlanguage(); Client.SendCommand("data?"); if (e.NavigationMode == NavigationMode.Back && PickFiles.PickedFiles.Count > 0) { StorageFile file = PickFiles.PickedFiles[0]; IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read); Stream stream = WindowsRuntimeStreamExtensions.AsStreamForRead(fileStream.GetInputStreamAt(0)); byte[] bt = ConvertStreamTobyte(stream); Client.SendCommand("FileName|" + file.Name); Thread.Sleep(1000); Client.SendCommand(bt); string[] type = file.Name.Split('.'); if (type[type.Length - 1] == "ppt") { this.ConPPT.IsEnabled = true; } } }
public async Task Load() { var folder = await Package.Current.InstalledLocation.GetFolderAsync("Assets"); var file = await folder.GetFileAsync("ColorTable.xml"); var stream = await file.OpenReadAsync(); using (var stm = WindowsRuntimeStreamExtensions.AsStream(stream)) { XDocument doc = XDocument.Load(stm); foreach (XElement color in doc.Root.Elements()) { string name = (string)color.Attribute("Name"); string colorValue = (string)color.Attribute("Value"); if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(colorValue)) { NamedColor c = ParseColor(colorValue); c.Name = name; map[name] = c; orderedList.Add(c); } } } }
internal ImageSource GetActualImageSource() { if (_imageSource != null) { return(_imageSource); } if (_uriSource != null) { // hdt BitmapImage imageSource = new BitmapImage(); StorageFile.GetFileFromApplicationUriAsync(_uriSource).AsTask().ContinueWith((fr) => { if ((fr.Result != null) && !fr.IsFaulted) { Action <Task <IRandomAccessStreamWithContentType> > func = delegate(Task <IRandomAccessStreamWithContentType> r) { using (Stream stream = WindowsRuntimeStreamExtensions.AsStreamForRead(r.Result)) { // Utility.InitImageSource(imageSource, stream); //导出RptText ImageUri时图片不出问题 李雪修改 InitImageSource(stream); } }; WindowsRuntimeSystemExtensions.AsTask <IRandomAccessStreamWithContentType>(fr.Result.OpenReadAsync()).ContinueWith(func); } }); return(imageSource); } return(null); }
public async void CreateCoverFromStream(Stream coverStream) { IRandomAccessStream src = WindowsRuntimeStreamExtensions.AsRandomAccessStream(coverStream); CoverSrc = new BitmapImage(); await CoverSrc.SetSourceAsync(src); }
public async Task <IRandomAccessStream> StartDownload(Uri uri) { byte[] bytes = null; TriggerDownLoadChanging(new DownLoadChangingEventArgs(DownloadBytesCount, 0, bytes)); cts = new CancellationTokenSource(); DownloadBytesCount = new DownLoadBytes(); var stream = await GetAsyncStreamDownLoad(uri, cts.Token); if (!cts.IsCancellationRequested && stream != null) { using (stream) { var randomAccessStream = new InMemoryRandomAccessStream(); var outputStream = randomAccessStream.GetOutputStreamAt(0); await RandomAccessStream.CopyAsync(stream.AsInputStream(), outputStream); DownloadBytesCount.BytesReceived = Convert.ToInt64(randomAccessStream.Size); var randomAccessStreamTemp = randomAccessStream.CloneStream(); Stream streamTemp = WindowsRuntimeStreamExtensions.AsStreamForRead(randomAccessStreamTemp.GetInputStreamAt(0)); var bytesTemp = ConvertStreamTobyte(streamTemp); TriggerDownLoadChanging(new DownLoadChangingEventArgs(DownloadBytesCount, 100, bytesTemp)); //TriggerDownLoadComplete(new DownLoadCompleteEventArgs(randomAccessStream)); TriggerDownLoadComplete(new DownLoadCompleteEventArgs(randomAccessStream.CloneStream())); return(randomAccessStream as IRandomAccessStream); } } return(null); }
/// <summary> /// 保存远程url地址图片,到本地 /// </summary> /// <param name="uri">远程地址</param> /// <param name="filename">保存的名称</param> /// <param name="folder">保存位置枚举</param> /// <returns></returns> internal async static Task SaveImageFromUrl(string uri, string filename, StorageFolder folder) { var rass = RandomAccessStreamReference.CreateFromUri(new Uri(uri)); IRandomAccessStream inputStream = await rass.OpenReadAsync(); Stream input = WindowsRuntimeStreamExtensions.AsStreamForRead(inputStream.GetInputStreamAt(0)); try { //获取图片扩展名的Guid StorageFile outputFile = await folder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting); using (IRandomAccessStream outputStream = await outputFile.OpenAsync(FileAccessMode.ReadWrite)) { Stream output = WindowsRuntimeStreamExtensions.AsStreamForWrite(outputStream.GetOutputStreamAt(0)); await input.CopyToAsync(output); output.Dispose(); input.Dispose(); } } catch (Exception ex) { throw ex; } }
/// <summary> /// Fixes 3D printing file stream. /// </summary> /// <param name="inputStream">The input file to be fixed as a Stream object.</param> /// <returns>The fixed file as a Stream.</returns> public async Task <Stream> FixAsync(Stream inputStream) { InputStream = inputStream; // 1. LoadModelFromPackageAsync accepts IRandomAccessStream and uses stream cloning internally // 2. WindowsRuntimeStreamExtensions.AsRandomStream converts Stream to IRandomAccessStream, but the resulting stream doesn't support cloning // 3. InMemoryRandomAccessStream does support cloning. So we needed a way to go from Stream to InMemoryRandomAccessStream // 4. Solution: Copy Stream to MemoryStream. Write to InMemoryRandomAccessStream via WriteAsync, which accepts IBuffer // To get IBuffer, we first need to get the memoryStream Bytes with ToArray() and then get IBuffer using the // System.Runtime.InteropServices.WindowsRuntime AsBuffer90 extension method. // We then pass the InMemoryRandomAccessStream object to LoadModelFromPackageAsync. using var memoryStream = new MemoryStream(); await InputStream.CopyToAsync(memoryStream); using InMemoryRandomAccessStream memoryRandomAccessStream = new InMemoryRandomAccessStream(); await memoryRandomAccessStream.WriteAsync(memoryStream.ToArray().AsBuffer()); var package = new Printing3D3MFPackage(); var model = await package.LoadModelFromPackageAsync(memoryRandomAccessStream); await model.RepairAsync(); await package.SaveModelToPackageAsync(model); return(WindowsRuntimeStreamExtensions.AsStream(await package.SaveAsync())); }
public static IEnumerable <string> ReadLines(string path) { if (string.IsNullOrWhiteSpace(path)) { throw new ArgumentException(); } try { IAsyncOperation <IRandomAccessStream> source = FileHelper.GetFileForPathOrURI(path).OpenAsync(FileAccessMode.Read); WindowsRuntimeSystemExtensions.AsTask <IRandomAccessStream>(source).Wait(); using (FileRandomAccessStream randomAccessStream = (FileRandomAccessStream)source.GetResults()) { StreamReader streamReader = new StreamReader(WindowsRuntimeStreamExtensions.AsStreamForRead((IInputStream)randomAccessStream)); List <string> list = new List <string>(); while (true) { string str = streamReader.ReadLine(); if (str != null) { list.Add(str); } else { break; } } return((IEnumerable <string>)list); } } catch (Exception ex) { throw File.GetRethrowException(ex); } }
/// <summary> /// 通过转成byte[]来实现图片储存,但不知道为什么就是不好用,得到得图片颜色配置不正确。 /// 会不会因为方法将所有像素数据视为sRGB 颜色空间中的像素数据? /// </summary> /// <param name="thumbnail"></param> /// <returns></returns> private async Task SaveWizPixelAsync(StorageItemThumbnail thumbnail) { Stream stream = WindowsRuntimeStreamExtensions.AsStreamForRead(thumbnail.GetInputStreamAt(0)); byte[] buffer = new byte[thumbnail.Size]; // byte[] pixelbytes; using (MemoryStream ms = new MemoryStream()) { stream.Read(buffer, 0, buffer.Length); } #region 测试得到的buffer是否完整 结果是使用buffer生成的IrandomAccessTream来为BitmapImage.SetValue()提供参数,显示正常。 //InMemoryRandomAccessStream memoryStream = new InMemoryRandomAccessStream(); //DataWriter datawriter = new DataWriter(memoryStream.GetOutputStreamAt(0)); //datawriter.WriteBytes(buffer); //await datawriter.StoreAsync(); #endregion var file = await ApplicationData.Current.LocalFolder.CreateFileAsync("Testimage.jpg", CreationCollisionOption.GenerateUniqueName); using (var sm = await file.OpenAsync(FileAccessMode.ReadWrite)) { BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, sm); encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied thumbnail.OriginalWidth, thumbnail.OriginalHeight, DisplayInformation.GetForCurrentView().LogicalDpi, DisplayInformation.GetForCurrentView().LogicalDpi, buffer); await encoder.FlushAsync(); } }
/// <summary> /// hdt 新增,提供报表中图表的导出 /// </summary> /// <param name="p_bmp"></param> /// <returns></returns> public static Stream GetBmpStream(RenderTargetBitmap p_bmp) { Task <IBuffer> taskBuf = taskBuf = p_bmp.GetPixelsAsync().AsTask(); taskBuf.Wait(); byte[] data = taskBuf.Result.ToArray(); InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream(); Task <BitmapEncoder> taskEncoder = BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, ms).AsTask(); taskEncoder.Wait(); BitmapEncoder encoder = taskEncoder.Result; float dpi = DisplayInformation.GetForCurrentView().LogicalDpi; encoder.SetPixelData( BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)p_bmp.PixelWidth, (uint)p_bmp.PixelHeight, dpi, dpi, data); encoder.FlushAsync().AsTask().Wait(); return(WindowsRuntimeStreamExtensions.AsStream(ms)); }
public async Task <Stream> Encode() { try { Stopwatch stopwatchEncode = new Stopwatch(); stopwatchEncode.Start(); IRandomAccessStream imageStream = (IRandomAccessStream) new InMemoryRandomAccessStream(); BitmapEncoder bitmapEncoder = await GraffitiEncoder.BuildEncoder(imageStream); BitmapPixelFormat pixelFormat; byte[] imageBinaryData1 = GraffitiEncoder.GetImageBinaryData1(this._bitmap, out pixelFormat); int num1 = (int)pixelFormat; int num2 = 0; int pixelWidth = ((BitmapSource)this._bitmap).PixelWidth; int pixelHeight = ((BitmapSource)this._bitmap).PixelHeight; double dpiX = 72.0; double dpiY = 72.0; byte[] pixels = imageBinaryData1; bitmapEncoder.SetPixelData((BitmapPixelFormat)num1, (BitmapAlphaMode)num2, (uint)pixelWidth, (uint)pixelHeight, dpiX, dpiY, pixels); await WindowsRuntimeSystemExtensions.AsTask(bitmapEncoder.FlushAsync()).ConfigureAwait(false); long size = (long)imageStream.Size; stopwatchEncode.Stop(); Execute.ExecuteOnUIThread((Action)(() => {})); return(WindowsRuntimeStreamExtensions.AsStreamForRead((IInputStream)imageStream)); } catch { return(null); } }
/// <summary> /// IRandomAccessStream转换为bytes /// </summary> /// <param name="randomAccessStream"></param> /// <returns></returns> public static async Task <byte[]> AccessStreamToBytesAsync(IRandomAccessStream randomAccessStream) { Stream stream = WindowsRuntimeStreamExtensions.AsStreamForRead(randomAccessStream.GetInputStreamAt(0)); MemoryStream ms = new MemoryStream(); await stream.CopyToAsync(ms); return(ms.ToArray()); }
protected override async void OnNavigatedTo(NavigationEventArgs e) { var fileToUpload = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Content/template.xlsx")); var fileStream = await fileToUpload.OpenReadAsync(); App.OneDriveService.RequestViewModel.Api.FileStream = WindowsRuntimeStreamExtensions.AsStream(fileStream); }
public static async Task <IBook> GetBookFromFile(Windows.Storage.IStorageFile file) { if (file == null) { return(null); } else if (Path.GetExtension(file.Path).ToLower() == ".pdf") { var book = new Books.Pdf.PdfBook(); try { await book.Load(file); } catch { return(null); } if (book.PageCount <= 0) { return(null); } return(book); } else if (new string[] { ".zip", ".cbz" }.Contains(Path.GetExtension(file.Path).ToLower())) { var book = new Books.Cbz.CbzBook(); try { await book.LoadAsync(WindowsRuntimeStreamExtensions.AsStream(await file.OpenReadAsync())); } catch { return(null); } if (book.PageCount <= 0) { return(null); } return(book); } else if (new string[] { ".rar", ".cbr", ".7z", ".cb7" }.Contains(Path.GetExtension(file.Path).ToLower())) { var book = new Books.Compressed.CompressedBook(); try { await book.LoadAsync(WindowsRuntimeStreamExtensions.AsStream(await file.OpenReadAsync())); } catch { return(null); } if (book.PageCount <= 0) { return(null); } return(book); } return(null); }
/// <summary> /// 网络图片Uri转换成流 /// </summary> /// <param name="uri"></param> /// <returns></returns> internal async static Task <Stream> UriToStream(string uri) { var rass = RandomAccessStreamReference.CreateFromUri(new Uri(uri)); IRandomAccessStream inputStream = await rass.OpenReadAsync(); Stream input = WindowsRuntimeStreamExtensions.AsStreamForRead(inputStream.GetInputStreamAt(0)); return(input); }
/// <summary> /// Convert a stream to an image, and dispose of the stream. /// This must be called on the UI thread! /// When the async is done, it may not do the callback on the UI thread! /// </summary> /// <param name="imageStream"></param> /// <returns></returns> private async Task <Tuple <BitmapImage, PDFPageViewModel> > ConvertToBMI(MemoryStream imageStream, PDFPageViewModel vm) { imageStream.Seek(0, SeekOrigin.Begin); var bm = new BitmapImage(); await bm.SetSourceAsync(WindowsRuntimeStreamExtensions.AsRandomAccessStream(imageStream)); imageStream.Dispose(); return(Tuple.Create(bm, vm)); }
/// <summary> /// Initialize with the page that we should track. /// </summary> /// <param name="pageInfo">A stream of cache tags and the PDF pages associated with it.</param> /// <remarks>We are really only interested in the first PdfPage we get - and we will re-subscribe, but not hold onto it.</remarks> public PDFPageViewModel(IObservable <Tuple <string, IObservable <PdfPage> > > pageInfo, IBlobCache cache = null) { _cache = cache ?? Blobs.LocalStorage; // Render an image when: // - We have at least one render request // - ImageStream is subscribed to // - the file or page updates somehow (new pageInfo iteration). // // Always pull from the cache first, but if that doesn't work, then render and place // in the cache. // Get the size of the thing when it is requested. This sequence must be finished before // any size calculations can be done! var imageSize = from pgInfo in pageInfo from sz in _cache.GetOrFetchPageSize(pgInfo.Item1, () => pgInfo.Item2.Take(1).Select(pdf => pdf.Size.ToIWalkerSize())) select new { PGInfo = pgInfo, Size = sz }; var publishedSize = imageSize .Do(info => _pageSize = info.Size) .Select(info => info.PGInfo) .Publish().RefCount(); _pageSizeLoaded = publishedSize.AsUnit(); // The render request must be "good" - that is well formed. Otherwise // we will just ignore it. This is because sometimes when things are being "sized" the // render request is malformed. RenderImage = ReactiveCommand.Create(); var renderRequest = RenderImage .Cast <Tuple <RenderingDimension, double, double> >() .Where(info => (info.Item1 == RenderingDimension.Horizontal && info.Item2 > 0) || (info.Item1 == RenderingDimension.Vertical && info.Item3 > 0) || (info.Item1 == RenderingDimension.MustFit && info.Item2 > 0 && info.Item3 > 0) ); // Generate an image when we have a render request and a everything else is setup. ImageStream = from requestInfo in Observable.CombineLatest(publishedSize, renderRequest, (pSize, rr) => new { pgInfo = pSize, RenderRequest = rr }) let imageDimensions = CalcRenderingSize(requestInfo.RenderRequest.Item1, requestInfo.RenderRequest.Item2, requestInfo.RenderRequest.Item3) from imageData in _cache.GetOrFetchPageImageData(requestInfo.pgInfo.Item1, imageDimensions.Item1, imageDimensions.Item2, () => requestInfo.pgInfo.Item2.SelectMany(pdfPg => { var ms = new MemoryStream(); var ra = WindowsRuntimeStreamExtensions.AsRandomAccessStream(ms); var opt = new PdfPageRenderOptions() { DestinationWidth = (uint)imageDimensions.Item1, DestinationHeight = (uint)imageDimensions.Item2 }; return(Observable.FromAsync(() => pdfPg.RenderToStreamAsync(ra).AsTask()) .Select(_ => ms.ToArray())); })) select new MemoryStream(imageData); }
private async void VoiceCaptureButton_Click(object sender, RoutedEventArgs e) { string output; //开始录音 if (VoiceRecordSym == true) { _memoryBuffer = new InMemoryRandomAccessStream(); VoiceCaptureButton.FontFamily = new FontFamily("Segoe UI"); VoiceCaptureButton.Content = "停止录音"; VoiceRecordSym = false; if (IsRecording) { throw new InvalidOperationException("Recording already in progress!"); } MediaCaptureInitializationSettings settings = new MediaCaptureInitializationSettings { StreamingCaptureMode = StreamingCaptureMode.Audio }; _mediaCapture = new MediaCapture(); await _mediaCapture.InitializeAsync(settings); //将录音文件存入_memoryBuffer里面 await _mediaCapture.StartRecordToStreamAsync(MediaEncodingProfile.CreateWav(AudioEncodingQuality.Auto), _memoryBuffer); IsRecording = true; } //停止录音 else { await _mediaCapture.StopRecordAsync(); IsRecording = false; VoiceCaptureButton.FontFamily = new FontFamily("Segoe MDL2 Assets"); VoiceCaptureButton.Content = "\xE1D6"; VoiceRecordSym = true; progessRing.IsActive = true; Input.IsReadOnly = true; //转换InMemoryRandomAccessStream成Stream Stream tempStream = WindowsRuntimeStreamExtensions.AsStreamForRead(_memoryBuffer.GetInputStreamAt(0)); using (var stream = new MemoryStream()) { tempStream.CopyTo(stream); VoiceToText voiceToText = new VoiceToText(); //传入VoiceToText函数 output = await voiceToText.ReadVoice(stream, "yue"); } //tempStream.Position = 0; progessRing.IsActive = false; Input.IsReadOnly = false; Input.Text += output; } }
public static async Task <string> GetTestData(string filePath) { var folder = Package.Current.InstalledLocation; var file = await folder.GetFileAsync(filePath); var openFile = await file.OpenReadAsync(); var reader = new StreamReader(WindowsRuntimeStreamExtensions.AsStreamForRead(openFile)); return(await reader.ReadToEndAsync()); }
public async static Task <Microsoft.OneDrive.Item> UploadFile() { var filename = TestHelpers.GetFilename(); Microsoft.OneDrive.Item item; var fileToUpload = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Content/template.xlsx")); using (var fileStream = await fileToUpload.OpenReadAsync()) { item = await App.OneDriveService.UploadFileAsync("", filename, WindowsRuntimeStreamExtensions.AsStream(fileStream)); } return(item); }
internal static Stream OpenFileForReading(StorageFile file) { Task <IRandomAccessStream> task = WindowsRuntimeSystemExtensions.AsTask <IRandomAccessStream>(file.OpenAsync(FileAccessMode.Read)); task.Wait(); if (task.Status != TaskStatus.RanToCompletion) { throw new Exception("Failed to open file!"); } else { return(WindowsRuntimeStreamExtensions.AsStreamForRead((IInputStream)task.Result)); } }
private async void BtnPlay_ClickAsync(object sender, RoutedEventArgs e) { if (!User.IsLogIn()) { await new ContentDialog { Title = "Информация", Content = "Авторизуйтесь в системе для получения возможности прослушивания песен", PrimaryButtonText = "ОК" }.ShowAsync(); return; } _mediaElement.MediaPlayer.Pause(); IRandomAccessStream src = null; await Task.Run(() => { App app = Application.Current as App; try { using (SqlConnection connection = new SqlConnection(app.GetConnectionString())) { connection.Open(); SqlCommand cmd = connection.CreateCommand(); cmd.CommandText = string.Format(DBQueryCollection.QUERY_FOR_MUSIC_SRC, _track.SrcId.ToString()); using (SqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); src = WindowsRuntimeStreamExtensions.AsRandomAccessStream(reader.GetStream(0)); } } } catch (Exception) { ShowErrorDialog(); return; } }); MediaSource mediaSource = MediaSource.CreateFromStream(src, "MPEG"); MediaPlaybackItem mediaPlaybackItem = new MediaPlaybackItem(mediaSource); MediaItemDisplayProperties props = mediaPlaybackItem.GetDisplayProperties(); props.Type = Windows.Media.MediaPlaybackType.Music; props.MusicProperties.Artist = _track.Artist.Name; props.MusicProperties.AlbumTitle = _track.Album.Name; props.MusicProperties.Title = _track.Name; mediaPlaybackItem.ApplyDisplayProperties(props); _mediaElement.MediaPlayer.Source = mediaPlaybackItem; _mediaElement.MediaPlayer.Play(); }
public static async Task <Point> GetPixelWidthAndHeight(this IRandomAccessStream iRandomAccessStream) { var tempIRandomAccessStream = iRandomAccessStream.CloneStream(); Stream inputStream = WindowsRuntimeStreamExtensions.AsStreamForRead(tempIRandomAccessStream.GetInputStreamAt(0)); var copiedBytes = ConvertStreamTobyte(inputStream); Stream tempStream = new MemoryStream(copiedBytes); Guid decoderId = Guid.Empty; ImageType type = ImageTypeCheck.CheckImageType(copiedBytes); switch (type) { case ImageType.GIF: { break; } case ImageType.JPG: { decoderId = BitmapDecoder.JpegDecoderId; break; } case ImageType.PNG: { decoderId = BitmapDecoder.PngDecoderId; break; } default: { break; } } var randomAccessStream = new InMemoryRandomAccessStream(); var outputStream = randomAccessStream.GetOutputStreamAt(0); await RandomAccessStream.CopyAsync(tempStream.AsInputStream(), outputStream); var bitDecoder = await BitmapDecoder.CreateAsync(decoderId, randomAccessStream); var frame = await bitDecoder.GetFrameAsync(0); Point point = new Point(); point.X = frame.PixelWidth; point.Y = frame.PixelHeight; return(point); }
private async void UploadBlob(CloudBlobContainer container, StorageFile file, string fileName, int fileId, long fileSize) { using (var fileStream = await file.OpenStreamForReadAsync()) { // Retrieve reference to a blob CloudBlockBlob blob = container.GetBlockBlobReference(fileName); AzureProgressStream progressStream = new AzureProgressStream(fileStream); progressStream.ProgressChanged += pstream_ProgressChanged; progressStream.SetLength(fileSize); progressStream.FileId = fileId; IInputStream inputStream = WindowsRuntimeStreamExtensions.AsInputStream(progressStream); await blob.UploadFromStreamAsync(inputStream); } }
/** * Extracts image pixels into byte array "pixels" */ protected void GetImagePixels(IRandomAccessStream iRandomAccessStream) { /*Point pointWH = await WriteableBitmapExpansion.GetPixelWidthAndHeight(iRandomAccessStream); * int w = (int)pointWH.X; * int h = (int)pointWH.Y;*/ int count = 0; byte[] tempByte = null; /* * //进行统一尺寸的格式压缩 * if ((w != width) || (h != height) || ) ||{ || var bytes = await WriteableBitmapExpansion.ResizeBytes(iRandomAccessStream, width, height, BitmapInterpolationMode.Cubic); || pixels = new Byte[3 * width * height]; || pointWH = new Point(width, height); || tempByte = bytes; ||} ||else ||{ || pointWH = await WriteableBitmapExpansion.GetPixelWidthAndHeight(imageIAStream); || pixels = new Byte[3 * (int)pointWH.X * (int)pointWH.Y]; || tempByte = await WriteableBitmapExpansion.WriteableBitmapToBytes(imageIAStream); ||} */ pixels = new Byte[3 * (int)width * (int)height]; /*tempByte = await WriteableBitmapExpansion.WriteableBitmapToBytes(imageIAStream);*/ Stream inputStream = WindowsRuntimeStreamExtensions.AsStreamForRead(imageIAStream.GetInputStreamAt(0)); tempByte = inputStream.ConvertStreamTobyte(); for (int th = 0; th < height; th++) { for (int tw = 0; tw < width; tw++) { Color color = WriteableBitmapExpansion.GetPixel(tempByte, Convert.ToInt32(width), tw, th); pixels[count] = color.R; count++; pixels[count] = color.G; count++; pixels[count] = color.B; count++; } } }
/// <summary> /// Gets the image. /// </summary> /// <param name="source">The source</param> /// <returns></returns> internal Image GetImage(ImageSource source) { if (source == null) { return(null); } if (this.imageCaches.ContainsKey(source)) { return(this.imageCaches[source]); } Windows.UI.Xaml.Media.Imaging.BitmapImage image = source as Windows.UI.Xaml.Media.Imaging.BitmapImage; Stream stream = null; try { if ((image != null) && (image.UriSource != null)) { try { Uri uri1 = ((Windows.UI.Xaml.Media.Imaging.BitmapImage)source).UriSource; Uri uri = new Uri("ms-appx:///" + uri1.LocalPath.TrimStart(new char[] { '/' })); stream = WindowsRuntimeStreamExtensions.AsStreamForRead(StorageFile.GetFileFromApplicationUriAsync(uri).GetResultSynchronously <StorageFile>().OpenSequentialReadAsync().GetResultSynchronously <IInputStream>()); } catch (Exception) { stream = Utility.GetImageStream(source, ImageFormat.Png, PictureSerializationMode.Normal); } } else if (image != null) { stream = Utility.GetImageStream(source, ImageFormat.Png, PictureSerializationMode.Normal); } if (stream != null) { byte[] buffer = new byte[stream.Length]; stream.Read(buffer, 0, buffer.Length); Image instance = Image.GetInstance(buffer); this.imageCaches.Add(source, instance); stream.Dispose(); return(instance); } return(null); } catch { return(null); } }
public static IBuffer ToBuffer(this IRandomAccessStream randomStream) { Stream stream = WindowsRuntimeStreamExtensions.AsStreamForRead(randomStream.GetInputStreamAt(0)); var memoryStream = new MemoryStream(); if (stream != null) { byte[] bytes = stream.ToByteArray(); if (bytes != null) { var binaryWriter = new BinaryWriter(memoryStream); binaryWriter.Write(bytes); } } return(WindowsRuntimeBufferExtensions.GetWindowsRuntimeBuffer(memoryStream, 0, (int)memoryStream.Length)); }
//合成数据 private byte[] Combine(IRandomAccessStream iRandomAccessStream) { Stream stream = WindowsRuntimeStreamExtensions.AsStreamForRead(iRandomAccessStream.GetInputStreamAt(0)); byte[] buffer = new byte[16 * 1024]; using (MemoryStream ms = new MemoryStream()) { int read; while ((read = stream.Read(buffer, 0, buffer.Length)) > 0) { ms.Write(buffer, 0, read); } Bytes.AddRange(ms.ToArray()); return(Bytes.ToArray()); } }
/// <summary> /// 检测上一次同步的时间,并于本机同步时间比对 /// </summary> /// <returns>相同返回<c>True</c>,不同返回<c>False</c></returns> public async Task <bool> CheckLastAsync() { if (_appFolder == null) { throw new UnauthorizedAccessException("You need to complete OneDrive authorization before you can upload the image"); } try { var historyFile = await _appFolder.GetFileAsync("LastAsyncTime"); using (var stream = (await historyFile.StorageFilePlatformService.OpenAsync()) as IRandomAccessStream) { Stream st = WindowsRuntimeStreamExtensions.AsStreamForRead(stream); st.Position = 0; StreamReader sr = new StreamReader(st, Encoding.UTF8); string result = sr.ReadToEnd(); result = result.Replace("\0", ""); if (string.IsNullOrEmpty(result)) { return(true); } else { try { int cloudTime = Convert.ToInt32(result); int localTime = Convert.ToInt32(AppTools.GetLocalSetting(AppSettings.SyncTime, "0")); if (cloudTime != localTime) { return(false); } return(true); } catch (Exception) { return(true); } } } } catch (Exception) { await _appFolder.StorageFolderPlatformService.CreateFileAsync("LastAsyncTime", CreationCollisionOption.OpenIfExists); return(true); } }
public RequestBuilder DownloadTo(Windows.Storage.IStorageFile file) { this.success = (headers, result) => { long?length = null; if (headers.AllKeys.Contains("Content-Length")) { length = long.Parse(headers["Content-Length"]); } var handle = file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite).AsTask().Result; ProgressCallbackHelper operation = result.CopyToProgress(WindowsRuntimeStreamExtensions.AsStream(handle), length); operation.Completed += (totalbytes) => { handle.Dispose(); }; }; return(this); }