Exemple #1
0
        public static async Task <Uri> ResizeImage(Uri uri, uint size)
        {
            if (uri.IsFile)
            {
                return(uri);
            }

            var response = await HttpWebRequest.Create(uri).GetResponseAsync();

            List <Byte> allBytes = new List <byte>();

            using (Stream imageStream = response.GetResponseStream())
            {
                InMemoryRandomAccessStream downloadedImageRas = new InMemoryRandomAccessStream();
                await RandomAccessStream.CopyAndCloseAsync(imageStream.AsInputStream(), downloadedImageRas.GetOutputStreamAt(0));

                BitmapDecoder bmpDecoder = await BitmapDecoder.CreateAsync(downloadedImageRas);

                BitmapFrame frame = await bmpDecoder.GetFrameAsync(0);

                BitmapTransform bmpTrans = new BitmapTransform();
                bmpTrans.InterpolationMode = BitmapInterpolationMode.Cubic;

                /*BitmapBounds bounds = new BitmapBounds();
                 * bounds.X = 0;
                 * bounds.Y = 0;
                 * bounds.Height = 360;
                 * bounds.Height = 360;
                 * bmpTrans.Bounds = bounds;*/
                bmpTrans.ScaledHeight = size;
                bmpTrans.ScaledWidth  = size;

                PixelDataProvider pixelDataProvider = await frame.GetPixelDataAsync(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Ignore, bmpTrans, ExifOrientationMode.RespectExifOrientation, ColorManagementMode.ColorManageToSRgb);

                byte[] pixelData = pixelDataProvider.DetachPixelData();

                InMemoryRandomAccessStream ras = new InMemoryRandomAccessStream();
                BitmapEncoder enc = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, ras);

                // write the pixel data to our stream
                enc.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Ignore, size, size, bmpDecoder.DpiX, bmpDecoder.DpiY, pixelData);
                await enc.FlushAsync();

                string fileName = Path.GetRandomFileName();
                var    file     = await ApplicationData.Current.LocalFolder.CreateFileAsync(
                    fileName + ".jpg", CreationCollisionOption.GenerateUniqueName);

                using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    await RandomAccessStream.CopyAndCloseAsync(ras.GetInputStreamAt(0), fileStream.GetOutputStreamAt(0));
                }
                return(new Uri("ms-appdata:///local/" + file.Name));
            }
        }
Exemple #2
0
        /// <summary>
        /// GetPixelFrame
        /// </summary>
        /// <param name="bitmap"></param>
        /// <returns></returns>
        public async Task <List <byte[]> > GetPixelFrame(BitmapDecoder bitmap)
        {
            List <byte[]> frames = new List <byte[]>();

            for (uint f = 0; f < FrameCount; f++)
            {
                BitmapFrame frame = await bitmap.GetFrameAsync(f).AsTask().ConfigureAwait(false);

                PixelDataProvider pixelData = await frame.GetPixelDataAsync().AsTask().ConfigureAwait(false);

                frames.Add(pixelData.DetachPixelData());
            }

            return(frames);
        }
Exemple #3
0
        private static async Task <byte[]> GetRGBABytesAsync(Stream imageStream, CancellationToken cancellationToken)
        {
            byte[] result;
            bool   overrideStream = !imageStream.CanSeek;
            Stream stream;

            if (overrideStream)
            {
                stream = new MemoryStream();
                imageStream.CopyTo(stream);
            }
            else
            {
                stream = imageStream;
            }

            using (var ras = stream.AsRandomAccessStream())
            {
                BitmapDecoder decoder = await BitmapDecoder.CreateAsync(ras).AsTask(cancellationToken).ConfigureAwait(false);

                BitmapFrame frame = await decoder.GetFrameAsync(0).AsTask(cancellationToken).ConfigureAwait(false);

                BitmapTransform transform = new BitmapTransform()
                {
                    ScaledWidth  = decoder.PixelWidth,
                    ScaledHeight = decoder.PixelHeight
                };

                PixelDataProvider pixelData = await frame.GetPixelDataAsync(
                    BitmapPixelFormat.Rgba8,
                    BitmapAlphaMode.Premultiplied,
                    transform,
                    ExifOrientationMode.IgnoreExifOrientation,
                    ColorManagementMode.DoNotColorManage)
                                              .AsTask(cancellationToken).ConfigureAwait(false);

                result = pixelData.DetachPixelData();
            }

            if (overrideStream)
            {
                stream.Dispose();
                stream = null;
            }

            return(result);
        }
