Exemplo n.º 1
0
        public object Convert(object value, System.Type targetType, object parameter, string language)
        {
            var imgUrl = value as string;

            if (!string.IsNullOrEmpty(imgUrl))
            {
                if (Images.ContainsKey(imgUrl))
                {
                    return(Images[imgUrl]);
                }

                var bitmap = new BitmapImage();
                var ms     = new InMemoryRandomAccessStream();

                Factory.ImageCache.GetImage(imgUrl, async imgStream =>
                {
                    var mssw = ms.AsStreamForWrite();
                    await imgStream.CopyToAsync(mssw);
                    await mssw.FlushAsync();
                    ms.Seek(0);

                    bitmap.SetSource(ms);
                });

                return(bitmap);
            }
            return(value);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Loads the contents of this <see cref="ITextDocument"/> from the specified <see cref="DrxDocument"/>.
        /// </summary>
        public static void LoadFromDrx(this ITextDocument rtf, DrxDocument document)
        {
            if (document.Header.BodyType != DrxBodyType.Rtf)
            {
                throw new Exception("Document is of an unsupported encoding.");
            }

            var bytes = document.GetPlainTextBodyAsType(DrxBodyType.Rtf);

            if (bytes.Length <= 0)
            {
                // Remember to clear the document,
                // as we don't want leftover state for new ones
                rtf.SetText(TextSetOptions.None, string.Empty);
                return;
            }

            using (var stream = new InMemoryRandomAccessStream())
            {
                var writeStream = stream.AsStreamForWrite();
                writeStream.Write(bytes, 0, bytes.Length);
                writeStream.Position = 0;

                stream.Seek(0);
                rtf.LoadFromStream(TextSetOptions.FormatRtf, stream);
            }
        }
Exemplo n.º 3
0
        private static async Task LoadDisplayLogoAsync(ZipArchive archive, Theme theme)
        {
            // try and find it in the archive
            var strings = ResourceLoader.GetForViewIndependentUse("ThemesSettingsPage");
            var entry   = archive.GetEntry(theme.DisplayLogo);

            if (entry == null)
            {
                Analytics.TrackEvent("ThemeInstallFailure", new Dictionary <string, string>()
                {
                    ["Info"] = "InvalidLogo"
                });
                throw new InvalidOperationException(strings.GetString("ThemeInvalidNoLogo"));
            }

            // then load it into an image source
            using (var stream = new InMemoryRandomAccessStream())
            {
                var image = new BitmapImage();
                using (var entryStream = entry.Open())
                {
                    var destination = stream.AsStreamForWrite();
                    await entryStream.CopyToAsync(destination);

                    await destination.FlushAsync();
                }

                stream.Seek(0);
                await image.SetSourceAsync(stream);

                theme.DisplayLogoSource = image;
            }
        }
Exemplo n.º 4
0
        public async Task <IBitmap> Load(Stream sourceStream, float?desiredWidth, float?desiredHeight)
        {
            return(await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(async() => {
                using (var rwStream = new InMemoryRandomAccessStream()) {
                    var writer = rwStream.AsStreamForWrite();
                    await sourceStream.CopyToAsync(writer);
                    await writer.FlushAsync();
                    rwStream.Seek(0);

                    var decoder = await BitmapDecoder.CreateAsync(rwStream);

                    var transform = new BitmapTransform
                    {
                        ScaledWidth = (uint)(desiredWidth ?? decoder.OrientedPixelWidth),
                        ScaledHeight = (uint)(desiredHeight ?? decoder.OrientedPixelHeight),
                        InterpolationMode = BitmapInterpolationMode.Fant
                    };

                    var pixelData = await decoder.GetPixelDataAsync(decoder.BitmapPixelFormat, BitmapAlphaMode.Premultiplied, transform, ExifOrientationMode.RespectExifOrientation, ColorManagementMode.ColorManageToSRgb);
                    var pixels = pixelData.DetachPixelData();

                    var bmp = new WriteableBitmap((int)transform.ScaledWidth, (int)transform.ScaledHeight);
                    using (var bmpStream = bmp.PixelBuffer.AsStream()) {
                        bmpStream.Seek(0, SeekOrigin.Begin);
                        bmpStream.Write(pixels, 0, (int)bmpStream.Length);
                        return (IBitmap) new WriteableBitmapImageBitmap(bmp);
                    }
                }
            }));
        }
Exemplo n.º 5
0
        private InMemoryRandomAccessStream RunStream(string path_url)
        {
            HttpWebRequest lxRequest = (HttpWebRequest)WebRequest.Create(
                rem_main_URL + path_url);

            if (ClanREST.user_token != null)
            {
                lxRequest.Headers["Authorization"] = "Bearer_" + ClanREST.user_token;
            }

            String lsResponse = string.Empty;

            using (HttpWebResponse lxResponse = (HttpWebResponse)lxRequest.GetResponse())
            {
                using (BinaryReader reader = new BinaryReader(lxResponse.GetResponseStream()))
                {
                    Byte[]       lnByte   = reader.ReadBytes(0);
                    MemoryStream lxMS     = new MemoryStream();
                    Byte[]       lnBuffer = reader.ReadBytes(1024);
                    while (lnBuffer.Length > 0)
                    {
                        lxMS.Write(lnBuffer, 0, lnBuffer.Length);
                        lnBuffer = reader.ReadBytes(1024);
                    }

                    InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream();
                    stream.AsStreamForWrite().Write(lxMS.ToArray(), 0, lxMS.ToArray().Length);
                    stream.Seek(0);
                    return(stream);
                }
            }
        }
Exemplo n.º 6
0
        /// <summary>
        /// Convert WriteableBitmap to byte
        /// </summary>
        /// <param name="writeableBitmap"></param>
        /// <returns></returns>
        public async static Task <byte[]> GetPhotoBytesAsync(this WriteableBitmap writeableBitmap)
        {
            if (writeableBitmap == null)
            {
                return new byte[0] {
                }
            }
            ;
            Stream stream = writeableBitmap.PixelBuffer.AsStream();

            byte[] pixels = new byte[stream.Length];
            await stream.ReadAsync(pixels, 0, pixels.Length);

            ConvertToRGBA(writeableBitmap.PixelHeight, writeableBitmap.PixelWidth, pixels);
            InMemoryRandomAccessStream ims = new InMemoryRandomAccessStream();
            var imsWriter = ims.AsStreamForWrite();
            await Task.Factory.StartNew(() => stream.CopyTo(imsWriter));

            stream.Flush();
            stream.Dispose();
            BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, ims);

            encoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Premultiplied, (uint)writeableBitmap.PixelWidth, (uint)writeableBitmap.PixelHeight, 96, 96, pixels);
            await encoder.FlushAsync();

            stream = ims.AsStreamForRead();
            byte[] pixeBuffer = new byte[ims.Size];
            await stream.ReadAsync(pixeBuffer, 0, pixeBuffer.Length);

            stream.Flush();
            stream.Dispose();
            return(pixeBuffer);
        }
        public async void DoChange()
        {
            UnsplashImageProvider      unsplahsImage      = new UnsplashImageProvider(wallpaperMonsterConfiguration);
            WebResponse                webResponse        = unsplahsImage.LoadWebResponse(dimensions);
            InMemoryRandomAccessStream randomAccessStream = new InMemoryRandomAccessStream();

            using (Stream stream = unsplahsImage.FindRandomImageStream(webResponse))
            {
                Stream memoryStream = new MemoryStream();
                await stream.CopyToAsync(memoryStream);

                memoryStream.Position = 0;
                await memoryStream.CopyToAsync(randomAccessStream.AsStreamForWrite());

                memoryStream.Position = 0;
                if (wallpaperMonsterConfiguration.FindShouldChangeWallpaper())
                {
                    ChangeWallpaper(unsplahsImage, memoryStream);
                }
            }

            if (wallpaperMonsterConfiguration.FindShouldChangeLockScreen())
            {
                ChangeLockScreen(randomAccessStream);
            }
        }
