示例#1
0
        public static async Task <InMemoryRandomAccessStream> ConvertByteToRandomAccessStream(byte[] arr)
        {
            InMemoryRandomAccessStream randomAccessStream = new InMemoryRandomAccessStream();
            await randomAccessStream.WriteAsync(arr.AsBuffer());

            randomAccessStream.Seek(0); // Just to be sure.
                                        // I don't think you need to flush here, but if it doesn't work, give it a try.
            return(randomAccessStream);
        }
示例#2
0
 static async ValueTask <ImageSource?> FetchImageAsync(Uri url)
 {
     var raStream = new InMemoryRandomAccessStream();
     await raStream.WriteAsync((await Reddit.FetchImageAsync(url)).AsBuffer());
     raStream.Seek(0);
     var bitmap = new BitmapImage();
     await bitmap.SetSourceAsync(raStream);
     return(bitmap);
 }
示例#3
0
        async void SetImageSource()
        {
            InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream();
            await stream.WriteAsync(ImageData.AsBuffer());

            stream.Seek(0);

            imageSource = new BitmapImage();
            imageSource.SetSource(stream);
        }
示例#4
0
        /// <summary>
        /// Convert byte[] to bitmap image
        /// </summary>
        private void ByteToBitmap()
        {

            if (_flag == null)
                _flag = new BitmapImage();
            using InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream();
            _ = stream.WriteAsync(FlagByte.AsBuffer());
            stream.Seek(0);
            _ = _flag.SetSourceAsync(stream);
        }
示例#5
0
        ///<summary>
        ///<para>Переделывает биты под картинку для отображения в проге</para>
        ///</summary>
        public static async Task <BitmapImage> ByteToImage(byte[] byteArray)
        {
            var bitmapImage = new BitmapImage();
            var stream      = new InMemoryRandomAccessStream();
            await stream.WriteAsync(byteArray.AsBuffer());

            stream.Seek(0);
            bitmapImage.SetSource(stream);
            return(bitmapImage);
        }
示例#6
0
        public static async Task <BitmapSource> LoadImageAsync(byte[] buffer)
        {
            using (var stream = new InMemoryRandomAccessStream())
            {
                await stream.WriteAsync(buffer.AsBuffer());

                stream.Seek(0);
                return(await LoadImageAsync(stream));
            }
        }
示例#7
0
        public override async Task <IRandomAccessStream> GetStreamAsync()
        {
            var content = await Client.DownloadAsync(Photo.Source).ConfigureAwait(false);

            var stream = new InMemoryRandomAccessStream();
            await stream.WriteAsync(content).AsTask().ConfigureAwait(false);

            Ready(this, stream);
            return(stream);
        }
示例#8
0
        async void SetImageSource()
        {
            InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream();
            await stream.WriteAsync(ImageData.AsBuffer());

            stream.Seek(0);

            imageSource = new BitmapImage();
            imageSource.SetSource(stream);
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("ImageSource"));
        }