Exemple #4
0
        public async Task <WriteableBitmap> getPNG(StorageFile sFile)
        {
            try
            {
                IRandomAccessStream stream = await sFile.OpenReadAsync();

                BitmapDecoder decoder = await BitmapDecoder.CreateAsync(BitmapDecoder.PngDecoderId, stream);

                // 获取第一帧
                BitmapFrame frame = await decoder.GetFrameAsync(0);

                // 获取像素数据
                PixelDataProvider pixprd = await frame.GetPixelDataAsync(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Straight, new BitmapTransform(), ExifOrientationMode.IgnoreExifOrientation, ColorManagementMode.DoNotColorManage);

                byte[] rgbaBuff = pixprd.DetachPixelData();
                byte[] res      = new byte[rgbaBuff.Length];
                for (int i = 0; i < rgbaBuff.Length; i += 4)
                {
                    byte r = rgbaBuff[i];
                    byte g = rgbaBuff[i + 1];
                    byte b = rgbaBuff[i + 2];
                    byte a = rgbaBuff[i + 3];
                    if (r == 0 && g == 0 && b == 0)
                    {
                        a = 0;
                    }
                    // 反色就是用255分别减去R,G,B的值
                    res[i]     = r;
                    res[i + 1] = g;
                    res[i + 2] = b;
                    res[i + 3] = a;
                }
                // 创建新的位图对象
                WriteableBitmap wb = new WriteableBitmap((int)frame.PixelWidth, (int)frame.PixelHeight);
                // 复制数据
                res.CopyTo(wb.PixelBuffer);
                return(wb);
            }
            catch (Exception)
            {
                throw;
            }
        }
        async Task <BitmapSource> LoadBitmapAsync(IRandomAccessStream stream)
        {
            WriteableBitmap bitmap = null;

            // Create a BitmapDecoder from the stream
            BitmapDecoder decoder = null;

            try
            {
                decoder = await BitmapDecoder.CreateAsync(stream);
            }
            catch
            {
                // Just skip ones that aren't valid
                return(null);
            }

            // Get the first frame
            BitmapFrame bitmapFrame = await decoder.GetFrameAsync(0);

            // Get the pixels
            PixelDataProvider dataProvider =
                await bitmapFrame.GetPixelDataAsync(BitmapPixelFormat.Bgra8,
                                                    BitmapAlphaMode.Premultiplied,
                                                    new BitmapTransform(),
                                                    ExifOrientationMode.RespectExifOrientation,
                                                    ColorManagementMode.ColorManageToSRgb);

            byte[] pixels = dataProvider.DetachPixelData();

            // Create WriteableBitmap and set the pixels
            bitmap = new WriteableBitmap((int)bitmapFrame.PixelWidth,
                                         (int)bitmapFrame.PixelHeight);

            using (Stream pixelStream = bitmap.PixelBuffer.AsStream())
            {
                pixelStream.Write(pixels, 0, pixels.Length);
            }

            bitmap.Invalidate();
            return(bitmap);
        }
Exemple #6
0
        async void OnPasteAppBarButtonClick(object sender, RoutedEventArgs args)
        {
            // Temporarily disable the Paste button
            Button button = sender as Button;

            button.IsEnabled = false;

            // Get the Clipboard contents and check for a bitmap
            DataPackageView dataView = Clipboard.GetContent();

            if (dataView.Contains(StandardDataFormats.Bitmap))
            {
                // Get the stream reference and a stream
                RandomAccessStreamReference streamRef = await dataView.GetBitmapAsync();

                IRandomAccessStreamWithContentType stream = await streamRef.OpenReadAsync();

                // Create a BitmapDecoder for reading the bitmap
                BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);

                BitmapFrame bitmapFrame = await decoder.GetFrameAsync(0);

                PixelDataProvider pixelProvider =
                    await bitmapFrame.GetPixelDataAsync(BitmapPixelFormat.Bgra8,
                                                        BitmapAlphaMode.Premultiplied,
                                                        new BitmapTransform(),
                                                        ExifOrientationMode.RespectExifOrientation,
                                                        ColorManagementMode.ColorManageToSRgb);

                // Save information sufficient for creating WriteableBitmap
                pastedPixelWidth  = (int)bitmapFrame.PixelWidth;
                pastedPixelHeight = (int)bitmapFrame.PixelHeight;
                pastedPixels      = pixelProvider.DetachPixelData();

                // Check if it's OK to replace the current painting
                await CheckIfOkToTrashFile(FinishPasteBitmapAndPixelArray);
            }

            // Re-enable the button and close the app bar
            button.IsEnabled         = true;
            this.BottomAppBar.IsOpen = false;
        }