Exemplo n.º 8
0
        public IImage Downsize(float maxWidthOrHeight, bool disposeOriginal = false)
        {
            if (Width > maxWidthOrHeight || Height > maxWidthOrHeight)
            {
                using (var memoryStream = new InMemoryRandomAccessStream())
                {
                    Save(memoryStream.AsStreamForWrite());
                    memoryStream.Seek(0);

                    // ReSharper disable once AccessToDisposedClosure
                    var newBitmap = AsyncPump.Run(async() => await CanvasBitmap.LoadAsync(_creator, memoryStream, 96));
                    using (var memoryStream2 = new InMemoryRandomAccessStream())
                    {
                        // ReSharper disable once AccessToDisposedClosure
                        AsyncPump.Run(async() => await newBitmap.SaveAsync(memoryStream2, CanvasBitmapFileFormat.Png));

                        memoryStream2.Seek(0);
                        var newImage = W2DGraphicsService.Instance.LoadImageFromStream(memoryStream2.AsStreamForRead());
                        if (disposeOriginal)
                        {
                            _bitmap.Dispose();
                        }

                        return(newImage);
                    }
                }
            }

            return(this);
        }
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            if (value == null)
            {
                return(null);
            }

            if (value.GetType() != typeof(string) && targetType != typeof(BitmapImage))
            {
                throw new InvalidCastException();
            }

            if (String.IsNullOrWhiteSpace((string)value))
            {
                return(null);
            }
            else
            {
                byte[] bytes = System.Convert.FromBase64String((string)value);

                using (InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream())
                {
                    ms.AsStreamForWrite().Write(bytes, 0, bytes.Length);
                    ms.Seek(0);

                    BitmapImage image = new BitmapImage();
                    image.SetSource(ms);
                    return(image);
                }
            }
        }