示例#9
0
        private async Task InitializeWebView2()
        {
            var environment = await CoreWebView2Environment.CreateAsync();

            await _webview.EnsureCoreWebView2Async(environment);

            ApplyDefaultWebViewSettings();

            _webview.CoreWebView2.AddWebResourceRequestedFilter($"{AppOrigin}*", CoreWebView2WebResourceContext.All);
            _webview.CoreWebView2.WebResourceRequested += (sender, eventArgs) =>
            {
                // Unlike server-side code, we get told exactly why the browser is making the request,
                // so we can be smarter about fallback. We can ensure that 'fetch' requests never result
                // in fallback, for example.
                var allowFallbackOnHostPage =
                    eventArgs.ResourceContext == CoreWebView2WebResourceContext.Document ||
                    eventArgs.ResourceContext == CoreWebView2WebResourceContext.Other;                     // e.g., dev tools requesting page source

                if (TryGetResponseContent(eventArgs.Request.Uri, allowFallbackOnHostPage, out var statusCode, out var statusMessage, out var content, out var headers))
                {
                    // NOTE: This is stream copying is to work around a hanging bug in WinRT with managed streams
                    var memStream = new MemoryStream();
                    content.CopyTo(memStream);
                    var ms = new InMemoryRandomAccessStream();
                    ms.WriteAsync(memStream.GetWindowsRuntimeBuffer()).AsTask().Wait();

                    var headerString = GetHeaderString(headers);
                    eventArgs.Response = environment.CreateWebResourceResponse(ms, statusCode, statusMessage, headerString);
                }
            };

            // The code inside blazor.webview.js is meant to be agnostic to specific webview technologies,
            // so the following is an adaptor from blazor.webview.js conventions to WebView2 APIs
            await _webview.CoreWebView2 !.AddScriptToExecuteOnDocumentCreatedAsync(@"
                window.external = {
                    sendMessage: message => {
                        window.chrome.webview.postMessage(message);
                    },
                    receiveMessage: callback => {
                        window.chrome.webview.addEventListener('message', e => callback(e.data));
                    }
                };
            ");

            _webview.CoreWebView2.WebMessageReceived += (sender, eventArgs)
                                                        => MessageReceived(new Uri(eventArgs.Source), eventArgs.TryGetWebMessageAsString());

            _webview.CoreWebView2.DOMContentLoaded += async(_, __) =>
            {
                await _webview.CoreWebView2 !.ExecuteScriptAsync(@"
					Blazor.start();
					"                    );
            };
        }
示例#10
0
        private async Task LoadTileImageAsync(Tile tile, IBuffer buffer)
        {
            using (var stream = new InMemoryRandomAccessStream())
            {
                await stream.WriteAsync(buffer);

                stream.Seek(0);

                await SetTileImageAsync(tile, () => ImageLoader.LoadImageAsync(stream)).ConfigureAwait(false);
            }
        }
示例#11
0
        public static async Task SetSourceAsync(this BitmapImage image, byte[] buffer)
        {
            using (var stream = new InMemoryRandomAccessStream())
            {
                await stream.WriteAsync(buffer.AsBuffer());

                stream.Seek(0);

                await image.SetSourceAsync(stream);
            }
        }
示例#12
0
        async void LoadImageAsync(Product product)
        {
            ImageSource = new Image();
            using (var stream = new InMemoryRandomAccessStream())
            {
                await stream.WriteAsync(product.Image.AsBuffer());

                stream.Seek(0);
                await ImageSource.SetSourceAsync(stream);
            }
        }
示例#13
0
 public static BitmapImage AsBitmapImage(this byte[] byteArray)
 {
     using (var stream = new InMemoryRandomAccessStream())
     {
         stream.WriteAsync(byteArray.AsBuffer()).GetResults();
         stream.Seek(0);
         BitmapImage bmp = new BitmapImage();
         bmp.SetSource(stream);
         return(bmp);
     }
 }
        private async Task LoadPendingTiles(TileSource tileSource, string sourceName)
        {
            PendingTile pendingTile;
            var         cache = Cache;

            if (cache == null || sourceName == null)
            {
                while (pendingTiles.TryDequeue(out pendingTile))
                {
                    await DownloadImage(pendingTile.Tile, pendingTile.Image, pendingTile.Uri, null);
                }
            }
            else
            {
                while (pendingTiles.TryDequeue(out pendingTile))
                {
                    var tile      = pendingTile.Tile;
                    var image     = pendingTile.Image;
                    var uri       = pendingTile.Uri;
                    var extension = Path.GetExtension(uri.LocalPath);

                    if (string.IsNullOrEmpty(extension) || extension == ".jpeg")
                    {
                        extension = ".jpg";
                    }

                    var cacheKey  = string.Format(@"{0}\{1}\{2}\{3}{4}", sourceName, tile.ZoomLevel, tile.XIndex, tile.Y, extension);
                    var cacheItem = await cache.GetAsync(cacheKey);

                    var loaded = false;

                    if (cacheItem == null || cacheItem.Expiration <= DateTime.UtcNow)
                    {
                        loaded = await DownloadImage(tile, image, uri, cacheKey);
                    }

                    if (!loaded && cacheItem != null && cacheItem.Buffer != null)
                    {
                        using (var stream = new InMemoryRandomAccessStream())
                        {
                            await stream.WriteAsync(cacheItem.Buffer);

                            await stream.FlushAsync();

                            stream.Seek(0);

                            await LoadImageFromStream(tile, image, stream);
                        }
                    }
                }
            }

            Interlocked.Decrement(ref taskCount);
        }
示例#15
0
        protected override async Task <ImageSource> LoadImage(bool removeCache, CancellationToken token)
        {
            using var stream = new InMemoryRandomAccessStream();
            await stream.WriteAsync(_data.AsBuffer());

            stream.Seek(0);
            var bitmap = new BitmapImage();
            await bitmap.SetSourceAsync(stream);

            return(bitmap);
        }
示例#16
0
        private async void ConvertToBitmapImage()
        {
            Cover = new BitmapImage();
            using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream())
            {
                await stream.WriteAsync(CoverBytes.AsBuffer());

                stream.Seek(0);
                await Cover.SetSourceAsync(stream);
            }
        }
示例#17
0
 public void newAvatar(byte[] newAvatar)
 {
     using (var stream = new InMemoryRandomAccessStream())
     {
         stream.WriteAsync(new MyBuffer(newAvatar).Buffer).AsTask().GetAwaiter().GetResult();
         var x = new BitmapImage();
         stream.Seek(0);
         x.SetSource(stream);
         this.Avatar = x;
     }
 }
示例#18
0
        /// <summary>
        /// 异步从网络下载图片
        /// </summary>
        /// <param name="outfileName">下载保存到本地的图片文件名</param>
        /// <param name="downloadUriString">图片uri</param>
        /// <param name="scaleSize">图片尺寸</param>
        /// <returns></returns>
        public static async Task DownloadAndScale(string outfileName, string downloadUriString, Size scaleSize)
        {
            try
            {
                Uri        downLoadingUri = new Uri(downloadUriString); //创建uri对象
                HttpClient client         = new HttpClient();           //实例化httpclient对象
                using (var response = await client.GetAsync(downLoadingUri))
                {
                    var buffer = await response.Content.ReadAsBufferAsync();//从返回的数据中读取buffer

                    var memoryStream = new InMemoryRandomAccessStream();
                    await memoryStream.WriteAsync(buffer);                                                //将buffer写入memorystream

                    await memoryStream.FlushAsync();                                                      //刷新

                    var decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(memoryStream); //解密文件流

                    //确定图片大小
                    var bt = new Windows.Graphics.Imaging.BitmapTransform();
                    bt.ScaledWidth  = (uint)scaleSize.Width;
                    bt.ScaledHeight = (uint)scaleSize.Height;
                    //得到像素数值
                    var pixelProvider = await decoder.GetPixelDataAsync(
                        decoder.BitmapPixelFormat, decoder.BitmapAlphaMode, bt,
                        ExifOrientationMode.IgnoreExifOrientation, ColorManagementMode.ColorManageToSRgb);


                    //下面保存图片
                    // Now that we have the pixel data, get the destination file
                    var localFolder = ApplicationData.Current.LocalFolder;
                    //var resultsFolder = await localFolder.CreateFolderAsync("Results", CreationCollisionOption.OpenIfExists);
                    var scaledFile = await localFolder.CreateFileAsync(outfileName, CreationCollisionOption.ReplaceExisting);

                    using (var scaledFileStream = await scaledFile.OpenAsync(FileAccessMode.ReadWrite))
                    {
                        var encoder = await BitmapEncoder.CreateAsync(
                            BitmapEncoder.JpegEncoderId, scaledFileStream);

                        var pixels = pixelProvider.DetachPixelData();
                        encoder.SetPixelData(
                            decoder.BitmapPixelFormat,
                            decoder.BitmapAlphaMode,
                            (uint)scaleSize.Width,
                            (uint)scaleSize.Height,
                            decoder.DpiX,
                            decoder.DpiY,
                            pixels
                            );
                        await encoder.FlushAsync();
                    }
                }
            }
            catch (Exception) { Debug.WriteLine("工具,图片异常"); }
        }
    public async void PrintUWpAsync(byte[] imageData)
    {
        int i = 0;

        while (i < 5)
        {
            try
            {
                BitmapImage biSource = new BitmapImage();
                using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream())
                {
                    await stream.WriteAsync(imageData.AsBuffer());

                    stream.Seek(0);
                    await biSource.SetSourceAsync(stream);
                }

                ViewToPrint.Source = biSource;
                if (PrintDoc != null)
                {
                    printDoc.GetPreviewPage -= PrintDoc_GetPreviewPage;
                    printDoc.Paginate       -= PrintDoc_Paginate;
                    printDoc.AddPages       -= PrintDoc_AddPages;
                }

                this.printDoc = new PrintDocument();
                try
                {
                    printDoc.GetPreviewPage += PrintDoc_GetPreviewPage;
                    printDoc.Paginate       += PrintDoc_Paginate;
                    printDoc.AddPages       += PrintDoc_AddPages;

                    bool showprint = await PrintManager.ShowPrintUIAsync();
                }
                catch (Exception e)
                {
                    Debug.WriteLine(e.ToString());
                }

                //  printmgr = null;
                // printDoc = null;
                // Task = null;
                PrintDoc = null;
                GC.Collect();
                printmgr.PrintTaskRequested -= Printmgr_PrintTaskRequested;
                break;
            }
            catch (Exception e)
            {
                i++;
            }
        }
    }