Exemple #7
0
        public async Task <byte[]> DecodePixelAsync(uint frameIndex)
        {
            BitmapFrame bitmapFrame = null;

            if (!_bitmapFrameCache.TryGetValue(frameIndex, out bitmapFrame))
            {
                bitmapFrame = await _bitmapDecoder.GetFrameAsync(frameIndex);

                _bitmapFrameCache.Add(frameIndex, bitmapFrame);
            }
            var pixelData = await bitmapFrame.GetPixelDataAsync(
                BitmapPixelFormat.Bgra8,
                BitmapAlphaMode.Premultiplied,
                new BitmapTransform(),
                ExifOrientationMode.IgnoreExifOrientation,
                ColorManagementMode.DoNotColorManage
                ).AsTask().ConfigureAwait(false);

            return(pixelData.DetachPixelData());
        }
            public async Task <byte[]> DecodeAsync(BitmapDecoder bitmapDecoder)
            {
                BitmapFrame bitmapFrame = null;

                if (_bitmapFrame == null || !_bitmapFrame.TryGetTarget(out bitmapFrame))
                {
                    bitmapFrame = await bitmapDecoder.GetFrameAsync(FrameIndex).AsTask().ConfigureAwait(false);

                    _bitmapFrame = new WeakReference <BitmapFrame>(bitmapFrame);
                }
                var pixelData = await bitmapFrame.GetPixelDataAsync(
                    BitmapPixelFormat.Bgra8,
                    BitmapAlphaMode.Premultiplied,
                    new BitmapTransform(),
                    ExifOrientationMode.IgnoreExifOrientation,
                    ColorManagementMode.DoNotColorManage
                    ).AsTask().ConfigureAwait(false);

                return(pixelData.DetachPixelData());
            }
        async Task LoadBitmapFromFile(StorageFile storageFile)
        {
            using (IRandomAccessStreamWithContentType stream = await storageFile.OpenReadAsync())
            {
                BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);

                BitmapFrame bitmapframe = await decoder.GetFrameAsync(0);

                PixelDataProvider dataProvider =
                    await bitmapframe.GetPixelDataAsync(BitmapPixelFormat.Bgra8,
                                                        BitmapAlphaMode.Premultiplied,
                                                        new BitmapTransform(),
                                                        ExifOrientationMode.RespectExifOrientation,
                                                        ColorManagementMode.ColorManageToSRgb);

                pixels = dataProvider.DetachPixelData();
                bitmap = new WriteableBitmap((int)bitmapframe.PixelWidth,
                                             (int)bitmapframe.PixelHeight);
                await InitializeBitmap();
            }
        }