Exemplo n.º 10
0
        private static async Task LoadDisplayLogo(ZipArchive archive, Theme theme)
        {
            // try and find it in the archive
            var entry = archive.GetEntry(theme.DisplayLogo);

            if (entry == null)
            {
                throw new InvalidOperationException("This theme specifies a logo file that doesn't exist!");
            }

            // then load it into an image source
            using (var stream = new InMemoryRandomAccessStream())
            {
                var image = new BitmapImage();
                using (var entryStream = entry.Open())
                {
                    var destination = stream.AsStreamForWrite();
                    await entryStream.CopyToAsync(destination);

                    await destination.FlushAsync();
                }

                stream.Seek(0);
                await image.SetSourceAsync(stream);

                theme.DisplayLogoSource = image;
            }
        }
Exemplo n.º 11
0
        public byte[] DrawStrokeOnImageBackground(IReadOnlyList <InkStroke> strokes, byte[] backgroundImageBuffer)
        {
            var stmbuffer = new InMemoryRandomAccessStream();

            stmbuffer.AsStreamForWrite().AsOutputStream().WriteAsync(backgroundImageBuffer.AsBuffer()).AsTask().Wait();

            CanvasDevice device = CanvasDevice.GetSharedDevice();
            var          canbit = CanvasBitmap.LoadAsync(device, stmbuffer, 96).AsTask().Result;


            CanvasRenderTarget renderTarget = new CanvasRenderTarget(device, canbit.SizeInPixels.Width, canbit.SizeInPixels.Height, 96);

            using (var ds = renderTarget.CreateDrawingSession())
            {
                ds.Clear(Colors.Transparent);

                if (backgroundImageBuffer != null)
                {
                    ds.DrawImage(canbit);
                }

                ds.DrawInk(strokes);
            }
            var stm = new InMemoryRandomAccessStream();

            renderTarget.SaveAsync(stm, CanvasBitmapFileFormat.Png).AsTask().Wait();
            var readfrom = stm.GetInputStreamAt(0).AsStreamForRead();
            var ms       = new MemoryStream();

            readfrom.CopyTo(ms);
            var outputBuffer = ms.ToArray();

            return(outputBuffer);
        }
Exemplo n.º 12
0
        /// <summary>
        /// Converts the YUV2 image data into a bitmap image.
        /// </summary>
        /// <param name="yuvPixelArray">The image data in YUV2 format.</param>
        /// <param name="width">The width of the image in pixels.</param>
        /// <param name="height">The height of the image in pixels.</param>
        /// <returns>A BitmapImage instance containing the image.</returns>
        public static BitmapImage Yuy2PixelArrayToBitmapImage(byte[] yuvPixelArray, int width, int height)
        {
            BitmapImage bitmapImage = null;

            byte[] rgbPixelArray = ImageProcessingUtils.Yuy2PixelArrayToRgbPixelArray(yuvPixelArray, width, height);

            if (rgbPixelArray != null)
            {
                bitmapImage = new BitmapImage();

                InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream();
                stream.AsStreamForWrite().Write(rgbPixelArray, 0, rgbPixelArray.Length);
                stream.Seek(0);

                try
                {
                    bitmapImage.SetSource(stream);
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.Message);
                    bitmapImage = null;
                }
            }

            return(bitmapImage);
        }
Exemplo n.º 13
0
        public InMemoryRandomAccessStream GetStream(Image <Rgba32> image)
        {
            var outputStream = new InMemoryRandomAccessStream();

            image.SaveAsJpeg(outputStream.AsStreamForWrite());
            outputStream.Seek(0);
            return(outputStream);
        }
