public override long Seek(long offset, SeekOrigin origin) { if (_disposed) { throw new ObjectDisposedException("_stream"); } switch (origin) { case SeekOrigin.Begin: _stream.Seek((ulong)offset); break; case SeekOrigin.Current: _stream.Seek(_stream.Position + (ulong)offset); break; case SeekOrigin.End: _stream.Seek(_stream.Size - (ulong)offset); break; default: throw new ArgumentOutOfRangeException("offset"); } return((long)_stream.Position); }
public async Task <Windows.UI.Xaml.Media.Imaging.BitmapImage> GetBitmapAsync() { var image = new Windows.UI.Xaml.Media.Imaging.BitmapImage(); stream.Seek(0); image.SetSource(stream); return(image); }
public Task <BitmapImage> GetBitmapAsync() { var image = new BitmapImage(); stream.Seek(0); image.SetSource(stream); return(Task.FromResult(image)); }
private async void LoadPhotos() { // clear existing photos m_oFlipView.Items.Clear(); m_oImageToFileMapping = new Dictionary <WriteableBitmap, StorageFile>(); m_oImageToBoxMapping = new Dictionary <WriteableBitmap, Box>(); // get box folder foreach (Box oCurrentBox in MoveList.CurrentMove.Boxes) { if (oCurrentBox != null) { StorageFolder oBoxFolder = await oCurrentBox.AssociatedMove.MoveFolder.GetFolderAsync(oCurrentBox.ImageFolder); IReadOnlyList <StorageFile> oPhotos = await oBoxFolder.GetFilesAsync(); // if there's an empty list of photos, we can stop the process here and show the empty indicator if (oPhotos.Count <= 0) { EmptyBoxIndicator.Visibility = Visibility.Visible; } else { // iterate through folder and load each photo foreach (StorageFile oPhoto in oPhotos) { using (IRandomAccessStream oPhotoStream = await oPhoto.OpenReadAsync()) { WriteableBitmap oBitmap = new WriteableBitmap(1, 1); oPhotoStream.Seek(0); oBitmap.SetSource(oPhotoStream); oBitmap = new WriteableBitmap(oBitmap.PixelWidth, oBitmap.PixelHeight); oPhotoStream.Seek(0); oBitmap.SetSource(oPhotoStream); // add photo m_oFlipView.Items.Add(oBitmap); m_oImageToFileMapping.Add(oBitmap, oPhoto); m_oImageToBoxMapping.Add(oBitmap, oCurrentBox); } } // hide the empty box indicator EmptyBoxIndicator.Visibility = Visibility.Collapsed; } } else { EmptyBoxIndicator.Visibility = Visibility.Visible; } } }
public static async Task <object> OpenImage(StorageFile file) { try { IRandomAccessStream stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read); if (stream.Size != 0) { BitmapImage bi = new BitmapImage(); await bi.SetSourceAsync(stream); bi = new BitmapImage(); stream.Seek(0); return(stream); } } catch (Exception ex) { MessageDialog msg = new MessageDialog(ex.Message + Environment.NewLine + ex.InnerException, ex.HResult.ToString()); msg.ShowAsync(); } return(null); }
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 async Task <bool> ApplyEffectAsync(StorageFile file, SwapChainPanelRenderer m_renderer) { IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.Read); string errorMessage = null; try { fileStream.Seek(0); ((IImageConsumer)_grayscaleEffect).Source = new Lumia.Imaging.RandomAccessStreamImageSource(fileStream); await m_renderer.RenderAsync(); } catch (Exception exception) { errorMessage = exception.Message; } if (!string.IsNullOrEmpty(errorMessage)) { var dialog = new MessageDialog(errorMessage); await dialog.ShowAsync(); return(false); } return(true); }
public static async Task CreateAndWriteToFileAsync(IRandomAccessStream contentStream, string path) { CreateParentDirectories(path); await using var stream = File.Open(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None); contentStream.Seek(0); await contentStream.AsStreamForRead().CopyToAsync(stream); }
private async Task <bool> ApplyEffectAsync(StorageFile file) { // Open a stream for the selected file. IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.Read); string errorMessage = null; try { // Show thumbnail of original image. _thumbnailImageBitmap.SetSource(fileStream); OriginalImage.Source = _thumbnailImageBitmap; // Rewind stream to start. fileStream.Seek(0); // Set the imageSource on the effect and render ((IImageConsumer)_grayscaleEffect).Source = new Lumia.Imaging.RandomAccessStreamImageSource(fileStream); await m_renderer.RenderAsync(); } catch (Exception exception) { errorMessage = exception.Message; } if (!string.IsNullOrEmpty(errorMessage)) { var dialog = new MessageDialog(errorMessage); await dialog.ShowAsync(); return(false); } return(true); }
/// <summary> /// Rotates the image at the specified file path. /// </summary> /// <param name="filePath">The file path to the image.</param> /// <param name="rotation">The rotation direction.</param> /// <remarks> /// https://docs.microsoft.com/en-us/uwp/api/windows.graphics.imaging.bitmapdecoder?view=winrt-22000 /// https://docs.microsoft.com/en-us/uwp/api/windows.graphics.imaging.bitmapencoder?view=winrt-22000 /// </remarks> public static async Task Rotate(string filePath, BitmapRotation rotation) { if (string.IsNullOrEmpty(filePath)) { return; } var file = await StorageHelpers.ToStorageItem <IStorageFile>(filePath); if (file == null) { return; } using IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.ReadWrite); BitmapDecoder decoder = await BitmapDecoder.CreateAsync(fileStream); using var memStream = new InMemoryRandomAccessStream(); BitmapEncoder encoder = await BitmapEncoder.CreateForTranscodingAsync(memStream, decoder); encoder.BitmapTransform.Rotation = rotation; await encoder.FlushAsync(); memStream.Seek(0); fileStream.Seek(0); fileStream.Size = 0; await RandomAccessStream.CopyAsync(memStream, fileStream); }
public override void SetLength(Int64 value) { if (value < 0) { throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_CannotResizeStreamToNegative); } Contract.EndContractBlock(); IRandomAccessStream wrtStr = EnsureNotDisposed <IRandomAccessStream>(); if (!_canSeek) { throw new NotSupportedException(SR.NotSupported_CannotSeekInStream); } EnsureCanWrite(); #if DEBUG AssertValidStream(wrtStr); #endif // DEBUG wrtStr.Size = unchecked ((UInt64)value); // If the length is set to a value < that the current position, then we need to set the position to that value // Because we can't directly set the position, we are going to seek to it. if (wrtStr.Size < wrtStr.Position) { wrtStr.Seek(unchecked ((UInt64)value)); } }
//gets the byte array from the BitmapDecoder // public async Task LoadFromDecoder(BitmapDecoder decoder) { this.decoder = decoder; //creates the byte array from the decoder var imagePixelData = await decoder.GetPixelDataAsync(); bytes = imagePixelData.DetachPixelData(); //creates the stream from the byte array stream = new InMemoryRandomAccessStream(); await stream.WriteAsync(bytes.AsBuffer()); stream.Seek(0); //creats the bitmapImage from the stream image = new BitmapImage(); image.SetSource(stream); //decoder initializes SoftwareBitmap softMap = await decoder.GetSoftwareBitmapAsync(); //gets the pixel width and height of the image width = (int)decoder.PixelWidth; height = (int)decoder.PixelHeight; }
/// <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; } } }
public SegmentRandomAccessStream(IRandomAccessStream stream, UInt64 offset, UInt64 length) { Stream = stream; Offset = offset; Length = length; stream.Seek(offset); }
async public static void Log(string s) { using (var releaser = await myLock.LockAsync()) { StorageFile sfile = await ApplicationData.Current.LocalFolder.CreateFileAsync("errorlog.txt", CreationCollisionOption.OpenIfExists); using (IRandomAccessStream rasw = await sfile.OpenAsync(FileAccessMode.ReadWrite)) { IBuffer ibuf = null; using (IInputStream inputStream = rasw.GetInputStreamAt(0)) { ulong size = rasw.Size; DataReader dataReader = new DataReader(inputStream); await dataReader.LoadAsync((uint)size); ibuf = dataReader.ReadBuffer((uint)size); inputStream.Dispose(); } if (ibuf.Length < 64000) { await rasw.WriteAsync(ibuf); } await rasw.WriteAsync(CryptographicBuffer.ConvertStringToBinary("\r\n" + DateTime.Now.ToUniversalTime().ToString() + " : " + s, BinaryStringEncoding.Utf8)); rasw.Seek(0); await rasw.FlushAsync(); rasw.Dispose(); } } }
public static async Task <Tuple <ImageSource, ImageSource> > GetImageAndBlurredCopyFromPixelDataAsync([NotNull] IBuffer buffer, int blur) { // Check if the input is valid if (buffer.Length == 0) { return(null); } // Apply the blur effect on a copy of the original image using (Stream imageStream = buffer.AsStream()) using (IRandomAccessStream randomImageStream = imageStream.AsRandomAccessStream()) { // Load the default image BitmapImage original = new BitmapImage(); await original.SetSourceAsync(randomImageStream); // Blur the copy of the image randomImageStream.Seek(0); using (RandomAccessStreamImageSource imageProvider = new RandomAccessStreamImageSource(randomImageStream)) using (BlurEffect blurEffect = new BlurEffect(imageProvider) { KernelSize = blur }) { // Process the blurred image WriteableBitmap blurred = new WriteableBitmap((int)original.PixelWidth, (int)original.PixelHeight); await blurEffect.GetBitmapAsync(blurred, OutputOption.Stretch); // Return the two images return(Tuple.Create <ImageSource, ImageSource>(original, blurred)); } } }
/// <summary> /// 保存文档时,调用Onsave()方法。 /// 首先,FileSavePicker用于允许用户选择文档,与FileOpenPicker类似。 /// 接下来,使用OpenTransactedWriteAsync打开文件。 /// NTFS文件系统支持事务;这些都不包含在.NETFramework中,但可用于Windows运行库。 /// OpenTransactedWriteAsync返回一个实现了接口IStorageStreamTransaction的StorageStreamTransaction对象。 /// 这个对象本身并不是流,但是它包含了一个可以用Stream属性引用的流。 /// 这个属性返回一个IRandomAccessStream流。 /// 与创建DataReader类似,可以创建一个DataWriter,写入原始数据类型,包括字符串, /// StoreAsync方法最后把缓冲区的内容写到流中。 /// 销毁写入器之前,需要调用CommitAsync方法来提交 /// </summary> public async void OnSave() { try { var picker = new FileSavePicker() { SuggestedStartLocation = PickerLocationId.DocumentsLibrary, SuggestedFileName = "新建文本文档" }; picker.FileTypeChoices.Add("Plain Text", new List<string>() { ".txt" }); StorageFile file = await picker.PickSaveFileAsync(); if (file != null) { using (StorageStreamTransaction tx = await file.OpenTransactedWriteAsync()) { IRandomAccessStream stream = tx.Stream; stream.Seek(0); using (var writer = new DataWriter(stream)) { writer.WriteString(myText.Text); tx.Stream.Size = await writer.StoreAsync(); await tx.CommitAsync(); } } } } catch (Exception ex) { await new MessageDialog(ex.Message, "Error").ShowAsync(); } }
public static async Task <ImageSource> BlurImageAsync([NotNull] IBuffer buffer, int blur) { using (Stream imageStream = buffer.AsStream()) using (IRandomAccessStream randomImageStream = imageStream.AsRandomAccessStream()) { BitmapDecoder decoder; try { decoder = await BitmapDecoder.CreateAsync(randomImageStream); } catch { // Invalid image data return(null); } randomImageStream.Seek(0); using (RandomAccessStreamImageSource imageProvider = new RandomAccessStreamImageSource(randomImageStream)) using (BlurEffect blurEffect = new BlurEffect(imageProvider) { KernelSize = blur }) { WriteableBitmap blurred = new WriteableBitmap((int)decoder.PixelWidth, (int)decoder.PixelHeight); return(await blurEffect.GetBitmapAsync(blurred, OutputOption.Stretch)); } } }
private async void Button_Click(object sender, RoutedEventArgs e) { FileOpenPicker openPicker = new FileOpenPicker(); openPicker.ViewMode = PickerViewMode.Thumbnail; openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary; openPicker.FileTypeFilter.Add(".jpg"); openPicker.FileTypeFilter.Add(".jpeg"); openPicker.FileTypeFilter.Add(".png"); StorageFile file = await openPicker.PickSingleFileAsync(); if (file != null) { using (IRandomAccessStream stream = await file.OpenReadAsync()) { BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream); bitmap.SetSource(stream); img.Source = bitmap; stream.Seek(0); grayscaleEffect.Source = new Lumia.Imaging.RandomAccessStreamImageSource(stream); await renderer.RenderAsync(); } } }
public static IRandomAccessStream GetAppendStream(StorageFile file) { IRandomAccessStream stream = GetWriteStream(file); stream.Seek(stream.Size); return(stream); }
/// <summary> /// GetImage by Filter /// </summary> /// <param name="stream"></param> /// <param name="filter"></param> /// <returns></returns> public async static Task <WriteableBitmap> GetImageByFilter(this IRandomAccessStream stream, IFilter filter) { stream.Seek(0); var imageFormat = ImageFormat.Jpeg; var imageType = await getImageType(stream); if (imageType == ImageType.PNG) { imageFormat = ImageFormat.Png; } using (var source = new RandomAccessStreamImageSource(stream, imageFormat)) { // Create effect collection with the source stream using (var filters = new FilterEffect(source)) { // Initialize the filter and add the filter to the FilterEffect collection filters.Filters = new IFilter[] { filter }; // Create a target where the filtered image will be rendered to var target = new WriteableBitmap((int)(Window.Current.Bounds.Width), (int)(Window.Current.Bounds.Height)); // Create a new renderer which outputs WriteableBitmaps using (var renderer = new WriteableBitmapRenderer(filters, target)) { // Render the image with the filter(s) target = await renderer.RenderAsync(); target.Invalidate(); return(target); } } } }
public override void SetLength(long value) { if (value < 0) { throw new ArgumentOutOfRangeException(nameof(value), global::Windows.Storage.Streams.SR.ArgumentOutOfRange_CannotResizeStreamToNegative); } IRandomAccessStream wrtStr = EnsureNotDisposed <IRandomAccessStream>(); if (!_canSeek) { throw new NotSupportedException(global::Windows.Storage.Streams.SR.NotSupported_CannotSeekInStream); } EnsureCanWrite(); Debug.Assert(wrtStr != null); wrtStr.Size = unchecked ((ulong)value); // If the length is set to a value < that the current position, then we need to set the position to that value // Because we can't directly set the position, we are going to seek to it. if (wrtStr.Size < wrtStr.Position) { wrtStr.Seek(unchecked ((ulong)value)); } }
public async static Task <WriteableBitmap> ToBitmapImageAsync(this byte[] imageBytes, Tuple <int, int> downscale, InterpolationMode mode) { if (imageBytes == null) { return(null); } IRandomAccessStream image = imageBytes.AsBuffer().AsStream().AsRandomAccessStream(); if (downscale != null && (downscale.Item1 > 0 || downscale.Item2 > 0)) { image = await image.ResizeImage((uint)downscale.Item1, (uint)downscale.Item2, mode).ConfigureAwait(false); } using (image) { BitmapDecoder decoder = await BitmapDecoder.CreateAsync(image); image.Seek(0); WriteableBitmap bitmap = null; await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Low, async() => { bitmap = new WriteableBitmap((int)decoder.PixelWidth, (int)decoder.PixelHeight); await bitmap.SetSourceAsync(image); }); return(bitmap); } }
private async void _pictureTimer_Tick(object sender, object e) { var newImage = _nextImageFiles[_nextImageIndex]; if (newImage != null) { // increment the index (and rotate back to 0 when needed) _nextImageIndex = (_nextImageIndex + 1) % _nextImageFiles.Length; Debug.WriteLine($"{DateTime.Now}: Next slideshow image: {newImage.Name}"); IRandomAccessStream fileStream = null; MemoryStream memStream = null; try { // even with the paid for codecs from the Microsoft Store HEIC images do not always load // so instead we use MagickImage to convert them to JPEG on the fly. // TODO: Consider doing this as a one-time step when downloading the image to just write a jpeg if (newImage.FileType == ".heic") { using (var magickImage = new MagickImage(newImage.Path)) { magickImage.Format = MagickFormat.Jpeg; memStream = new MemoryStream(); magickImage.Write(memStream); fileStream = memStream.AsRandomAccessStream(); fileStream.Seek(0); } } else { fileStream = (FileRandomAccessStream)await newImage.OpenAsync(Windows.Storage.FileAccessMode.Read); } var image = new BitmapImage(); await image.SetSourceAsync(fileStream); SlideShowSource = image; } catch (Exception exception) { // TODO: at some point we need better handling and tracking of exceptions... Debug.WriteLine("EXCEPTION LOADING IMAGE: " + exception); } finally { fileStream?.Dispose(); memStream?.Dispose(); } if (_nextImageIndex == _nextImageFiles.Length / 2) { RefreshImageQueueAsync(); } } }
/// <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 <string> Sha1Async(this IRandomAccessStream randomAccessStream) { using var sha1 = SHA1.Create(); var result = await sha1.ComputeHashAsync(randomAccessStream.AsStreamForRead()); randomAccessStream.Seek(0); // reset the stream return(result.Select(b => b.ToString("x2")).Aggregate((acc, str) => acc + str)); }
public static async Task <BitmapImage> ToBitmapImageAsync(this IRandomAccessStream accessStream) { accessStream.Seek(0); BitmapImage bitmap = new BitmapImage(); await bitmap.SetSourceAsync(accessStream); return(bitmap); }
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)); }
private ImageSource GetImageSource(IRandomAccessStream stream) { var bitmapImage = new BitmapImage(); stream.Seek(0); bitmapImage.SetSource(stream); return(bitmapImage); }
public static async Task RotateCaptureImageByDisplayInformationAutoRotationPreferences(IRandomAccessStream inStream, IRandomAccessStream outStream) { BitmapDecoder decoder = await BitmapDecoder.CreateAsync(inStream); BitmapEncoder encoder = await BitmapEncoder.CreateForTranscodingAsync(outStream, decoder); var ort = DisplayInformation.GetForCurrentView().CurrentOrientation; Debug.WriteLine(ort); switch (ort) { //The same as Portrait case DisplayOrientations.None: encoder.BitmapTransform.Rotation = BitmapRotation.Clockwise90Degrees; break; //The default view for capture. case DisplayOrientations.Landscape: encoder.BitmapTransform.Rotation = BitmapRotation.None; break; case DisplayOrientations.Portrait: encoder.BitmapTransform.Rotation = BitmapRotation.Clockwise90Degrees; break; case DisplayOrientations.LandscapeFlipped: encoder.BitmapTransform.Rotation = BitmapRotation.Clockwise180Degrees; break; case DisplayOrientations.PortraitFlipped: encoder.BitmapTransform.Rotation = BitmapRotation.Clockwise270Degrees; break; default: break; } await encoder.FlushAsync(); inStream.Seek(0); outStream.Seek(0); }
/// <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; }
private async void PlayBackImage_ImageOpened(IRandomAccessStream stream) { if (CurrentSong != null) { { var device = new CanvasDevice(); var bitmap = await CanvasBitmap.LoadAsync(device, stream); var renderer = new CanvasRenderTarget(device, bitmap.SizeInPixels.Width, bitmap.SizeInPixels.Height, bitmap.Dpi); using (var ds = renderer.CreateDrawingSession()) { var blur = new GaussianBlurEffect { Source = bitmap }; blur.BlurAmount = 16.0f; blur.BorderMode = EffectBorderMode.Hard; ds.DrawImage(blur); } stream.Seek(0); await renderer.SaveAsync(stream, CanvasBitmapFileFormat.Png); stream.Seek(0); BitmapImage image = new BitmapImage(); image.SetSource(stream); BackgroundBlur.Source = image; renderer = null; bitmap = null; device = null; GC.Collect(); } } }
/// <summary> /// TODO: Apply filter to image /// </summary> /// <param name="fileStream"></param> private async void ApplyEffectAsync(IRandomAccessStream fileStream) { double scaleFactor = 1.0; scaleFactor = DisplayInformation.GetForCurrentView().RawPixelsPerViewPixel; _writeableBitmap = new WriteableBitmap((int)(Window.Current.Bounds.Width * scaleFactor), (int)(Window.Current.Bounds.Height * scaleFactor)); _grayscaleEffect = new GrayscaleEffect(); _brightnessEffect = new BrightnessEffect(_grayscaleEffect); // m_renderer = new SwapChainPanelRenderer(_brightnessEffect, SwapChainPanelTarget); string errorMessage = null; try { // Rewind the stream to start. fileStream.Seek(0); // Set the imageSource on the effect and render. ((IImageConsumer)_grayscaleEffect).Source = new Lumia.Imaging.RandomAccessStreamImageSource(fileStream); await m_renderer.RenderAsync(); } catch (Exception exception) { errorMessage = exception.Message; } }
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); }
/// <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); }
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(); } } }
private async void loadWebViewToStream(WebView webview, IRandomAccessStream stream) { await Task.Delay(TimeSpan.FromMilliseconds(10)); await webview.CapturePreviewToStreamAsync(stream); await stream.FlushAsync(); stream.Seek(0); }
/// <summary> /// Apply filter to image /// </summary> /// <param name="fileStream"></param> private async Task ApplyEffectAsync(IRandomAccessStream fileStream, IImageProvider provider, SwapChainPanel target) { using (var _renderer = new SwapChainPanelRenderer(provider, target)) { try { // Rewind the stream to start. fileStream.Seek(0); // Set the imageSource on the effect and render. ((IImageConsumer)provider).Source = new RandomAccessStreamImageSource(fileStream); await _renderer.RenderAsync(); } catch (Exception exception) { System.Diagnostics.Debug.WriteLine(exception.Message); } } }