Exemple #10
0
        public static async Task <IRandomAccessStream> ResizeImageFile(Uri uri, uint size)
        {
            StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(uri);

            using (var fileStream = await file.OpenAsync(FileAccessMode.Read))
            {
                BitmapDecoder bmpDecoder = await BitmapDecoder.CreateAsync(fileStream);

                BitmapFrame frame = await bmpDecoder.GetFrameAsync(0);

                BitmapTransform bmpTrans = new BitmapTransform();
                bmpTrans.InterpolationMode = BitmapInterpolationMode.Cubic;

                /*BitmapBounds bounds = new BitmapBounds();
                 * bounds.X = 0;
                 * bounds.Y = 0;
                 * bounds.Height = 360;
                 * bounds.Height = 360;
                 * bmpTrans.Bounds = bounds;*/
                bmpTrans.ScaledHeight = size;
                bmpTrans.ScaledWidth  = size;

                PixelDataProvider pixelDataProvider = await frame.GetPixelDataAsync(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Ignore, bmpTrans, ExifOrientationMode.RespectExifOrientation, ColorManagementMode.ColorManageToSRgb);

                byte[] pixelData = pixelDataProvider.DetachPixelData();

                InMemoryRandomAccessStream ras = new InMemoryRandomAccessStream();
                BitmapEncoder enc = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, ras);

                // write the pixel data to our stream
                enc.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Ignore, size, size, bmpDecoder.DpiX, bmpDecoder.DpiY, pixelData);
                await enc.FlushAsync();

                return(ras);
            }
        }
        async void OnOpenAppBarButtonClick(object sender, RoutedEventArgs args)
        {
            // Create FileOpenPicker
            FileOpenPicker picker = new FileOpenPicker();

            picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;

            // Initialize with filename extensions
            IReadOnlyList <BitmapCodecInformation> codecInfos =
                BitmapDecoder.GetDecoderInformationEnumerator();

            foreach (BitmapCodecInformation codecInfo in codecInfos)
            {
                foreach (string extension in codecInfo.FileExtensions)
                {
                    picker.FileTypeFilter.Add(extension);
                }
            }

            // Get the selected file
            StorageFile storageFile = await picker.PickSingleFileAsync();

            if (storageFile == null)
            {
                return;
            }

            // Open the stream and create a decoder
            BitmapDecoder decoder = null;

            using (IRandomAccessStreamWithContentType stream = await storageFile.OpenReadAsync())
            {
                string exception = null;

                try
                {
                    decoder = await BitmapDecoder.CreateAsync(stream);
                }
                catch (Exception exc)
                {
                    exception = exc.Message;
                }

                if (exception != null)
                {
                    MessageDialog msgdlg =
                        new MessageDialog("That particular image file could not be loaded. " +
                                          "The system reports on error of: " + exception);
                    await msgdlg.ShowAsync();

                    return;
                }

                // Get the first frame
                BitmapFrame bitmapFrame = await decoder.GetFrameAsync(0);

                // Set information title
                txtblk.Text = String.Format("{0}: {1} x {2} {3} {4} x {5} DPI",
                                            storageFile.Name,
                                            bitmapFrame.PixelWidth, bitmapFrame.PixelHeight,
                                            bitmapFrame.BitmapPixelFormat,
                                            bitmapFrame.DpiX, bitmapFrame.DpiY);
                // Save the resolution
                dpiX = bitmapFrame.DpiX;
                dpiY = bitmapFrame.DpiY;

                // Get the pixels
                PixelDataProvider dataProvider =
                    await bitmapFrame.GetPixelDataAsync(BitmapPixelFormat.Bgra8,
                                                        BitmapAlphaMode.Premultiplied,
                                                        new BitmapTransform(),
                                                        ExifOrientationMode.RespectExifOrientation,
                                                        ColorManagementMode.ColorManageToSRgb);

                byte[] pixels = dataProvider.DetachPixelData();

                // Create WriteableBitmap and set the pixels
                WriteableBitmap bitmap = new WriteableBitmap((int)bitmapFrame.PixelWidth,
                                                             (int)bitmapFrame.PixelHeight);

                using (Stream pixelStream = bitmap.PixelBuffer.AsStream())
                {
                    await pixelStream.WriteAsync(pixels, 0, pixels.Length);
                }

                // Invalidate the WriteableBitmap and set as Image source
                bitmap.Invalidate();
                image.Source = bitmap;
            }

            // Enable the other buttons
            saveAsButton.IsEnabled      = true;
            rotateLeftButton.IsEnabled  = true;
            rotateRightButton.IsEnabled = true;
        }
        private static async Task <byte[]> GetPixelsAsync(BitmapFrame frame)
        {
            var pixelData = await frame.GetPixelDataAsync(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied, new BitmapTransform(), ExifOrientationMode.RespectExifOrientation, ColorManagementMode.DoNotColorManage);

            return(pixelData.DetachPixelData());
        }
Exemple #13
0
            private async Task AdvanceFrame()
            {
                if (_bitmapDecoder.FrameCount == 0)
                {
                    return;
                }

                var         frameIndex = _currentFrameIndex;
                BitmapFrame frame      = null;

                if (!_frameProperties[frameIndex].HasValue)
                {
                    frame = await _bitmapDecoder.GetFrameAsync((uint)frameIndex);

                    _frameProperties[frameIndex] = await RetrieveFramePropertiesAsync(frame);
                }
                FrameProperties frameProperties = _frameProperties[frameIndex].Value;

                // Increment frame index and loop count
                _currentFrameIndex++;
                if (_currentFrameIndex >= _bitmapDecoder.FrameCount)
                {
                    _completedLoops++;
                    _currentFrameIndex = 0;
                }

                // Set up the timer to display the next frame
                if (_imageProperties.IsAnimated &&
                    (_imageProperties.LoopCount == 0 || _completedLoops < _imageProperties.LoopCount))
                {
                    _animationTimer.Interval = TimeSpan.FromMilliseconds(frameProperties.DelayMilliseconds);
                }
                else
                {
                    _animationTimer.Stop();
                }

                // Decode the frame
                if (frame == null)
                {
                    frame = await _bitmapDecoder.GetFrameAsync((uint)frameIndex);
                }
                var pixelData = await frame.GetPixelDataAsync(
                    BitmapPixelFormat.Bgra8,
                    BitmapAlphaMode.Premultiplied,
                    new BitmapTransform(),
                    ExifOrientationMode.IgnoreExifOrientation,
                    ColorManagementMode.DoNotColorManage
                    );

                var pixels           = pixelData.DetachPixelData();
                var frameRectangle   = frameProperties.Rect;
                var disposeRectangle = Rect.Empty;

                if (frameIndex > 0)
                {
                    var previousFrameProperties = _frameProperties[frameIndex - 1].GetValueOrDefault();
                    if (previousFrameProperties.ShouldDispose)
                    {
                        // Clear the pixels from the last frame
                        disposeRectangle = previousFrameProperties.Rect;
                    }
                }
                else
                {
                    disposeRectangle = new Rect(0, 0, _imageProperties.PixelWidth, _imageProperties.PixelHeight);
                }


                // Compose and display the frame
                try
                {
                    PrepareFrame(pixels, frameRectangle, disposeRectangle);
                    UpdateImageSource(frameRectangle);
                }
                catch (Exception e) when(_canvasImageSource.Device.IsDeviceLost(e.HResult))
                {
                    // XAML will also raise a SurfaceContentsLost event, and we use this to trigger
                    // redrawing the surface. Therefore, ignore this error.
                }
            }