Exemplo n.º 14
0
        public static async Task <BitmapImage> GetImageAsync(string url)
        {
            try
            {
                byte[] data   = (await GetBufferAsync(new Uri(url), noCache: true)).ToArray();
                var    bmp    = new BitmapImage();
                var    stream = new InMemoryRandomAccessStream();
                stream.AsStreamForWrite().Write(data, 0, data.Length);
                stream.AsStreamForWrite().Flush();
                stream.Seek(0);
                bmp.SetSource(stream);
                return(bmp);
            }
            catch
            { }

            return(null);
        }
 async void PlayAudio(object sender, GenericEventArgs <Stream> args)
 {
     await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async() =>
     {
         Stream str = args.EventData;
         InMemoryRandomAccessStream ras = new InMemoryRandomAccessStream();
         await str.CopyToAsync(ras.AsStreamForWrite());
         Windows.Media.Playback.BackgroundMediaPlayer.Current.SetStreamSource(ras);
     });
 }
Exemplo n.º 16
0
        public static BitmapImage ImageFromBuffer(Byte[] bytes)
        {
            BitmapImage image = new BitmapImage();

            using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream())
            {
                stream.AsStreamForWrite().Write(bytes, 0, bytes.Length);
                image.SetSource(stream);
            }
            return(image);
        }
Exemplo n.º 17
0
        public override void Save(Stream stream, ImageFormat format)
        {
            Guid encoderId;

            if (format.Equals(ImageFormat.Bmp))
            {
                encoderId = BitmapEncoder.BmpEncoderId;
            }
            else if (format.Equals(ImageFormat.Gif))
            {
                encoderId = BitmapEncoder.GifEncoderId;
            }
            else if (format.Equals(ImageFormat.Jpeg))
            {
                encoderId = BitmapEncoder.JpegEncoderId;
            }
            else if (format.Equals(ImageFormat.Png))
            {
                encoderId = BitmapEncoder.PngEncoderId;
            }
            else if (format.Equals(ImageFormat.Tiff))
            {
                encoderId = BitmapEncoder.TiffEncoderId;
            }
            else
            {
                throw new ArgumentOutOfRangeException(nameof(format), format, "Unsupported bitmap encoding format");
            }

            Task.Run(
                async() =>
            {
                using (var localStream = new InMemoryRandomAccessStream())
                {
                    var encoder        = await BitmapEncoder.CreateAsync(encoderId, localStream);
                    var bitmapToEncode = this.Clone(PixelFormat.Format32bppArgb);
                    var length         = bitmapToEncode._height * bitmapToEncode._stride;
                    var bytes          = new byte[length];
                    Marshal.Copy(bitmapToEncode._scan0, bytes, 0, length);
                    encoder.SetPixelData(
                        BitmapPixelFormat.Bgra8,
                        BitmapAlphaMode.Straight,
                        (uint)bitmapToEncode._width,
                        (uint)bitmapToEncode._height,
                        96.0,
                        96.0,
                        bytes);
                    await encoder.FlushAsync();

                    localStream.Seek(0);
                    await localStream.AsStreamForWrite().CopyToAsync(stream);
                }
            }).Wait();
        }
Exemplo n.º 18
0
        /// <summary>
        /// 流类型的 转换
        /// </summary>
        /// <param name="stream">Stream 对象</param>
        /// <returns>IRandomAccessStream对象</returns>
        private static async Task <InMemoryRandomAccessStream> StreamToIRandomAccessStreamAsync(Stream stream)
        {
            InMemoryRandomAccessStream ras = new InMemoryRandomAccessStream();
            Stream s = ras.AsStreamForWrite();
            await stream.CopyToAsync(s);

            //需要提交数据
            await s.FlushAsync();

            return(ras);
        }