示例#20
0
        public static BitmapImage ImageFromBytes(Byte[] bytes)
        {
            BitmapImage image = new BitmapImage();

            using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream())
            {
                stream.WriteAsync(bytes.AsBuffer());
                stream.Seek(0);
                image.SetSourceAsync(stream);
            }
            return(image);
        }
示例#21
0
        /// <summary>
        /// 初始化 CanvasBitmap.
        /// </summary>
        private async Task InitCanvasBitmap()
        {
            using (var stream = new InMemoryRandomAccessStream()) {
                var buffer = this.ImageByteString.ToByteArray().AsBuffer();
                await stream.WriteAsync(buffer);

                stream.Seek(0);
                var bitmap = await CanvasBitmap.LoadAsync(this.Stage, stream);

                this.CanvasBitmap = bitmap;
            }
        }
示例#22
0
        public static async Task <BitmapImage> ImageFromBuffer(IBuffer buffer)
        {
            var image = new BitmapImage();

            using (var stream = new InMemoryRandomAccessStream()) {
                stream.Seek(0);
                await stream.WriteAsync(buffer);

                await image.SetSourceAsync(stream);
            }
            return(image);
        }
示例#23
0
 public static BitmapImage ToOperatorImage(this string value)
 {
     byte[] array = (byte[])Resources.Resource.ResourceManager.GetObject($"operator_{value}");
     using (var stream = new InMemoryRandomAccessStream())
     {
         stream.WriteAsync(array.AsBuffer()).GetResults();
         stream.Seek(0);
         BitmapImage bmp = new BitmapImage();
         bmp.SetSource(stream);
         return(bmp);
     }
 }
