private static async Task<byte[]> ConvertIRandomAccessStreamByte(IRandomAccessStream stream) { DataReader read = new DataReader(stream.GetInputStreamAt(0)); await read.LoadAsync((uint)stream.Size); byte[] temp = new byte[stream.Size]; read.ReadBytes(temp); return temp; }
/// <summary> /// Returns a byte array with the content of the stream. /// </summary> /// <param name="stream">stream to get bytes for</param> /// <returns>awaitable byte array</returns> public static async Task<byte[]> GetPhotoBits(IRandomAccessStream stream) { Debug.Assert(stream != null, "GetPhotoBits should not be called with a null stream."); var reader = new DataReader(stream.GetInputStreamAt(0)); var bytes = new byte[stream.Size]; await reader.LoadAsync((uint)stream.Size); reader.ReadBytes(bytes); return bytes; }
public static async Task<byte[]> IRandomAccessStreamToByteArr(IRandomAccessStream irStream) { DataReader reader = new Windows.Storage.Streams.DataReader(irStream.GetInputStreamAt(0)); await reader.LoadAsync((uint)irStream.Size); byte[] pixels = new byte[irStream.Size]; reader.ReadBytes(pixels); return pixels; }
private async Task SaveVideo(IRandomAccessStream videoStream) { StorageFile videoFile = await ApplicationData.Current.LocalFolder.CreateFileAsync("MyCam.mp4"); using (DataReader reader = new DataReader(videoStream.GetInputStreamAt(0))) { await reader.LoadAsync((uint)videoStream.Size); byte[] data = new byte[(int)videoStream.Size]; reader.ReadBytes(data); await FileIO.WriteBytesAsync(videoFile, data); } }
internal static byte[] RandomAccessStreamToBytes(IRandomAccessStream randomstream) { Stream stream = randomstream.GetInputStreamAt(0).AsStreamForRead(); var memoryStream = new MemoryStream(); if (stream != null) { return StreamToBytes(stream); } else { return null; } }
//stream to base64 public static async Task<string> streamToString(IRandomAccessStream fileStream) { string Base64String = ""; var reader = new DataReader(fileStream.GetInputStreamAt(0)); await reader.LoadAsync((uint)fileStream.Size); byte[] byteArray = new byte[fileStream.Size]; reader.ReadBytes(byteArray); Base64String = Convert.ToBase64String(byteArray); //string s = ByteToString(byteArray); return Base64String; }
public async Task<byte[]> ImageInitialize(IRandomAccessStream stream) { var size = stream.Size; byte[] bytes = new byte[size]; var reader = new DataReader(stream.GetInputStreamAt(0)); await reader.LoadAsync((uint)size); reader.ReadBytes(bytes); return bytes; }
private async Task Play(IRandomAccessStream buffer) { if (buffer == null) throw new ArgumentNullException("buffer"); var storageFolder = Windows.ApplicationModel.Package.Current.InstalledLocation; if (!string.IsNullOrEmpty(_fileName)) { var oldFile = await storageFolder.GetFileAsync(_fileName); await oldFile.DeleteAsync(); } await Dispatcher.RunAsync( CoreDispatcherPriority.Normal, async () => { var storageFile = await storageFolder.CreateFileAsync(AudioFileName, CreationCollisionOption.GenerateUniqueName); _fileName = storageFile.Name; using (var fileStream = await storageFile.OpenAsync(FileAccessMode.ReadWrite)) { await RandomAccessStream.CopyAndCloseAsync( buffer.GetInputStreamAt(0), fileStream.GetOutputStreamAt(0)); await buffer.FlushAsync(); buffer.Dispose(); } var stream = await storageFile.OpenAsync(FileAccessMode.Read); playBack.SetSource(stream, storageFile.FileType); playBack.Play(); }); }
private async Task CalculateHash( IDispatcher d, HashProgress notifier) { if (notifier != null) { Action action = () => notifier(Path, 0); if (d == null) { action(); } else { d.Execute(action); } } //TODO - exception handling StorageFile file = await GetFromRoot(m_path, m_root); int num_chunks = (int)(GetSize() / Chunker.chunk_size) + 1; int hash_size = num_chunks * 32; float current_chunk = 0; var hash_builder = new StringBuilder(hash_size); m_hash = ""; var chunker = new Chunker(GetSize()); foreach (Chunk chunk in chunker.GetChunks()) { using (IRandomAccessStream inputStream = await file.OpenAsync(FileAccessMode.Read)) { using (var dataReader = new DataReader(inputStream.GetInputStreamAt(chunk.Start))) { await dataReader.LoadAsync(chunk.Length); IBuffer buf = dataReader.ReadBuffer(chunk.Length); IBuffer hashed = m_alg.HashData(buf); hash_builder.Append(CryptographicBuffer.EncodeToHexString(hashed)); } } current_chunk++; if (notifier != null) { float percent_done = current_chunk / num_chunks; Action action = () => notifier(Path, percent_done * 100); if (d == null) { action(); } else { d.Execute(action); } } } m_hash = hash_builder.ToString(); if (hash_size > 32) //hash the hash { // Convert the string to UTF8 binary data. IBuffer hashbuf = CryptographicBuffer.ConvertStringToBinary(m_hash, BinaryStringEncoding.Utf8); IBuffer hashed = m_alg.HashData(hashbuf); m_hash = CryptographicBuffer.EncodeToHexString(hashed); } if (notifier != null) { Action action = () => notifier(Path, 100); if (d == null) { action(); } else { d.Execute(action); } } }
public async Task<ImagePackage> InitializeAsync(CoreDispatcher dispatcher, Image image, Uri uriSource, IRandomAccessStream streamSource, CancellationTokenSource cancellationTokenSource) { var bitmapDecoder = ImagingCache.Get<BitmapDecoder>(uriSource); if (bitmapDecoder == null) { var inMemoryStream = new InMemoryRandomAccessStream(); var copyAction = RandomAccessStream.CopyAndCloseAsync( streamSource.GetInputStreamAt(0L), inMemoryStream.GetOutputStreamAt(0L)); await copyAction.AsTask(cancellationTokenSource.Token); bitmapDecoder = await BitmapDecoder.CreateAsync(BitmapDecoder.GifDecoderId, inMemoryStream); ImagingCache.Add(uriSource, bitmapDecoder); } var imageProperties = await RetrieveImagePropertiesAsync(bitmapDecoder); var frameProperties = new List<FrameProperties>(); for (var i = 0u; i < bitmapDecoder.FrameCount; i++) { var bitmapFrame = await bitmapDecoder.GetFrameAsync(i).AsTask(cancellationTokenSource.Token).ConfigureAwait(false); ; frameProperties.Add(await RetrieveFramePropertiesAsync(i, bitmapFrame)); } _frameProperties = frameProperties; _bitmapDecoder = bitmapDecoder; _imageProperties = imageProperties; _dispatcher = dispatcher; await _dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { CreateCanvasResources(); var uri = image.Tag as Uri; if (uri == uriSource) { image.Source = _canvasImageSource; } }); _isInitialized = true; return new ImagePackage(this, _canvasImageSource, _imageProperties.PixelWidth, _imageProperties.PixelHeight); ; }
/// <summary> /// Convert ImageObject to Byte Array /// </summary> /// <param name="fileStream">IRandomAccessStream</param> /// <returns>Byte Array</returns> public static async Task<byte[]> ConvertImagetoByte(IRandomAccessStream fileStream) { var reader = new DataReader(fileStream.GetInputStreamAt(0)); await reader.LoadAsync((uint)fileStream.Size); byte[] pixels = new byte[fileStream.Size]; reader.ReadBytes(pixels); return pixels; }
public static async Task <WriteableBitmap> Resize(this WriteableBitmap source, IRandomAccessStream iRandomAccessStream, int width, int height, BitmapInterpolationMode bitmapInterpolationMode = BitmapInterpolationMode.NearestNeighbor) { Stream inputStream = WindowsRuntimeStreamExtensions.AsStreamForRead(iRandomAccessStream.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); var pixels = await frame.GetPixelDataAsync( frame.BitmapPixelFormat, frame.BitmapAlphaMode, new BitmapTransform() { ScaledHeight = Convert.ToUInt32(height), ScaledWidth = Convert.ToUInt32(width), InterpolationMode = bitmapInterpolationMode, }, ExifOrientationMode.RespectExifOrientation, ColorManagementMode.ColorManageToSRgb); var bytes = pixels.DetachPixelData(); var target = new WriteableBitmap(width, height); var outputStreamWB = target.PixelBuffer.AsStream(); outputStreamWB.Seek(0, SeekOrigin.Begin); outputStreamWB.Write(bytes, 0, bytes.Length); target.Invalidate(); return(target); }
private async Task GetUrlsFromPDF(IRandomAccessStream stream) { using (var dataReader = new DataReader(stream.GetInputStreamAt(0))) { uint u = await dataReader.LoadAsync((uint)stream.Size); IBuffer buffer = dataReader.ReadBuffer(u); GetPDFLinks(buffer); TimeSpan t = new TimeSpan(0, 0, 1); await Task.Delay(t); } }
public IInputStream GetInputStreamAt(ulong position) => _stream.GetInputStreamAt(position);
private IBuffer RandomAccessStreamToBuffer(IRandomAccessStream randomstream) { Stream stream = WindowsRuntimeStreamExtensions.AsStreamForRead(randomstream.GetInputStreamAt(0)); MemoryStream memoryStream = new MemoryStream(); if (stream != null) { byte[] bytes = ConvertStreamTobyte(stream); if (bytes != null) { var binaryWriter = new BinaryWriter(memoryStream); binaryWriter.Write(bytes); } } IBuffer buffer = WindowsRuntimeBufferExtensions.GetWindowsRuntimeBuffer(memoryStream, 0, (int)memoryStream.Length); return buffer; }
private async void CalculateLights() { try { //Debug.WriteLine("Calculating"); //Calculate how many bytes of sound were captured since we last processed. _currentSize = _stream.Size - _currentSize; _position = _stream.Size - BYTES_TO_READ; // This is where the byteArray to be stored. var buffer = new byte[BYTES_TO_READ]; //Debug.WriteLine("Creating data reader."); //await _stream.ReadAsync(buffer.AsBuffer(), (uint)buffer.Length, InputStreamOptions.None); DataReader reader = new DataReader(_stream.GetInputStreamAt(_position)); //Debug.WriteLine("Loading data reader."); await reader.LoadAsync((uint)buffer.Length); //Debug.WriteLine("reading bytes."); reader.ReadBytes(buffer); //List<byte> bytes = new List<byte>(); _position += _currentSize; float max = 0; // interpret as 16 bit audio for (int index = 0; index < buffer.Length; index += 2) { //Debug.WriteLine("Shifting bytes"); short sample = (short)((buffer[index + 1] << 8) | buffer[index + 0]); //Debug.WriteLine("Converting to floating point."); var sample32 = sample / 32768f; // to floating point if (sample32 < 0) { sample32 = -sample32; // absolute value } if (sample32 > max) { max = sample32; // is this the max value? } } //Debug.WriteLine("Determining max"); // calculate what fraction this peak is of previous peaks if (max > audioValueMax) { audioValueMax = (double)max; } audioValueLast = max; //Debug.WriteLine("Figuring out pct"); double pct = audioValueLast / audioValueMax * 100; lblMeasure.Text = pct + ""; pct = pct % 10; _client.Publish("/lights", System.Text.Encoding.UTF8.GetBytes(pct + ""), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, false); } catch (Exception ex) { UpdateStatus(ex.Message); } }
public static async Task <Photo> ResizeJpeg(IRandomAccessStream chosenPhoto, uint size, string originalFileName, string localFileName, double?quality = null) { Photo photo = null; var orientedPixelHeight = 0u; var orientedPixelWidth = 0u; //using (var sourceStream = chosenPhoto) { var decoder = await BitmapDecoder.CreateAsync(chosenPhoto); if (decoder.DecoderInformation != null) { var maxDimension = Math.Max(decoder.PixelWidth, decoder.PixelHeight); var scale = (double)size / maxDimension; if (scale < 1.0) { var orientedScaledHeight = (uint)(decoder.OrientedPixelHeight * scale); var orientedScaledWidth = (uint)(decoder.OrientedPixelWidth * scale); var scaledHeight = (uint)(decoder.PixelHeight * scale); var scaledWidth = (uint)(decoder.PixelWidth * scale); var transform = new BitmapTransform { ScaledHeight = scaledHeight, ScaledWidth = scaledWidth, InterpolationMode = BitmapInterpolationMode.Fant }; var pixelData = await decoder.GetPixelDataAsync( decoder.BitmapPixelFormat, decoder.BitmapAlphaMode, transform, ExifOrientationMode.RespectExifOrientation, ColorManagementMode.DoNotColorManage); using (var destinationStream = new InMemoryRandomAccessStream()) { var propertySet = new BitmapPropertySet(); if (quality.HasValue && quality > 0.0 && quality <= 1.0) { var qualityValue = new BitmapTypedValue(quality, Windows.Foundation.PropertyType.Single); propertySet.Add("ImageQuality", qualityValue); } var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, destinationStream, propertySet); encoder.SetPixelData(decoder.BitmapPixelFormat, BitmapAlphaMode.Premultiplied, orientedScaledWidth, orientedScaledHeight, decoder.DpiX, decoder.DpiY, pixelData.DetachPixelData()); await encoder.FlushAsync(); var reader = new DataReader(destinationStream.GetInputStreamAt(0)); var bytes = new byte[destinationStream.Size]; await reader.LoadAsync((uint)destinationStream.Size); reader.ReadBytes(bytes); photo = new Photo { Bytes = bytes, Width = (int)orientedScaledWidth, Height = (int)orientedScaledHeight, FileName = originalFileName }; if (!string.IsNullOrEmpty(localFileName)) { photo.File = await SaveToLocalFolderAsync(destinationStream.AsStream(), localFileName); } } } orientedPixelHeight = decoder.OrientedPixelHeight; orientedPixelWidth = decoder.OrientedPixelWidth; } } if (photo == null) { var reader = new DataReader(chosenPhoto.GetInputStreamAt(0)); var bytes = new byte[chosenPhoto.Size]; await reader.LoadAsync((uint)chosenPhoto.Size); reader.ReadBytes(bytes); photo = new Photo { Bytes = bytes, Width = (int)orientedPixelWidth, Height = (int)orientedPixelHeight, FileName = originalFileName }; if (!string.IsNullOrEmpty(localFileName)) { photo.File = await SaveToLocalFolderAsync(chosenPhoto.AsStream(), localFileName); } } chosenPhoto.Dispose(); return(photo); }
public async Task<ImageSource> InitializeAsync(CoreDispatcher dispatcher, IRandomAccessStream streamSource, CancellationTokenSource cancellationTokenSource) { var inMemoryStream = new InMemoryRandomAccessStream(); var copyAction = RandomAccessStream.CopyAndCloseAsync( streamSource.GetInputStreamAt(0L), inMemoryStream.GetOutputStreamAt(0L)); await copyAction.AsTask(cancellationTokenSource.Token); var bitmapDecoder = await BitmapDecoder. CreateAsync(BitmapDecoder.GifDecoderId, inMemoryStream).AsTask(cancellationTokenSource.Token).ConfigureAwait(false); var imageProperties = await RetrieveImagePropertiesAsync(bitmapDecoder); var frameProperties = new List<FrameProperties>(); for (var i = 0u; i < bitmapDecoder.FrameCount; i++) { var bitmapFrame = await bitmapDecoder.GetFrameAsync(i).AsTask(cancellationTokenSource.Token).ConfigureAwait(false); ; frameProperties.Add(await RetrieveFramePropertiesAsync(i, bitmapFrame)); } _frameProperties = frameProperties; _bitmapDecoder = bitmapDecoder; _imageProperties = imageProperties; _dispatcher = dispatcher; await _dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { CreateCanvasResources(); }); _isInitialized = true; return _canvasImageSource; }
private async void SetLogFile(object sender, RoutedEventArgs e) { progress.Visibility = Visibility.Visible; App.DisableSelection = true; App.SgstBox.IsEnabled = false; FileOpenPicker open = new FileOpenPicker(); open.FileTypeFilter.Add(".elog"); StorageFile file = await open.PickSingleFileAsync(); if (file != null) { string text; if (add.IsChecked.Value) { text = App.Eng ? "Irrevocable operation. New records will be added to the current log." : "Необратимая операция. Новые записи будут добавлены в текущий журнал."; } else { text = App.Eng ? "Irrevocable operation. Current log will be erased." : "Необратимая операция. Текущий журнал будет удален."; } MessageDialog dialog = new MessageDialog(text); string proceed, cancel; if (App.Eng) { proceed = "Proceed"; cancel = "Cancel"; } else { proceed = "Продолжить"; cancel = "Отмена"; } bool consent = false; dialog.Commands.Add(new UICommand(proceed, x => consent = true)); dialog.Commands.Add(new UICommand(cancel)); await dialog.ShowAsync(); if (!consent) { App.DisableSelection = false; App.SgstBox.IsEnabled = true; progress.Visibility = Visibility.Collapsed; return; } file = await file.CopyAsync(ApplicationData.Current.TemporaryFolder, "events.elog", NameCollisionOption.ReplaceExisting); using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite)) { using (DataReader reader = new DataReader(stream.GetInputStreamAt(0))) { await reader.LoadAsync((uint)code.Length); byte[] coded = new byte[code.Length]; for (int i = 0; i < coded.Length; i++) { coded[i] = (byte)(reader.ReadByte() ^ code[i]); } using (DataWriter writer = new DataWriter(stream.GetOutputStreamAt(0))) writer.WriteBytes(coded); } } StorageFolder folder = await ApplicationData.Current.TemporaryFolder.CreateFolderAsync("temp", CreationCollisionOption.ReplaceExisting); try { await Task.Run(() => ZipFile.ExtractToDirectory(file.Path, folder.Path)); } catch { await(new MessageDialog("Wrong file format!")).ShowAsync(); await file.DeleteAsync(); await folder.DeleteAsync(); App.DisableSelection = false; App.SgstBox.IsEnabled = true; progress.Visibility = Visibility.Collapsed; return; } await file.DeleteAsync(); if (add.IsChecked.Value) { XmlDocument doc = await XmlDocument.LoadFromFileAsync(await folder.GetFileAsync("data.xml")); IXmlNode root = doc.FirstChild; StorageFolder Icons = await folder.TryGetItemAsync("Icons") as StorageFolder; StorageFolder Videos = await folder.TryGetItemAsync("Videos") as StorageFolder; StorageFolder Audios = await folder.TryGetItemAsync("Audios") as StorageFolder; StorageFolder Inks = await folder.TryGetItemAsync("Inks") as StorageFolder; StorageFolder locIcons = await ApplicationData.Current.LocalFolder.CreateFolderAsync("Icons", CreationCollisionOption.OpenIfExists); StorageFolder locVideos = await ApplicationData.Current.LocalFolder.CreateFolderAsync("Videos", CreationCollisionOption.OpenIfExists); StorageFolder locAudios = await ApplicationData.Current.LocalFolder.CreateFolderAsync("Audios", CreationCollisionOption.OpenIfExists); StorageFolder locInks = await ApplicationData.Current.LocalFolder.CreateFolderAsync("Inks", CreationCollisionOption.OpenIfExists); foreach (IXmlNode evntNode in root.ChildNodes) { Event evnt = new Event(evntNode); if (evnt.IsPast && !evnt.Keep) { continue; } if (App.Storage.Exist(evnt.Guid)) { continue; } if (evnt.IconPath.AbsoluteUri != "ms-appx:///Assets/item.png") { StorageFile iconFile = await Icons.GetFileAsync(Path.GetFileName(evnt.IconPath.AbsolutePath)); await iconFile.CopyAsync(locIcons); } switch (evnt.MediaMessageType) { case MediaMessageType.Video: StorageFile videoFile = await Videos.GetFileAsync(Path.GetFileName(evnt.MediaMessageUri.AbsolutePath)); await videoFile.CopyAsync(locVideos); break; case MediaMessageType.Voice: StorageFile audioFile = await Audios.GetFileAsync(Path.GetFileName(evnt.MediaMessageUri.AbsolutePath)); await audioFile.CopyAsync(locAudios); break; } if (evnt.HasStroke) { await(await Inks.GetFileAsync(evnt.Guid.ToString() + ".gif")).CopyAsync(locInks); } if (!evnt.IsPast && evnt.Alarm != null) { var xml = App.FormNotification(evnt.Name, evnt.Message, evnt.IconPath.AbsoluteUri, evnt.Guid.ToString()); ScheduledToastNotification notification = new ScheduledToastNotification(xml, evnt.Alarm.Value); _notifier.AddToSchedule(notification); } await evnt.SaveToFileAsync(); App.Storage.AddEvent(evnt); } } else { foreach (var item in await ApplicationData.Current.LocalFolder.GetItemsAsync()) { await item.DeleteAsync(); } var notifs = _notifier.GetScheduledToastNotifications(); foreach (var notif in notifs) { _notifier.RemoveFromSchedule(notif); } foreach (var item in await folder.GetItemsAsync()) { if (item.IsOfType(StorageItemTypes.File)) { await((StorageFile)item).MoveAsync(ApplicationData.Current.LocalFolder); } else if (item.IsOfType(StorageItemTypes.Folder)) { StorageFolder fld = (StorageFolder)item; StorageFolder locfld = await ApplicationData.Current.LocalFolder.CreateFolderAsync(fld.DisplayName); foreach (var itm in await fld.GetFilesAsync()) { await itm.MoveAsync(locfld); } } } App.Storage = await EventStorage.DeserializeAsync(); foreach (var year in App.Storage.CallendarActive) { foreach (var mnth in year.Months) { foreach (var evnt in mnth.Events) { if (evnt.Alarm != null) { var xml = App.FormNotification(evnt.Name, evnt.Message, evnt.IconPath.AbsoluteUri, evnt.Guid.ToString()); ScheduledToastNotification notification = new ScheduledToastNotification(xml, evnt.Alarm.Value); _notifier.AddToSchedule(notification); } } } } } await folder.DeleteAsync(); } App.DisableSelection = false; App.SgstBox.IsEnabled = true; progress.Visibility = Visibility.Collapsed; }
/// <summary> /// Async loading image stream from cache or network /// </summary> /// <param name="imageUri">Uri of the image to load</param> /// <returns>Stream of the image if load was successfull, null otherwise</returns> public virtual async Task <IRandomAccessStream> LoadImageStream(Uri imageUri, CancellationTokenSource cancellationTokenSource) { CheckConfig(); if (imageUri == null) { return(null); } var imageUrl = imageUri.AbsoluteUri; //有Cache情况,先加载Cache if (_ImageConfig.CacheMode != CacheMode.NoCache) { //加载Cache var resultFromCache = await this.LoadImageStreamFromCache(imageUri); if (resultFromCache != null) { SaveStream(resultFromCache, Regex.Replace(imageUri.LocalPath, @".+?/", "")); return(resultFromCache); } } try { ImageLog.Log("[network] loading " + imageUrl); IRandomAccessStream randStream = null; //如果有自定义UriParser,使用自定义,反之使用默认方式. if (_ImageConfig.UriParser != null) { randStream = await _ImageConfig. UriParser.GetStreamFromUri(imageUri, cancellationTokenSource.Token); } else { randStream = await imageUri.GetStreamFromUri(cancellationTokenSource.Token); } if (randStream == null) { ImageLog.Log("[error] failed to download: " + imageUrl); return(null); } var inMemoryStream = new InMemoryRandomAccessStream(); using (randStream) { var copyAction = RandomAccessStream.CopyAndCloseAsync( randStream.GetInputStreamAt(0L), inMemoryStream.GetOutputStreamAt(0L)); await copyAction.AsTask(cancellationTokenSource.Token); } randStream = inMemoryStream; ImageLog.Log("[network] loaded " + imageUrl); if (_ImageConfig.CacheMode != CacheMode.NoCache) { if (_ImageConfig.CacheMode == CacheMode.MemoryAndStorageCache || _ImageConfig.CacheMode == CacheMode.OnlyMemoryCache) { if (randStream != null) { _ImageConfig.MemoryCacheImpl.Put(imageUrl, randStream); } } if (_ImageConfig.CacheMode == CacheMode.MemoryAndStorageCache || _ImageConfig.CacheMode == CacheMode.OnlyStorageCache) { //是http or https 才加入本地缓存 if (imageUri.IsWebScheme()) { await Task.Factory.StartNew(() => { ImageLog.Log(string.Format("{0} in task t-{1}", imageUri, Task.CurrentId)); // Async saving to the storage cache without await var saveAsync = _ImageConfig.StorageCacheImpl.SaveAsync(imageUrl, randStream) .ContinueWith(task => { ImageLog.Log(string.Format("{0} in task t1-{1}", imageUri, Task.CurrentId)); if (task.IsFaulted || !task.Result) { ImageLog.Log("[error] failed to save in storage: " + imageUri); } } ); }, default(CancellationToken), TaskCreationOptions.AttachedToParent, this._sequentialScheduler); } } } SaveStream(randStream, Regex.Replace(imageUri.LocalPath, @".+?/", "")); return(randStream); } catch (Exception) { ImageLog.Log("[error] failed to save loaded image: " + imageUrl); } //var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)); // May be another thread has saved image to the cache // It is real working case if (_ImageConfig.CacheMode != CacheMode.NoCache) { var resultFromCache = await this.LoadImageStreamFromCache(imageUri); if (resultFromCache != null) { SaveStream(resultFromCache, Regex.Replace(imageUri.LocalPath, @".+?/", "")); return(resultFromCache); } } ImageLog.Log("[error] failed to load image stream from cache and network: " + imageUrl); return(null); }
/// <summary> /// 通过传入数据流来显示GIF呈现 /// </summary> /// <param name="iRandomAccessStream">传入一个图片的数据流</param> public async Task SetSourceAsync(IRandomAccessStream iRandomAccessStream) { if (this.ImageDownLoadProgress != null) { this.ImageDownLoadProgress(0); } if (this.IsAnimation) { this.imageGifGrid.Opacity = 0; CreateAnimationBegin(); } else { this.imageGifGrid.Opacity = 1.0; } if (this.ImageDownLoadProgress != null) { for (int i = 0; i <= 7; i++) { this.ImageDownLoadProgress(i * 10); await Task.Delay(TimeSpan.FromMilliseconds(50)); } } var randomAccessStream = new InMemoryRandomAccessStream(); try { Stream tempStream = iRandomAccessStream.GetInputStreamAt(0).AsStreamForRead(); //为了能判断文件头做了一个流拷贝,保存了一份字节数组 MemoryStream ms = new MemoryStream(); await tempStream.CopyToAsync(ms); bytes = ms.ToArray(); tempStream = new MemoryStream(bytes); // var outputStream = randomAccessStream.GetOutputStreamAt(0); await RandomAccessStream.CopyAsync(tempStream.AsInputStream(), outputStream); //判断并设置图片类型 ImageType type = ImageTypeCheck.CheckImageType(bytes); if (this.ImageDownLoadProgress != null) { this.ImageDownLoadProgress(80); await Task.Delay(TimeSpan.FromMilliseconds(100)); } switch (type) { case ImageType.GIF: { viewBox.Stretch = this.Stretch; await CreateGifBitFrame(randomAccessStream); PlayGif(); break; } case ImageType.JPG: { viewBox.Stretch = Windows.UI.Xaml.Media.Stretch.None; JpegAndPng(randomAccessStream); break; } case ImageType.PNG: { viewBox.Stretch = Windows.UI.Xaml.Media.Stretch.None; JpegAndPng(randomAccessStream); break; } default: { break; } } } catch { var ss = this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { BitmapImage bi = new BitmapImage(); bi.DownloadProgress -= bi_DownloadProgress; bi.DownloadProgress += bi_DownloadProgress; bi.ImageOpened -= bi_ImageOpened; bi.ImageOpened += bi_ImageOpened; bi.ImageFailed -= bi_ImageFailed; bi.ImageFailed += bi_ImageFailed; randomAccessStream.Seek(0); randomAccessStream.FlushAsync(); //await bi.SetSourceAsync(randomAccessStream); bi.SetSource(randomAccessStream); this.imageGifGrid.Children.Clear(); //优化 this.imageList.Clear(); this.bitmapImageList.Clear(); this.bitFrame.Clear(); viewBox.Stretch = Windows.UI.Xaml.Media.Stretch.None; Image imageGif = new Image(); imageGif.Source = null; imageGif.Stretch = this.Stretch; imageGif.HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Stretch; imageGif.VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Stretch; if (!double.IsNaN(this.width) && this.width != 0.0) { imageGif.Width = this.width; } if (!double.IsNaN(this.height) && this.height != 0.0) { imageGif.Height = this.height; } imageGif.Source = bi; this.imageGifGrid.Children.Add(imageGif); }); this.Stop = catchStop; } }
/* * private int checkAS7000HRM() * { * _AS700HRM = new Class1(); * * int i = 99; * i = _AS700HRM.AS7000_Init(); * Debug.WriteLine("Return 995 "); * //if (i==1) Debug.WriteLine("Return 1 "); * //else Debug.WriteLine("Return 0 "); * Debug.WriteLine("Return "+i); * return 0; * * } */ public async void readResultFile(string TestCase) { Debug.WriteLine("readResultFileStart!"); string testItem = TestCase; Debug.WriteLine("TestCase" + TestCase); switch (TestCase) { case "TestVibrator": testItem += ".txt"; break; case "TestAccelerometer": testItem += ".txt"; break; case "TestGyrometer": testItem += ".txt"; break; case "TestAS7000HRM": testItem += ".txt"; break; } StorageFolder storageFolder; StorageFile sampleFile; if (testItem == "TestHeartRate.txt") { storageFolder = KnownFolders.DocumentsLibrary; var Documentfile = await storageFolder.TryGetItemAsync(testItem); if (Documentfile == null) { return; } else { sampleFile = await storageFolder.GetFileAsync(testItem); } } else { var file = await KnownFolders.VideosLibrary.TryGetItemAsync(testItem); if (file != null) { storageFolder = KnownFolders.VideosLibrary; sampleFile = await storageFolder.GetFileAsync(testItem); } else { return; } } Debug.WriteLine("StartTCPSend:" + testItem + "\n"); if (sampleFile != null) { using (IRandomAccessStream stream = await sampleFile.OpenReadAsync()) { using (DataReader reader = new DataReader(stream.GetInputStreamAt(0UL))) { uint len = (uint)stream.Size; // 載入資料 await reader.LoadAsync(len); buffer = reader.ReadBuffer(len); // 暫存在Tag屬性中,稍後用到 //this.Tag = buffer; } } } //buffer = this.Tag as IBuffer; sendFileTCP(buffer, testItem); }
public IInputStream GetInputStreamAt(ulong position) { return(stream.GetInputStreamAt(position)); }
public static async Task <Photo> ResizeJpeg(IRandomAccessStream stream, uint size, string originalFileName) { Photo photo; using (var sourceStream = stream) { var decoder = await BitmapDecoder.CreateAsync(sourceStream); if (decoder.DecoderInformation != null && decoder.DecoderInformation.CodecId == BitmapDecoder.JpegDecoderId) { var maxDimension = Math.Max(decoder.PixelWidth, decoder.PixelHeight); var scale = (double)size / maxDimension; var orientedScaledHeight = (uint)(decoder.OrientedPixelHeight * scale); var orientedScaledWidth = (uint)(decoder.OrientedPixelWidth * scale); var scaledHeight = (uint)(decoder.PixelHeight * scale); var scaledWidth = (uint)(decoder.PixelWidth * scale); var transform = new BitmapTransform { ScaledHeight = scaledHeight, ScaledWidth = scaledWidth, InterpolationMode = BitmapInterpolationMode.Fant }; var pixelData = await decoder.GetPixelDataAsync( decoder.BitmapPixelFormat, decoder.BitmapAlphaMode, transform, ExifOrientationMode.RespectExifOrientation, ColorManagementMode.DoNotColorManage); using (var destinationStream = new InMemoryRandomAccessStream()) { var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, destinationStream); encoder.SetPixelData(decoder.BitmapPixelFormat, decoder.BitmapAlphaMode, orientedScaledWidth, orientedScaledHeight, decoder.DpiX, decoder.DpiY, pixelData.DetachPixelData()); await encoder.FlushAsync(); var reader = new DataReader(destinationStream.GetInputStreamAt(0)); var bytes = new byte[destinationStream.Size]; await reader.LoadAsync((uint)destinationStream.Size); reader.ReadBytes(bytes); photo = new Photo { Bytes = bytes, Width = (int)orientedScaledWidth, Height = (int)orientedScaledHeight, FileName = originalFileName }; } } else { var reader = new DataReader(stream.GetInputStreamAt(0)); var bytes = new byte[stream.Size]; await reader.LoadAsync((uint)stream.Size); reader.ReadBytes(bytes); photo = new Photo { Bytes = bytes, Width = (int)decoder.OrientedPixelWidth, Height = (int)decoder.OrientedPixelHeight, FileName = originalFileName }; } } return(photo); }
/// Open coloring page with coloring image and, if applicable, ink. protected override async void OnNavigatedTo(NavigationEventArgs e) { // NavigationEvent parameter is the source of the coloring page, either a blank coloring image or a previously inked coloring page. String parameter = e.Parameter.ToString(); // If navigating from ContinueColoring, the image is a previously inked coloring page. if (parameter.EndsWith(Constants.inkedImageFile)) { // Get folder in local storage containing ink file and coloring image source. string folderpath = parameter.Substring(0, parameter.IndexOf(Constants.inkedImageFile)); _Foldername = folderpath.Substring(parameter.IndexOf(Constants.inkImageFolder)); try { StorageFolder folder = await ApplicationData.Current.LocalFolder.GetFolderAsync(_Foldername); // Get coloring image source. StorageFile imgsrcFile = await folder.GetFileAsync(Constants.imgsrcFile); _Imgsrc = await FileIO.ReadTextAsync(imgsrcFile); // Load ink. StorageFile inkFile = await folder.GetFileAsync(Constants.inkFile); if (inkFile != null) { IRandomAccessStream stream = await inkFile.OpenAsync(Windows.Storage.FileAccessMode.Read); using (var inputStream = stream.GetInputStreamAt(0)) { await myInkCanvas.InkPresenter.StrokeContainer.LoadAsync(stream); } stream.Dispose(); } } catch (Exception ex) { Debug.WriteLine(ex); } } // If navigating from PickColoringPage, the image is a blank coloring image. else { Uri abspath = new Uri($"{Windows.ApplicationModel.Package.Current.InstalledLocation.Path}\\Images"); Uri relpath = abspath.MakeRelativeUri(new Uri(parameter)); _Imgsrc = relpath.ToString(); } // Set up printing. _PrintHelper = new PhotosPrintHelper(this); _PrintHelper.RegisterForPrinting(); // Adjust ScrollViewer size to Window. var bounds = Window.Current.Bounds; myScrollViewer.Height = bounds.Height - myCommandBar.Height; myScrollViewer.Width = bounds.Width; myImage.Source = new BitmapImage(new Uri("ms-appx:///" + _Imgsrc)); }
public static async Task<StorageFile> StoreToFolderAsync(string fullName, StorageFolder folder, IRandomAccessStream inputStream, CancellationToken cancelToken = default(CancellationToken)) { if (fullName == "") return null; var file = await folder.CreateFileAsync(fullName, CreationCollisionOption.ReplaceExisting); using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite)) { await RandomAccessStream.CopyAndCloseAsync(inputStream.GetInputStreamAt(0), stream.GetOutputStreamAt(0)).AsTask(cancelToken); } return file; }
public static Stream ConvertIRandomAccessStreamToStream(this IRandomAccessStream randomStream) { Stream stream = WindowsRuntimeStreamExtensions.AsStreamForRead(randomStream.GetInputStreamAt(0)); return(stream); }
public static async Task<IRandomAccessStream> ProtectPDFStream(IRandomAccessStream source) { // Create a DataProtectionProvider object for the specified descriptor. DataProtectionProvider Provider = new DataProtectionProvider("LOCAL=user"); InMemoryRandomAccessStream protectedData = new InMemoryRandomAccessStream(); IOutputStream dest = protectedData.GetOutputStreamAt(0); await Provider.ProtectStreamAsync(source.GetInputStreamAt(0), dest); await dest.FlushAsync(); //Verify that the protected data does not match the original //DataReader reader1 = new DataReader(source.GetInputStreamAt(0)); //DataReader reader2 = new DataReader(protectedData.GetInputStreamAt(0)); //var size1 = await reader1.LoadAsync((uint)(source.Size < 10000 ? source.Size : 10000)); //var size2 = await reader2.LoadAsync((uint)(protectedData.Size < 10000 ? protectedData.Size : 10000)); //IBuffer buffOriginalData = reader1.ReadBuffer((uint)size1); //IBuffer buffProtectedData = reader2.ReadBuffer((uint)size2); //if (CryptographicBuffer.Compare(buffOriginalData, buffProtectedData)) //{ // throw new Exception("ProtectPDFStream returned unprotected data"); //} //protectedData.Seek(0); //await protectedData.FlushAsync(); // Return the encrypted data. return protectedData; }
/// <summary> /// Saves the file with fullFilePath, uses FileMode.Create, so file create time will be rewrited if needed /// If exception has occurred while writing the file, it will delete it /// </summary> /// <param name="fullFilePath">example: "\\image_cache\\213898adj0jd0asd</param> /// <param name="cacheStream">stream to write to the file</param> /// <returns>true if file was successfully written, false otherwise</returns> protected async virtual Task<bool> InternalSaveAsync(string fullFilePath, IRandomAccessStream cacheStream) { var storageFile = await SF.CreateFileAsync(fullFilePath, CreationCollisionOption.ReplaceExisting); using (IRandomAccessStream outputStream = await storageFile.OpenAsync(FileAccessMode.ReadWrite)) { try { await RandomAccessStream.CopyAsync( cacheStream.GetInputStreamAt(0L), outputStream.GetOutputStreamAt(0L)); return true; } catch { try { // If file was not saved normally, we should delete it await storageFile.DeleteAsync(); } catch { ImageLog.Log("[error] can not delete unsaved file: " + fullFilePath); } } } ImageLog.Log("[error] can not save cache to the: " + fullFilePath); return false; }
public async Task<byte[]> GetBytesFromStream(IRandomAccessStream randomStream) { var reader = new DataReader(randomStream.GetInputStreamAt(0)); var bytes = new byte[randomStream.Size]; await reader.LoadAsync((uint)randomStream.Size); reader.ReadBytes(bytes); return bytes; }
// ToDo refactor please if EncodeHelper is not the apropiate place public static async Task<byte[]> GetStreamToBytesAsync(IRandomAccessStream fileStream) { using (DataReader reader = new DataReader(fileStream.GetInputStreamAt(0))) { await reader.LoadAsync((uint)fileStream.Size); byte[] pixeByte = new byte[fileStream.Size]; reader.ReadBytes(pixeByte); return pixeByte; } }
public static async Task <Photo> ResizeJpeg(IRandomAccessStream chosenPhoto, uint size, string originalFileName, string localFileName) { //Debug.WriteLine("ResizeJpeg.ThreadId=" + Thread.CurrentThread.ManagedThreadId); Photo photo; using (var sourceStream = chosenPhoto) { var decoder = await BitmapDecoder.CreateAsync(sourceStream); if (decoder.DecoderInformation != null && decoder.DecoderInformation.CodecId == BitmapDecoder.JpegDecoderId) { var maxDimension = Math.Max(decoder.PixelWidth, decoder.PixelHeight); var scale = (double)size / maxDimension; var orientedScaledHeight = (uint)(decoder.OrientedPixelHeight * scale); var orientedScaledWidth = (uint)(decoder.OrientedPixelWidth * scale); var scaledHeight = (uint)(decoder.PixelHeight * scale); var scaledWidth = (uint)(decoder.PixelWidth * scale); var transform = new BitmapTransform { ScaledHeight = scaledHeight, ScaledWidth = scaledWidth }; var pixelData = await decoder.GetPixelDataAsync( decoder.BitmapPixelFormat, decoder.BitmapAlphaMode, transform, ExifOrientationMode.RespectExifOrientation, ColorManagementMode.DoNotColorManage); using (var destinationStream = new InMemoryRandomAccessStream()) { var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, destinationStream); encoder.SetPixelData(decoder.BitmapPixelFormat, decoder.BitmapAlphaMode, orientedScaledWidth, orientedScaledHeight, decoder.DpiX, decoder.DpiY, pixelData.DetachPixelData()); await encoder.FlushAsync(); var reader = new DataReader(destinationStream.GetInputStreamAt(0)); var bytes = new byte[destinationStream.Size]; await reader.LoadAsync((uint)destinationStream.Size); reader.ReadBytes(bytes); photo = new Photo { Bytes = bytes, Width = (int)orientedScaledWidth, Height = (int)orientedScaledHeight, FileName = originalFileName }; if (!string.IsNullOrEmpty(localFileName)) { //await ComputeMD5(destinationStream); photo.File = await SaveToLocalFolderAsync(destinationStream.AsStream(), localFileName); } } } else { var reader = new DataReader(chosenPhoto.GetInputStreamAt(0)); var bytes = new byte[chosenPhoto.Size]; await reader.LoadAsync((uint)chosenPhoto.Size); reader.ReadBytes(bytes); photo = new Photo { Bytes = bytes, Width = (int)decoder.OrientedPixelWidth, Height = (int)decoder.OrientedPixelHeight, FileName = originalFileName }; if (!string.IsNullOrEmpty(localFileName)) { //await ComputeMD5(destinationStream); photo.File = await SaveToLocalFolderAsync(chosenPhoto.AsStream(), localFileName); } } } return(photo); }
public static async Task<string> GetStringFromStream(IRandomAccessStream stream) { using (var dataReader = new DataReader(stream.GetInputStreamAt(0))) { var size = await dataReader.LoadAsync((uint)stream.Size); return dataReader.ReadString(size); } }
public static FileInputStream RandomAccessStream2FileInputStream(IRandomAccessStream randomStream) { FileInputStream inputStream = randomStream.GetInputStreamAt(0) as FileInputStream; return(inputStream); }
public static async Task<IRandomAccessStream> UnprotectPDFStream(IRandomAccessStream source) { // Create a DataProtectionProvider object. DataProtectionProvider Provider = new DataProtectionProvider(); InMemoryRandomAccessStream unprotectedData = new InMemoryRandomAccessStream(); IOutputStream dest = unprotectedData.GetOutputStreamAt(0); await Provider.UnprotectStreamAsync(source.GetInputStreamAt(0), dest); await unprotectedData.FlushAsync(); unprotectedData.Seek(0); return unprotectedData; }
public static Stream RandomAccessStream2Stream(IRandomAccessStream randomStream) { return(WindowsRuntimeStreamExtensions.AsStreamForRead(randomStream.GetInputStreamAt(0))); }
public static async Task<byte[]> ConvertMemoryStreamToByteArray(IRandomAccessStream s) { // see stackoverflow.com/questions/14017900/conversion-between-bitmapimage-and-byte-array-in-windows8 using (DataReader reader = new DataReader(s.GetInputStreamAt(0))) { await reader.LoadAsync((uint)s.Size); byte[] p = new byte[s.Size]; reader.ReadBytes(p); return p; } }
public static IBuffer RandomAccessStream2Buffer(IRandomAccessStream randomStream) { Stream stream = WindowsRuntimeStreamExtensions.AsStreamForRead(randomStream.GetInputStreamAt(0)); MemoryStream memoryStream = new MemoryStream(); if (stream != null) { byte[] bytes = Stream2Bytes(stream); if (bytes != null) { var binaryWriter = new BinaryWriter(memoryStream); binaryWriter.Write(bytes); } } IBuffer buffer = WindowsRuntimeBufferExtensions.GetWindowsRuntimeBuffer(memoryStream, 0, (int)memoryStream.Length); return(buffer); }