Exemplo n.º 19
0
        public static async Task <WriteableBitmap> GetImage(string url)
        {
            // string fileName = Http.APIService.FileNameFromURL(url)+".jpg";
            string          fileName = Http.APIService.FileNameFromURL(url);
            WriteableBitmap wb       = await GetLocalPictureAsync(fileName);

            if (wb == null)
            {
                try
                {
                    IBuffer buffer = await SendGetRequestAsBytes(url);

                    if (buffer != null)
                    {
                        BitmapImage bi = new BitmapImage();
                        wb = null;
                        Stream stream2Write;
                        using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream())
                        {
                            stream2Write = stream.AsStreamForWrite();

                            await stream2Write.WriteAsync(buffer.ToArray(), 0, (int)buffer.Length);

                            await stream2Write.FlushAsync();

                            stream.Seek(0);

                            await bi.SetSourceAsync(stream);

                            wb = new WriteableBitmap(bi.PixelWidth, bi.PixelHeight);
                            stream.Seek(0);
                            await wb.SetSourceAsync(stream);

                            //保存在本地
                            await SaveBitmapToFileAsync(wb, fileName);

                            return(wb);
                        }
                    }
                    else
                    {
                        return(null);
                    }
                }
                catch
                {
                    return(null);
                }
            }
            else
            {
                return(wb);
            }
        }
Exemplo n.º 20
0
        public static async void AppendFile(StorageFile sf)
        {
            TagLib.File afi = TagLib.File.Create(new UwpStorageFileAbstraction(sf), ReadStyle.Average);
            AudioInfo   ai  = new AudioInfo()
            {
                Album  = string.IsNullOrEmpty(afi.Tag.Album) ? "未知专辑" : afi.Tag.Album,
                Artist = string.IsNullOrEmpty(string.Join('/', afi.Tag.Performers)) ? "未知歌手" : string.Join('/', afi.Tag.Performers),
                LengthInMilliseconds = afi.Properties.Duration.TotalMilliseconds,
                SongName             = string.IsNullOrEmpty(afi.Tag.Title) ? "Untitled" : afi.Tag.Title,
                LocalSongFile        = sf
            };

            //记载歌词
            try
            {
                StorageFile lrcfile = await(await sf.GetParentAsync()).GetFileAsync(Path.ChangeExtension(sf.Name, "lrc"));
                ai.Lyric = await FileIO.ReadTextAsync(lrcfile);
            }
            catch (Exception) { }
            try
            {
                BitmapImage img = new BitmapImage();
                using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream())
                {
                    stream.AsStreamForWrite().Write(afi.Tag.Pictures[0].Data.ToArray(), 0,
                                                    afi.Tag.Pictures[0].Data.ToArray().Length);
                    stream.Seek(0);
                    await img.SetSourceAsync(stream);

                    InMemoryRandomAccessStream streamb = new InMemoryRandomAccessStream();
                    streamb.AsStreamForWrite().Write(afi.Tag.Pictures[0].Data.ToArray(), 0,
                                                     afi.Tag.Pictures[0].Data.ToArray().Length);
                    streamb.Seek(0);
                    ai.Thumbnail = Windows.Storage.Streams.RandomAccessStreamReference.CreateFromStream(streamb);
                }

                ai.BitmapImage = img;
            }
            catch (Exception) { }

            HyPlayItem hyPlayItem = new HyPlayItem()
            {
                AudioInfo = ai,
                isOnline  = false,
                ItemType  = HyPlayItemType.Local,
                Name      = ai.SongName,
                Path      = sf.Path
            };

            List.Add(hyPlayItem);
            RequestSyncPlayList();
        }
Exemplo n.º 21
0
        //粤语发音
        private async void Voice_Click(object sender, RoutedEventArgs e)
        {
            TextToVoice temp  = new TextToVoice();
            Stream      voice = await temp.ReadText(Input.Text);

            InMemoryRandomAccessStream ras = new InMemoryRandomAccessStream();
            await voice.CopyToAsync(ras.AsStreamForWrite());

            await ras.FlushAsync();

            ras.Seek(0);
            MyMediaPlayer.SetSource(ras, "");
        }
Exemplo n.º 22
0
        /// <summary>
        /// Converts the sketch to a bitmap image.
        /// </summary>
        /// <returns>The `UIImage` representation of the sketch.</returns>
        public BitmapImage ToImage()
        {
            // Convert the image and return
            var skPngdata  = Draw();
            var imageBytes = skPngdata.ToArray();
            var image      = new BitmapImage();
            InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream();

            ms.AsStreamForWrite().Write(imageBytes, 0, imageBytes.Length);
            ms.Seek(0);
            image.SetSource(ms);
            return(image);
        }
Exemplo n.º 23
0
        public static ImageSource GetSource(this byte[] imagem)
        {
            var retorno = new BitmapImage();

            using (var stream = new InMemoryRandomAccessStream())
            {
                var otherStream = stream.AsStreamForWrite();
                otherStream.Write(imagem, 0, imagem.Length);
                stream.Seek(0);
                retorno.SetSource(stream);
            }
            return(retorno);
        }