Exemple #14
0
        async Task CreateCollage(IReadOnlyList <StorageFile> files)
        {
            progressIndicator.Visibility = Windows.UI.Xaml.Visibility.Visible;
            var sampleDataGroups = files;

            if (sampleDataGroups.Count() == 0)
            {
                return;
            }

            try
            {
                // Do a square-root of the number of images to get the
                // number of images on x and y axis
                int number = (int)Math.Ceiling(Math.Sqrt((double)files.Count));
                // Calculate the width of each small image in the collage
                int numberX = (int)(ImageCollage.ActualWidth / number);
                int numberY = (int)(ImageCollage.ActualHeight / number);
                // Initialize an empty WriteableBitmap.
                WriteableBitmap destination = new WriteableBitmap(numberX * number, numberY * number);
                int             col         = 0; // Current Column Position
                int             row         = 0; // Current Row Position
                destination.Clear(Colors.White); // Set the background color of the image to white
                WriteableBitmap bitmap;          // Temporary bitmap into which the source
                // will be copied
                foreach (var file in files)
                {
                    // Create RandomAccessStream reference from the current selected image
                    RandomAccessStreamReference streamRef = RandomAccessStreamReference.CreateFromFile(file);
                    int    wid = 0;
                    int    hgt = 0;
                    byte[] srcPixels;
                    // Read the image file into a RandomAccessStream
                    using (IRandomAccessStreamWithContentType fileStream = await streamRef.OpenReadAsync())
                    {
                        // Now that you have the raw bytes, create a Image Decoder
                        BitmapDecoder decoder = await BitmapDecoder.CreateAsync(fileStream);

                        // Get the first frame from the decoder because we are picking an image
                        BitmapFrame frame = await decoder.GetFrameAsync(0);

                        // Convert the frame into pixels
                        PixelDataProvider pixelProvider = await frame.GetPixelDataAsync();

                        // Convert pixels into byte array
                        srcPixels = pixelProvider.DetachPixelData();
                        wid       = (int)frame.PixelWidth;
                        hgt       = (int)frame.PixelHeight;
                        // Create an in memory WriteableBitmap of the same size
                        bitmap = new WriteableBitmap(wid, hgt);
                        Stream pixelStream = bitmap.PixelBuffer.AsStream();
                        pixelStream.Seek(0, SeekOrigin.Begin);
                        // Push the pixels from the original file into the in-memory bitmap
                        pixelStream.Write(srcPixels, 0, (int)srcPixels.Length);
                        bitmap.Invalidate();

                        if (row < number)
                        {
                            // Resize the in-memory bitmap and Blit (paste) it at the correct tile
                            // position (row, col)
                            destination.Blit(new Rect(col * numberX, row * numberY, numberX, numberY),
                                             bitmap.Resize(numberX, numberY, WriteableBitmapExtensions.Interpolation.Bilinear),
                                             new Rect(0, 0, numberX, numberY));
                            col++;
                            if (col >= number)
                            {
                                row++;
                                col = 0;
                            }
                        }
                    }
                }

                ImageCollage.Source = destination;
                ((WriteableBitmap)ImageCollage.Source).Invalidate();
                progressIndicator.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
            }
            catch (Exception ex)
            {
                // TODO: Log Error, unable to render image
                throw;
            }
        }