示例#24
0
        public static async Task <BitmapImage> ByteArrayToImageAsync(byte[] pixeByte)
        {
            using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream())
            {
                BitmapImage image = new BitmapImage();
                await stream.WriteAsync(pixeByte.AsBuffer());

                stream.Seek(0);
                image.SetSource(stream);
                return(image);
            }
        }
示例#25
0
        public override async Task <IRandomAccessStream> GetStreamAsync()
        {
            var file = await StorageFile.GetFileFromApplicationUriAsync(Photo.Source);

            var content = await FileIO.ReadBufferAsync(file);

            var stream = new InMemoryRandomAccessStream();
            await stream.WriteAsync(content).AsTask().ConfigureAwait(false);

            Ready(this, stream);
            return(stream);
        }
        public void SetResponse(Stream content, int statusCode, string statusMessage, string headerString)
        {
            // NOTE: This is stream copying is to work around a hanging bug in WinRT with managed streams
            var memStream = new MemoryStream();

            content.CopyTo(memStream);
            var ms = new InMemoryRandomAccessStream();

            ms.WriteAsync(memStream.GetWindowsRuntimeBuffer()).AsTask().Wait();

            _webResourceRequestedEventArgs.Response = _environment.CreateWebResourceResponse(ms, statusCode, statusMessage, headerString);
        }