Exemplo n.º 24
0
        private async void MyBooksSelectionChanged(object sender, RoutedEventArgs e)
        {
            var selected = flipMyBooks.SelectedItem as EbookViewModel;

            if (selected == null)
            {
                return;
            }

            ProgressRingBooks.IsActive = true;

            ObservableCollection <ImageSource> pdf = null;

            if (gvImages.ItemsSource != null)
            {
                pdf = gvImages.ItemsSource as ObservableCollection <ImageSource>;
                gvImages.SelectedIndex = 0;
                pdf.Clear();
            }
            else
            {
                pdf = new ObservableCollection <ImageSource>();
                gvImages.ItemsSource = pdf;
            }

            var query = new GetAllEbookPartsQuery();
            await query.ExecuteAsync(OAuthSettings.AccessToken, selected.Id, selected.PartCount,
                                     async (sourceStream) =>
            {
                var stream = new InMemoryRandomAccessStream();
                await sourceStream.CopyToAsync(stream.AsStreamForWrite());
                var doc = await PdfDocument.LoadFromStreamAsync(stream);
                for (uint i = 0; i < doc.PageCount; ++i)
                {
                    var bmpStream = new Windows.Storage.Streams.InMemoryRandomAccessStream();

                    await doc.GetPage(i).RenderToStreamAsync(bmpStream);

                    Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                    {
                        var bmp = new BitmapImage();
                        bmp.SetSource(bmpStream);
                        pdf.Add(bmp);
                    });
                }
            });

            ProgressRingBooks.IsActive = false;
        }
Exemplo n.º 25
0
        public BitmapImage ToImage()
        {
            // Get image data from sketch
            var skPngdata = Untitled1ToData();

            // Convert to image and return
            var imageBytes = skPngdata.ToArray();
            var image      = new BitmapImage();
            InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream();

            ms.AsStreamForWrite().Write(imageBytes, 0, imageBytes.Length);
            ms.Seek(0);
            image.SetSource(ms);
            return(image);
        }
Exemplo n.º 26
0
        public static async Task <BitmapImage> ConvertToImageAsync(byte[] bytes)
        {
            using (var ras = new InMemoryRandomAccessStream())
            {
                var memoryStream = new MemoryStream(bytes);

                await memoryStream.CopyToAsync(ras.AsStreamForWrite());

                var bitmapImage = new BitmapImage();

                await bitmapImage.SetSourceAsync(ras);

                return(bitmapImage);
            }
        }
        public IRandomAccessStream GetData()
        {
            var facesImage   = faces.Substring(22);
            var imageDataRaw = Convert.FromBase64String(facesImage);

            var ramStream = new InMemoryRandomAccessStream();
            var stream    = ramStream.AsStreamForWrite();

            stream.Write(imageDataRaw, 0, imageDataRaw.Length);
            stream.Flush();

            ramStream.Seek(0);

            return(ramStream);
        }
        public static ImageSource ByteToImage(byte[] imageData)
        {
            BitmapImage biImg = new BitmapImage();

            InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream();

            ms.AsStreamForWrite().Write(imageData, 0, imageData.Length);
            ms.Seek(0);

            biImg.SetSource(ms);

            ImageSource imgSrc = biImg as ImageSource;

            return(imgSrc);
        }
Exemplo n.º 29
0
        public IRandomAccessStream AsStream()
        {
            var bytes       = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(this));
            var stream      = new InMemoryRandomAccessStream();
            var writeStream = stream.AsStreamForWrite();

            using (var writer = new BinaryWriter(writeStream, Encoding.UTF8, true))
            {
                writer.Write(bytes.Length);
                writeStream.Write(bytes, 0, bytes.Length);
            }

            stream.Seek(0);
            return(stream);
        }
Exemplo n.º 30
0
        private static async Task <SoftwareBitmap> GetSoftwareBitmapFromBitmap(Bitmap bitmap)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                bitmap.Save(ms, ImageFormat.Bmp);
                using (IRandomAccessStream ras = new InMemoryRandomAccessStream())
                {
                    ms.Seek(0, SeekOrigin.Begin);
                    await ms.CopyToAsync(ras.AsStreamForWrite());

                    BitmapDecoder decoder = await BitmapDecoder.CreateAsync(ras);

                    return(await decoder.GetSoftwareBitmapAsync());
                }
            }
        }