示例#27
0
        private async void mediaItemClicked(object sender, PointerRoutedEventArgs e)
        {
            if (sender is StackPanel)
            {
                StackPanel sp = sender as StackPanel;
                if (sp.DataContext is MediaItem)
                {
                    meMainMediaPlayer.Visibility = Visibility.Collapsed;
                    imgSelectedMedia.Visibility  = Visibility.Collapsed;

                    MediaItem mi = sp.DataContext as MediaItem;
                    if (mi.rawStorageFile.FileType == ".jpg" || mi.rawStorageFile.FileType == ".jpeg")
                    {
                        imgSelectedMedia.Visibility = Visibility.Visible;
                        var bytes = await GetBtyeFromFileAsync(mi.rawStorageFile);

                        if (bytes != null)
                        {
                            //var stream = new MemoryStream(bytes);
                            var randomAccessStream = new InMemoryRandomAccessStream();
                            randomAccessStream.WriteAsync(bytes.AsBuffer());
                            randomAccessStream.Seek(0);
                            var bi = new BitmapImage();
                            bi.ImageFailed += (s, o) =>
                            {
                                // This event is optional and is used to let us know if something went wrong
                                var m = "Failure";
                            };

                            await bi.SetSourceAsync(randomAccessStream);

                            imgSelectedMedia.Source = bi;
                        }
                    }
                    else if (mi.rawStorageFile.FileType == ".wma" || mi.rawStorageFile.FileType == ".mp3")
                    {
                        meMainMediaPlayer.Visibility = Visibility.Visible;
                        var bytes = await GetBtyeFromFileAsync(mi.rawStorageFile);

                        if (bytes != null)
                        {
                            var randomAccessStream = new InMemoryRandomAccessStream();
                            randomAccessStream.WriteAsync(bytes.AsBuffer());
                            randomAccessStream.Seek(0);
                            meMainMediaPlayer.SetSource(randomAccessStream, mi.rawStorageFile.ContentType);
                            meMainMediaPlayer.Play();
                            meMainMediaPlayer.Volume = 0.5;
                        }
                    }
                }
            }
        }
示例#28
0
        public async Task LoadPreviewAsync()
        {
            if (This.Preview != null)
            {
                using (var stream = new InMemoryRandomAccessStream())
                {
                    await stream.WriteAsync(This.Preview.AsBuffer());

                    stream.Seek(0);
                    await Preview.SetSourceAsync(stream);
                }
            }
        }
示例#29
0
        private async void LoadImage()
        {
            var image = new BitmapImage();

            using (var stream = new InMemoryRandomAccessStream())
            {
                await stream.WriteAsync(CoverBytes.AsBuffer());

                stream.Seek(0);
                await image.SetSourceAsync(stream);
            }
            Cover = image;
        }
示例#30
0
        private async void newAvatar(byte[] newAvatar)
        {
            using (var stream = new InMemoryRandomAccessStream())
            {
                await stream.WriteAsync(new MyBuffer(newAvatar).Buffer);

                BitmapImage x = new BitmapImage();
                stream.Seek(0);
                await x.SetSourceAsync(stream);

                this.Avatar = x;
            }
        }
示例#31
0
 /// <summary>
 /// Converts the specified byte array to a <see cref="IRandomAccessStream" />.
 /// </summary>
 /// <param name="buffer"></param>
 /// <returns></returns>
 private static async Task<IRandomAccessStream> ConvertToRandomAccessStream(byte[] buffer)
 {
     //https://stackoverflow.com/questions/16397509/how-to-convert-byte-array-to-inmemoryrandomaccessstream-or-irandomaccessstream-i
     var randomAccessStream = new InMemoryRandomAccessStream();
     await randomAccessStream.WriteAsync(buffer.AsBuffer());
     randomAccessStream.Seek(0);
     return randomAccessStream;
 }