public async Task ConverterBitmapToTargetStreamAsync(IRandomAccessStream bitmapSourceStream, IRandomAccessStream saveTargetStream)
        {
            BitmapDecoder decoder = await BitmapDecoder.CreateAsync(bitmapSourceStream);

            // Scale image to appropriate size
            BitmapTransform transform = new BitmapTransform()
            {
                //ScaledWidth = Convert.ToUInt32(bi.PixelWidth),
                //ScaledHeight = Convert.ToUInt32(bi.PixelHeight)
            };

            PixelDataProvider pixelData = await decoder.GetPixelDataAsync(
                BitmapPixelFormat.Bgra8,                    // WriteableBitmap uses BGRA format
                BitmapAlphaMode.Straight,
                transform,
                ExifOrientationMode.RespectExifOrientation,                 // This sample ignores Exif orientation
                ColorManagementMode.DoNotColorManage);

            var BitmapEncoderGuid = BitmapEncoder.PngEncoderId;

            BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoderGuid, saveTargetStream);

            encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore,
                                 (uint)decoder.PixelWidth,
                                 (uint)decoder.PixelHeight,
                                 96.0,
                                 96.0,
                                 pixelData.DetachPixelData());
            await encoder.FlushAsync();
        }
Example #2
0
        private async void DisplayImage(byte[] img, int imageType)
        {
            if (Displayer != null)
            {
                try
                {
                    // Decode the JPEG
                    BitmapDecoder decoder = await BitmapDecoder.CreateAsync(ConvertTo(img));

                    PixelDataProvider pixelData = await decoder.GetPixelDataAsync();

                    byte[] decompressedImage = pixelData.DetachPixelData();
                    uint   width             = decoder.PixelWidth;
                    uint   height            = decoder.PixelHeight;
                    // TODO: Convert SoftwareBitmap to matrix and pass to ImageDisplayer
                    if (imageType == RECEIVING_RGB)
                    {
                        // TODO: Make Display methods take the one dimensional decompressed byte array
                        byte[,,] decompressedRGBMatrix = ConvertDecompressedToRGBMatrix(decompressedImage, width, height);
                        Displayer.DisplayRGB(decompressedImage);
                    }
                    else if (imageType == RECEIVING_ONE_BAND)
                    {
                        // Displayer.DisplayOneBand(decompressedImage);
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                }
            }
        }
Example #3
0
        private async Task <byte[]> ImageToBytes(IRandomAccessStream sourceStream)
        {
            byte[] imageArray;

            BitmapDecoder decoder = await BitmapDecoder.CreateAsync(sourceStream);

            var transform = new BitmapTransform {
                ScaledWidth = decoder.PixelWidth, ScaledHeight = decoder.PixelHeight
            };
            PixelDataProvider pixelData = await decoder.GetPixelDataAsync(
                BitmapPixelFormat.Rgba8,
                BitmapAlphaMode.Straight,
                transform,
                ExifOrientationMode.RespectExifOrientation,
                ColorManagementMode.DoNotColorManage);

            using (var destinationStream = new InMemoryRandomAccessStream())
            {
                BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, destinationStream);

                encoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Premultiplied, decoder.PixelWidth,
                                     decoder.PixelHeight, 96, 96, pixelData.DetachPixelData());
                await encoder.FlushAsync();

                BitmapDecoder outputDecoder = await BitmapDecoder.CreateAsync(destinationStream);

                await destinationStream.FlushAsync();

                imageArray = (await outputDecoder.GetPixelDataAsync()).DetachPixelData();
            }
            return(imageArray);
        }
Example #4
0
        public async Task <byte[]> GetScaledPixelsAsync(int height, int width)
        {
            using (IRandomAccessStream fileStream = await m_file.OpenAsync(Windows.Storage.FileAccessMode.Read))
            {
                BitmapDecoder decoder = await BitmapDecoder.CreateAsync(fileStream);

                // Scale image to appropriate size
                BitmapTransform transform = new BitmapTransform()
                {
                    ScaledWidth  = Convert.ToUInt32(width),
                    ScaledHeight = Convert.ToUInt32(height)
                };
                PixelDataProvider pixelData = await decoder.GetPixelDataAsync(
                    BitmapPixelFormat.Bgra8, // WriteableBitmap uses BGRA format
                    BitmapAlphaMode.Straight,
                    transform,
                    ExifOrientationMode.IgnoreExifOrientation, // This sample ignores Exif orientation
                    ColorManagementMode.DoNotColorManage
                    );

                // An array containing the decoded image data, which could be modified before being displayed
                byte[] sourcePixels = pixelData.DetachPixelData();

                return(sourcePixels);
            }
        }
Example #5
0
        public static async Task <IRandomAccessStream> ImageToJPegStreamAsync(IRandomAccessStream imageStream)
        {
            //Create a decoder for the image
            var decoder = await BitmapDecoder.CreateAsync(imageStream);

            PixelDataProvider pixelData = await decoder.GetPixelDataAsync();

            byte[] pixelBytes = pixelData.DetachPixelData();

            //
            InMemoryRandomAccessStream jpegStream = new InMemoryRandomAccessStream();

            double jpegImageQuality = 0.9;

            var propertySet  = new BitmapPropertySet();
            var qualityValue = new BitmapTypedValue(jpegImageQuality, Windows.Foundation.PropertyType.Single);

            propertySet.Add("ImageQuality", qualityValue);

            var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, jpegStream, propertySet);

            //key thing here is to use decoder.OrientedPixelWidth and decoder.OrientedPixelHeight otherwise you will get garbled image on devices on some photos with orientation in metadata
            encoder.SetPixelData(decoder.BitmapPixelFormat, decoder.BitmapAlphaMode, decoder.OrientedPixelWidth, decoder.OrientedPixelHeight, decoder.DpiX, decoder.DpiY, pixelBytes);

            //ulong jpegImageSize = 0;
            //jpegImageSize = jpegStream.Size;

            await encoder.FlushAsync();

            await jpegStream.FlushAsync();

            return(jpegStream);
        }
Example #6
0
    public async Task <WriteableBitmap> GetImage()
    {
        if (this.mediaCapture == null)
        {
            return(null);
        }
        InMemoryRandomAccessStream inStream = new InMemoryRandomAccessStream();

        await this.mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), inStream);

        BitmapDecoder decoder = await BitmapDecoder.CreateAsync(inStream);

        BitmapTransform   transform = new BitmapTransform();
        PixelDataProvider provider  = await decoder.GetPixelDataAsync(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, transform, ExifOrientationMode.IgnoreExifOrientation, ColorManagementMode.DoNotColorManage);

        byte[] sourcePixels = provider.DetachPixelData();

        WriteableBitmap bmp = new WriteableBitmap((int)decoder.PixelWidth, (int)decoder.PixelHeight);

        using (Stream outputStream = bmp.PixelBuffer.AsStream())
        {
            await outputStream.WriteAsync(sourcePixels, 0, sourcePixels.Length);
        }
        return(bmp);
    }
Example #7
0
        private async Task ResizeToJpegPhoto(IRandomAccessStream inputStream, IRandomAccessStream outputStream, uint maxSize)
        {
            BitmapDecoder decoder = await BitmapDecoder.CreateAsync(inputStream);

            double scaleFactor = 1.0;
            uint   pixelSize   = decoder.PixelWidth > decoder.PixelHeight ? decoder.PixelWidth : decoder.PixelHeight;

            if (pixelSize > maxSize)
            {
                scaleFactor = (double)maxSize / pixelSize;
            }
            BitmapTransform transform = new BitmapTransform();

            transform.ScaledWidth       = (uint)(decoder.PixelWidth * scaleFactor);
            transform.ScaledHeight      = (uint)(decoder.PixelHeight * scaleFactor);
            transform.InterpolationMode = BitmapInterpolationMode.Fant;

            BitmapPixelFormat pixelFormat       = decoder.BitmapPixelFormat;
            BitmapAlphaMode   alphaMode         = decoder.BitmapAlphaMode;
            PixelDataProvider pixelDataProvider = await decoder.GetPixelDataAsync(pixelFormat, alphaMode, transform, ExifOrientationMode.RespectExifOrientation, ColorManagementMode.DoNotColorManage);

            var pixels = pixelDataProvider.DetachPixelData();

            uint finalWidth  = (uint)(decoder.OrientedPixelWidth * scaleFactor);
            uint finalHeight = (uint)(decoder.OrientedPixelHeight * scaleFactor);

            BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, outputStream);

            encoder.SetPixelData(pixelFormat, alphaMode, finalWidth, finalHeight, decoder.DpiX, decoder.DpiY, pixels);
            await encoder.FlushAsync();
        }
        public static async Task <WriteableBitmap> StorageFileToWriteableBitmapWithDirection(StorageFile file)
        {
            if (file == null)
            {
                return(null);
            }
            using (IRandomAccessStream stream = await file.OpenReadAsync())
            {
                // Create a decoder from the stream. With the decoder, we can get
                // the properties of the image.
                BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);

                PixelDataProvider pix = await decoder.GetPixelDataAsync(
                    BitmapPixelFormat.Bgra8,
                    BitmapAlphaMode.Straight,
                    new BitmapTransform(),
                    ExifOrientationMode.RespectExifOrientation,
                    ColorManagementMode.DoNotColorManage);

                byte[]          pixels    = pix.DetachPixelData();
                WriteableBitmap Bmp       = new WriteableBitmap((int)decoder.OrientedPixelWidth, (int)decoder.OrientedPixelHeight);
                Stream          pixStream = Bmp.PixelBuffer.AsStream();
                pixStream.Write(pixels, 0, (int)(decoder.OrientedPixelWidth * decoder.OrientedPixelHeight * 4));

                return(Bmp);
            }
        }
        private async Task ResizeImage(StorageFile sourceFile, StorageFile destinationFile)
        {
            using (var sourceStream = await sourceFile.OpenAsync(FileAccessMode.Read))
            {
                BitmapDecoder decoder = await BitmapDecoder.CreateAsync(sourceStream);

                var newWidth  = Math.Min(800, decoder.PixelWidth);
                var newHeight = newWidth * decoder.PixelHeight / decoder.PixelWidth;

                BitmapTransform transform = new BitmapTransform()
                {
                    ScaledHeight = newHeight, ScaledWidth = newWidth
                };
                PixelDataProvider pixelData = await decoder.GetPixelDataAsync(
                    BitmapPixelFormat.Rgba8,
                    BitmapAlphaMode.Straight,
                    transform,
                    ExifOrientationMode.RespectExifOrientation,
                    ColorManagementMode.DoNotColorManage);

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

                    encoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Premultiplied, newWidth, newHeight, 96,
                                         96, pixelData.DetachPixelData());
                    await encoder.FlushAsync();
                }
            }
        }
Example #10
0
        public static async Task <Image <TColor, TDepth> > FromStorageFile(StorageFile file)
        {
            using (IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
            {
                BitmapDecoder decoder = await BitmapDecoder.CreateAsync(fileStream);

                Size s = new Size((int)decoder.PixelWidth, (int)decoder.PixelHeight);

                BitmapTransform   transform = new BitmapTransform();
                PixelDataProvider pixelData = await decoder.GetPixelDataAsync(
                    BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, transform, ExifOrientationMode.IgnoreExifOrientation,
                    ColorManagementMode.DoNotColorManage);

                byte[]   sourcePixels = pixelData.DetachPixelData();
                GCHandle handle       = GCHandle.Alloc(sourcePixels, GCHandleType.Pinned);
                using (Image <Bgra, Byte> img = new Image <Bgra, byte>(s.Width, s.Height, s.Width * 4, handle.AddrOfPinnedObject()))
                {
                    Image <TColor, TDepth> result = new Image <TColor, TDepth>(img.Size);
                    result.ConvertFrom(img);

                    handle.Free();
                    return(result);
                }
            }
        }
Example #11
0
        public static async Task <string> SaveStreamAsync(IRandomAccessStream streamToSave, uint width, uint height, string fileName)
        {
            FolderPicker folderPicker = new FolderPicker();

            folderPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            folderPicker.ViewMode = PickerViewMode.List;
            folderPicker.FileTypeFilter.Add(".jpg");
            folderPicker.FileTypeFilter.Add(".jpeg");
            folderPicker.FileTypeFilter.Add(".png");
            StorageFolder newFolder = await folderPicker.PickSingleFolderAsync();

            StorageFile destination = await newFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);

            BitmapTransform transform = new BitmapTransform();

            BitmapDecoder bmpDecoder = await BitmapDecoder.CreateAsync(streamToSave);

            PixelDataProvider pixelData = await bmpDecoder.GetPixelDataAsync(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Straight, transform, ExifOrientationMode.RespectExifOrientation, ColorManagementMode.DoNotColorManage);

            using (var destFileStream = await destination.OpenAsync(FileAccessMode.ReadWrite))
            {
                BitmapEncoder bmpEncoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, destFileStream);

                bmpEncoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Straight, width, height, 300, 300, pixelData.DetachPixelData());
                await bmpEncoder.FlushAsync();
            }
            return(destination.Path);
        }
        private static async Task <WriteableBitmap> GetImageFile(Uri fileUri)
        {
            StorageFile imageFile = await StorageFile.GetFileFromApplicationUriAsync(fileUri);

            WriteableBitmap writeableBitmap = null;

            using (IRandomAccessStream imageStream = await imageFile.OpenReadAsync())
            {
                BitmapDecoder bitmapDecoder = await BitmapDecoder.CreateAsync(imageStream);

                BitmapTransform   dummyTransform    = new BitmapTransform();
                PixelDataProvider pixelDataProvider =
                    await bitmapDecoder.GetPixelDataAsync(BitmapPixelFormat.Bgra8,
                                                          BitmapAlphaMode.Premultiplied, dummyTransform,
                                                          ExifOrientationMode.RespectExifOrientation,
                                                          ColorManagementMode.ColorManageToSRgb);

                byte[] pixelData = pixelDataProvider.DetachPixelData();

                writeableBitmap = new WriteableBitmap(
                    (int)bitmapDecoder.OrientedPixelWidth,
                    (int)bitmapDecoder.OrientedPixelHeight);
                using (Stream pixelStream = writeableBitmap.PixelBuffer.AsStream())
                {
                    await pixelStream.WriteAsync(pixelData, 0, pixelData.Length);
                }
            }
            return(writeableBitmap);
        }
Example #13
0
        /// <summary>
        /// Resize the file to a certain level
        /// </summary>
        /// <param name="name">Final Name Of the Files Generated </param>
        /// <param name="hsize">Height Of Image</param>
        /// <param name="wsize">Width Of Image</param>
        /// <param name="file">The File That Needs To Be Resized</param>
        /// <param name="folder">Location of the final file</param>
        public async static Task Resizer(String name, uint hsize, uint wsize, StorageFile file, StorageFolder folder)
        {
            StorageFile newFile = await folder.CreateFileAsync(name);

            using (var sourceStream = await file.OpenAsync(FileAccessMode.Read))
            {
                BitmapDecoder decoder = await BitmapDecoder.CreateAsync(sourceStream);

                BitmapTransform transform = new BitmapTransform()
                {
                    ScaledHeight = hsize, ScaledWidth = wsize
                };
                PixelDataProvider pixelData = await decoder.GetPixelDataAsync(
                    BitmapPixelFormat.Rgba8,
                    BitmapAlphaMode.Straight,
                    transform,
                    ExifOrientationMode.RespectExifOrientation,
                    ColorManagementMode.DoNotColorManage);

                using (var destinationStream = await newFile.OpenAsync(FileAccessMode.ReadWrite))
                {
                    BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, destinationStream);

                    encoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Premultiplied, wsize, hsize, 100, 100, pixelData.DetachPixelData());
                    await encoder.FlushAsync();
                }
            }
        }
Example #14
0
        public static async Task <BitmapSource> CreateScaledBitmapFromStreamAsync(WebView web, IRandomAccessStream source)
        {
            int             height  = Convert.ToInt32(web.ActualHeight);
            int             width   = Convert.ToInt32(web.ActualWidth);
            WriteableBitmap bitmap  = new WriteableBitmap(width, height);
            BitmapDecoder   decoder = await BitmapDecoder.CreateAsync(source);

            BitmapTransform transform = new BitmapTransform();

            transform.ScaledHeight = (uint)height;
            transform.ScaledWidth  = (uint)width;
            PixelDataProvider pixelData = await decoder.GetPixelDataAsync(
                BitmapPixelFormat.Bgra8,
                BitmapAlphaMode.Straight,
                transform,
                ExifOrientationMode.RespectExifOrientation,
                ColorManagementMode.DoNotColorManage);

            pixelData.DetachPixelData().CopyTo(bitmap.PixelBuffer);
            var savefile = await ApplicationData.Current.LocalFolder.CreateFileAsync("inkSample", CreationCollisionOption.ReplaceExisting);

            using (IRandomAccessStream stream = await savefile.OpenAsync(FileAccessMode.ReadWrite))
            {
                BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);

                Stream pixelStream = bitmap.PixelBuffer.AsStream();
                byte[] pixels      = new byte[pixelStream.Length];
                await pixelStream.ReadAsync(pixels, 0, pixels.Length);

                encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)bitmap.PixelWidth, (uint)bitmap.PixelHeight, 96.0, 96.0, pixels);
                await encoder.FlushAsync();
            }
            return(bitmap);
        }
Example #15
0
        public static async Task ToArray(this StorageFile file, IOutputArray result, ImreadModes modes = ImreadModes.AnyColor | ImreadModes.AnyDepth)
        {
            using (IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
            {
                BitmapDecoder decoder = await BitmapDecoder.CreateAsync(fileStream);

                Size s = new Size((int)decoder.PixelWidth, (int)decoder.PixelHeight);

                BitmapTransform   transform = new BitmapTransform();
                PixelDataProvider pixelData = await decoder.GetPixelDataAsync(
                    BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, transform, ExifOrientationMode.IgnoreExifOrientation,
                    ColorManagementMode.DoNotColorManage);

                byte[]   sourcePixels = pixelData.DetachPixelData();
                GCHandle handle       = GCHandle.Alloc(sourcePixels, GCHandleType.Pinned);
                using (Image <Bgra, Byte> img = new Image <Bgra, byte>(s.Width, s.Height, s.Width * 4, handle.AddrOfPinnedObject()))
                {
                    if (modes.HasFlag(ImreadModes.Grayscale))
                    {
                        CvInvoke.CvtColor(img, result, ColorConversion.Bgra2Gray);
                    }
                    else
                    {
                        CvInvoke.CvtColor(img, result, ColorConversion.Bgra2Bgr);
                    }

                    handle.Free();
                }
            }
        }
Example #16
0
        private async void openFile_click(object sender, RoutedEventArgs e)
        {
            FileOpenPicker openPicker = new FileOpenPicker();

            openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            openPicker.FileTypeFilter.Add(".png");
            openPicker.FileTypeFilter.Add(".jpeg");
            openPicker.FileTypeFilter.Add(".jpg");
            openPicker.FileTypeFilter.Add(".bmp");

            StorageFile file = await openPicker.PickSingleFileAsync();

            if (file != null)
            {
                using (IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
                {
                    BitmapDecoder decoder = await BitmapDecoder.CreateAsync(fileStream);

                    OryginalWriteableBitmapMainImage = new WriteableBitmap((int)decoder.PixelWidth, (int)decoder.PixelHeight);
                    WriteableBitmapMainImage         = new WriteableBitmap((int)decoder.PixelWidth, (int)decoder.PixelHeight);

                    OryginalLayer_Image.Source = OryginalWriteableBitmapMainImage;
                    FilteredLayer_Image.Source = WriteableBitmapMainImage;

                    BitmapTransform transform = new BitmapTransform()
                    {
                        ScaledWidth  = Convert.ToUInt32(WriteableBitmapMainImage.PixelWidth),
                        ScaledHeight = Convert.ToUInt32(WriteableBitmapMainImage.PixelHeight)
                    };


                    PixelDataProvider pixelData = await decoder.GetPixelDataAsync(
                        BitmapPixelFormat.Bgra8,
                        BitmapAlphaMode.Straight,
                        transform,
                        ExifOrientationMode.IgnoreExifOrientation,
                        ColorManagementMode.DoNotColorManage);

                    byte[] sourcePixels = pixelData.DetachPixelData();
                    orygPixels = (byte[])sourcePixels.Clone();

                    // copy pixels to filtered layer
                    using (Stream stream = WriteableBitmapMainImage.PixelBuffer.AsStream())
                    {
                        await stream.WriteAsync(sourcePixels, 0, sourcePixels.Length);

                        fileName_textBlock.Text = file.Name;
                    }

                    // copy pixels to oryginal layer
                    using (Stream stream = OryginalWriteableBitmapMainImage.PixelBuffer.AsStream())
                    {
                        await stream.WriteAsync(orygPixels, 0, sourcePixels.Length);
                    }
                }

                WriteableBitmapMainImage.Invalidate();
                OryginalWriteableBitmapMainImage.Invalidate();
            }
        }
Example #17
0
        public async void LoadBitmap(string name)
        {
            StorageFile srcfile = await StorageFile.GetFileFromApplicationUriAsync(new Uri(name));

            using (IRandomAccessStream fileStream = await srcfile.OpenAsync(Windows.Storage.FileAccessMode.Read))
            {
                BitmapDecoder decoder = await BitmapDecoder.CreateAsync(fileStream);

                BitmapTransform transform = new BitmapTransform()
                {
                    ScaledWidth  = 8,
                    ScaledHeight = 8
                };
                PixelDataProvider pixelData = await decoder.GetPixelDataAsync(
                    BitmapPixelFormat.Bgra8,
                    BitmapAlphaMode.Straight,
                    transform,
                    ExifOrientationMode.IgnoreExifOrientation,
                    ColorManagementMode.DoNotColorManage
                    );

                byte[] sourcePixels = pixelData.DetachPixelData();
                byte[] hatPixels    = new byte[192];

                for (int i = 0; i < (sourcePixels.Length / 4) / 8; i++)
                {
                    MapToHat(hatPixels, i * 8 * 3, sourcePixels, i * 8 * 4);
                }
                WriteLEDMatrix(hatPixels);
            }
        }
Example #18
0
    private async Task <WriteableBitmap> ReadAsync()
    {
        // 파일로부터 IRandomAccessStream를 가져오고
        using (IRandomAccessStream stream = await _file.OpenAsync(FileAccessMode.ReadWrite))
        {
            //BitmapDecoder로 이미지를 가져온다
            BitmapDecoder decoder = await BitmapDecoder.CreateAsync(BitmapDecoder.JpegDecoderId, stream);

            uint width  = decoder.PixelWidth;
            uint height = decoder.PixelHeight;
            if (_angle % 180 != 0)
            {
                width  = decoder.PixelHeight;
                height = decoder.PixelWidth;
            }
            // 그런 다음 사진을 조작하여 변형을 반영한다.
            BitmapTransform transform = new BitmapTransform
            {
                Rotation = rotation_angles[_angle]
            };
            // PixelDataProvider를 이용하여 사진을 회전
            PixelDataProvider data = await decoder.GetPixelDataAsync(
                BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, transform,
                ExifOrientationMode.IgnoreExifOrientation, ColorManagementMode.DoNotColorManage);

            _bitmap = new WriteableBitmap((int)width, (int)height);
            // 이후 정보를 파일에 다시 기록하여 회전된 이미지를 생성
            byte[] buffer = data.DetachPixelData();
            using (Stream pixels = _bitmap.PixelBuffer.AsStream())
            {
                pixels.Write(buffer, 0, (int)pixels.Length);
            }
        }
        return(_bitmap);
    }
        public async static Task <BitmapHolder> ToBitmapHolderAsync(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);

                PixelDataProvider pixelDataProvider = await decoder.GetPixelDataAsync();

                var   bytes = pixelDataProvider.DetachPixelData();
                int[] array = new int[decoder.PixelWidth * decoder.PixelHeight];
                CopyPixels(bytes, array);

                return(new BitmapHolder(array, (int)decoder.PixelWidth, (int)decoder.PixelHeight));
            }
        }
Example #20
0
        async private static Task <byte[]> GetCroppedPixelsAsync(IRandomAccessStream stream, FaceRectangle rectangle)
        {
            // Create a decoder from the stream. With the decoder, we can get
            // the properties of the image.
            BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);

            // Create cropping BitmapTransform and define the bounds.
            BitmapTransform transform = new BitmapTransform();
            BitmapBounds    bounds    = new BitmapBounds();

            bounds.X         = (uint)rectangle.Left;
            bounds.Y         = (uint)rectangle.Top;
            bounds.Height    = (uint)rectangle.Height;
            bounds.Width     = (uint)rectangle.Width;
            transform.Bounds = bounds;

            // Get the cropped pixels within the bounds of transform.
            PixelDataProvider pix = await decoder.GetPixelDataAsync(
                BitmapPixelFormat.Bgra8,
                BitmapAlphaMode.Straight,
                transform,
                ExifOrientationMode.IgnoreExifOrientation,
                ColorManagementMode.ColorManageToSRgb);

            return(pix.DetachPixelData());
        }
Example #21
0
        /// <summary>
        /// Use BitmapTransform to define the region to crop, and then get the pixel data in the region.
        /// If you want to get the pixel data of a scaled image, set the scaledWidth and scaledHeight
        /// of the scaled image.
        /// </summary>
        async static private Task <byte[]> GetPixelData(BitmapDecoder decoder, uint startPointX, uint startPointY,
                                                        uint width, uint height, uint scaledWidth, uint scaledHeight)
        {
            BitmapTransform transform = new BitmapTransform();
            BitmapBounds    bounds    = new BitmapBounds();

            bounds.X         = startPointX;
            bounds.Y         = startPointY;
            bounds.Height    = height;
            bounds.Width     = width;
            transform.Bounds = bounds;

            transform.ScaledWidth  = scaledWidth;
            transform.ScaledHeight = scaledHeight;

            // Get the cropped pixels within the bounds of transform.
            PixelDataProvider pix = await decoder.GetPixelDataAsync(
                BitmapPixelFormat.Bgra8,
                BitmapAlphaMode.Straight,
                transform,
                ExifOrientationMode.IgnoreExifOrientation,
                ColorManagementMode.ColorManageToSRgb);

            byte[] pixels = pix.DetachPixelData();
            return(pixels);
        }
Example #22
0
        /// <summary>
        /// 读取照片流 转为WriteableBitmap给二维码解码器
        /// </summary>
        /// <param name="fileStream"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public async static Task <WriteableBitmap> ReadBitmap(IRandomAccessStream fileStream, string type)
        {
            WriteableBitmap bitmap = null;

            try
            {
                Guid          decoderId = DecoderIDFromFileExtension(type);
                BitmapDecoder decoder   = await BitmapDecoder.CreateAsync(decoderId, fileStream);

                BitmapTransform tf     = new BitmapTransform();
                uint            width  = decoder.OrientedPixelWidth;
                uint            height = decoder.OrientedPixelHeight;
                double          dScale = 1;
                if (decoder.OrientedPixelWidth > MaxSizeSupported.Width || decoder.OrientedPixelHeight > MaxSizeSupported.Height)
                {
                    dScale          = Math.Min(MaxSizeSupported.Width / decoder.OrientedPixelWidth, MaxSizeSupported.Height / decoder.OrientedPixelHeight);
                    width           = (uint)(decoder.OrientedPixelWidth * dScale);
                    height          = (uint)(decoder.OrientedPixelHeight * dScale);
                    tf.ScaledWidth  = (uint)(decoder.PixelWidth * dScale);
                    tf.ScaledHeight = (uint)(decoder.PixelHeight * dScale);
                }
                bitmap = new WriteableBitmap((int)width, (int)height);
                PixelDataProvider dataprovider = await decoder.GetPixelDataAsync(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, tf,
                                                                                 ExifOrientationMode.RespectExifOrientation, ColorManagementMode.DoNotColorManage);

                byte[] pixels       = dataprovider.DetachPixelData();
                Stream pixelStream2 = bitmap.PixelBuffer.AsStream();
                pixelStream2.Write(pixels, 0, pixels.Length);
                //bitmap.SetSource(fileStream);
            }
            catch
            {
            }
            return(bitmap);
        }
        async protected override void OnTapped(TappedRoutedEventArgs args)
        {
            if (ignoreTaps)
            {
                return;
            }

            // Capture photo to memory stream
            ImageEncodingProperties    imageEncodingProps = ImageEncodingProperties.CreateJpeg();
            InMemoryRandomAccessStream memoryStream       = new InMemoryRandomAccessStream();
            await mediaCapture.CapturePhotoToStreamAsync(imageEncodingProps, memoryStream);

            // Use BitmapDecoder to get pixels array
            BitmapDecoder decoder = await BitmapDecoder.CreateAsync(memoryStream);

            PixelDataProvider pixelProvider = await decoder.GetPixelDataAsync();

            byte[] pixels = pixelProvider.DetachPixelData();

            // Saturate the colors
            for (int index = 0; index < pixels.Length; index += 4)
            {
                Color color = Color.FromArgb(pixels[index + 3],
                                             pixels[index + 2],
                                             pixels[index + 1],
                                             pixels[index + 0]);
                HSL hsl = new HSL(color);
                hsl   = new HSL(hsl.Hue, 1.0, hsl.Lightness);
                color = hsl.Color;

                pixels[index + 0] = color.B;
                pixels[index + 1] = color.G;
                pixels[index + 2] = color.R;
                pixels[index + 3] = color.A;
            }

            // Create a WriteableBitmap and initialize it
            WriteableBitmap bitmap = new WriteableBitmap((int)decoder.PixelWidth,
                                                         (int)decoder.PixelHeight);
            Stream pixelStream = bitmap.PixelBuffer.AsStream();
            await pixelStream.WriteAsync(pixels, 0, pixels.Length);

            bitmap.Invalidate();

            // Display the bitmap
            image.Source = bitmap;

            // Set a timer for the image
            DispatcherTimer timer = new DispatcherTimer
            {
                Interval = TimeSpan.FromSeconds(2.5)
            };

            timer.Tick += OnTimerTick;
            timer.Start();
            ignoreTaps = true;

            base.OnTapped(args);
        }
Example #24
0
        private async void CUButton_Click(object sender, RoutedEventArgs e)
        {
            if (title.Text == "")
            {
                var i = new MessageDialog("Title Empty!").ShowAsync();
                return;
            }
            if (detail.Text == "")
            {
                var i = new MessageDialog("Detail Empty!").ShowAsync();
                return;
            }
            if (date.Date.Date < DateTime.Today.Date)
            {
                var i = new MessageDialog("Invalid Date!").ShowAsync();
                return;
            }

            if (CUButton.Content.ToString() == "Create")
            {
                WriteableBitmap defaultimage = null;
                StorageFile     file         = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/background.jpg"));

                if (file != null)
                {
                    using (IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
                    {
                        BitmapDecoder bitmapDecoder = await BitmapDecoder.CreateAsync(fileStream);

                        BitmapTransform   dummyTransform    = new BitmapTransform();
                        PixelDataProvider pixelDataProvider =
                            await bitmapDecoder.GetPixelDataAsync(BitmapPixelFormat.Bgra8,
                                                                  BitmapAlphaMode.Premultiplied, dummyTransform,
                                                                  ExifOrientationMode.RespectExifOrientation,
                                                                  ColorManagementMode.ColorManageToSRgb);

                        byte[] pixelData = pixelDataProvider.DetachPixelData();

                        defaultimage = new WriteableBitmap(
                            (int)bitmapDecoder.OrientedPixelWidth,
                            (int)bitmapDecoder.OrientedPixelHeight);
                        using (Stream pixelStream = defaultimage.PixelBuffer.AsStream())
                        {
                            await pixelStream.WriteAsync(pixelData, 0, pixelData.Length);
                        }
                    }
                }
                ViewModel.AddTodoItem(title.Text, detail.Text, defaultimage, date.Date.DateTime);
                //Frame.Navigate(typeof(MainPage), ViewModel);
            }
            else
            {
                ViewModel.UpdateTodoItem(ViewModel.SelectedItem.id, title.Text, detail.Text, date.Date.DateTime);
                CUButton.Content = "Create";
                //Frame.Navigate(typeof(MainPage), ViewModel);
            }
        }
Example #25
0
        public static async Task <WriteableBitmap> Resize(StorageFile file, double sizeMax)
        {
            IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read);

            BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);

            double sourceWidth  = (double)decoder.PixelWidth;
            double sourceHeight = (double)decoder.PixelHeight;
            double width        = sourceWidth;
            double height       = sourceHeight;

            bool   needResize = false;
            double WtoH       = sourceWidth / sourceHeight;

            if (WtoH > 1d)//width is longer
            {
                if (sourceWidth > sizeMax)
                {
                    width      = sizeMax;
                    height     = width * sourceHeight / sourceWidth;
                    needResize = true;
                }
            }
            else//height is longer
            {
                if (sourceHeight > sizeMax)
                {
                    height     = sizeMax;
                    width      = height * sourceWidth / sourceHeight;
                    needResize = true;
                }
            }

            WriteableBitmap wb = null;

            wb = new WriteableBitmap((int)width, (int)height);
            if (needResize)
            {
                BitmapTransform transform = new BitmapTransform()
                {
                    ScaledWidth  = (uint)width,
                    ScaledHeight = (uint)height
                };

                PixelDataProvider pixelData = await decoder.GetPixelDataAsync(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore,
                                                                              transform, ExifOrientationMode.IgnoreExifOrientation, ColorManagementMode.DoNotColorManage);

                byte[] pixelBuffer = pixelData.DetachPixelData();
                wb = wb.FromByteArray(pixelBuffer);
            }
            else
            {
                wb.SetSource(stream);
            }

            return(wb);
        }
Example #26
0
        public IAsyncInfo GenerateGif(StorageFile outputFile, int delay, bool repeat, List <byte[]> sourceBytes)
        {
            return(AsyncInfo.Run(async ctx =>
            {
                var outStream = await outputFile.OpenAsync(FileAccessMode.ReadWrite);

                BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.GifEncoderId, outStream);

                if (repeat)     // set repeat property
                {
                    var containerProperties = new BitmapPropertySet
                    {
                        { "/appext/Application", new BitmapTypedValue(Encoding.UTF8.GetBytes("NETSCAPE2.0"), PropertyType.UInt8Array) },
                        { "/appext/Data", new BitmapTypedValue(new byte[] { 3, 1, 0, 0, 0 }, PropertyType.UInt8Array) },
                    };

                    await encoder.BitmapContainerProperties.SetPropertiesAsync(containerProperties);
                }

                try
                {
                    for (int i = 0; i < sourceBytes.Count; i++)
                    {
                        using (MemoryRandomAccessStream frameStream = new MemoryRandomAccessStream(sourceBytes[i]))
                        {
                            BitmapDecoder decoder = await BitmapDecoder.CreateAsync(frameStream);
                            PixelDataProvider pixels = await decoder.GetPixelDataAsync();

                            encoder.SetPixelData(decoder.BitmapPixelFormat, BitmapAlphaMode.Ignore,
                                                 decoder.OrientedPixelWidth, decoder.OrientedPixelHeight,
                                                 decoder.DpiX, decoder.DpiY,
                                                 pixels.DetachPixelData());

                            if (i == 0)
                            {
                                var properties = new BitmapPropertySet {
                                    { "/grctlext/Delay", new BitmapTypedValue(delay / 10, PropertyType.UInt16) }
                                };
                                await encoder.BitmapProperties.SetPropertiesAsync(properties);
                            }

                            if (i < sourceBytes.Count - 1)
                            {
                                await encoder.GoToNextFrameAsync();
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine("exception caught: " + ex.ToString());
                    //   throw ex;
                }
                await encoder.FlushAsync();
                outStream.Dispose();
            }));
        }
Example #27
0
        public async Task <StorageFile> GetCroppedBitmapAsync1(StorageFile savedStorageFile,
                                                               uint startPointX, uint startPointY, uint width, uint height, double scale)
        {
            using (IRandomAccessStream stream = await savedStorageFile.OpenReadAsync())
            {
                BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);

                uint scaledWidth  = (uint)Math.Floor(decoder.PixelWidth * scale);
                uint scaledHeight = (uint)Math.Floor(decoder.PixelHeight * scale);

                BitmapTransform transform = new BitmapTransform();
                BitmapBounds    bounds    = new BitmapBounds();
                bounds.X         = startPointX;
                bounds.Y         = startPointY;
                bounds.Height    = height;
                bounds.Width     = width;
                transform.Bounds = bounds;

                PixelDataProvider pix = await decoder.GetPixelDataAsync(
                    BitmapPixelFormat.Bgra8,
                    BitmapAlphaMode.Straight,
                    transform,
                    ExifOrientationMode.IgnoreExifOrientation,
                    ColorManagementMode.ColorManageToSRgb);


                byte[] pixels = pix.DetachPixelData();


                // Stream the bytes into a WriteableBitmap
                WriteableBitmap cropBmp = new WriteableBitmap((int)width, (int)height);

                Stream pixStream = cropBmp.PixelBuffer.AsStream();
                pixStream.Write(pixels, 0, (int)(width * height * 4));

                var  fileName          = Guid.NewGuid() + "Bps1.jpg";
                Guid bitMapEncoderGuid = BitmapEncoder.JpegEncoderId;
                var  file = await ApplicationData.Current.TemporaryFolder.CreateFileAsync(fileName,
                                                                                          CreationCollisionOption.GenerateUniqueName);

                using (var irStream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    // var bmenc = await BitmapEncoder.CreateAsync(bitMapEncoderGuid, irStream);
                    var bmenc = await BitmapEncoder.CreateForTranscodingAsync(irStream, decoder);

                    Stream sstrm = cropBmp.PixelBuffer.AsStream();
                    byte[] pxls  = new byte[sstrm.Length];
                    await sstrm.ReadAsync(pxls, 0, pxls.Length);

                    bmenc.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied, (uint)cropBmp.PixelWidth,
                                       (uint)cropBmp.PixelHeight, scaledWidth, scaledHeight, pxls);
                    await bmenc.FlushAsync();
                }
                return(file);
            }
        }
        async Task ColorizeCustomButtonAsync(Windows.UI.Color newColor)
        {
            // Get the bitmap from the png
            var         sourceUri   = new Uri("ms-appx:///Assets/ButtonIconFill.png");
            StorageFile storageFile = await StorageFile.GetFileFromApplicationUriAsync(sourceUri);

            using (IRandomAccessStream readableStream = await storageFile.OpenAsync(FileAccessMode.Read))
            {
                BitmapDecoder bitmapDecoder = await BitmapDecoder.CreateAsync(readableStream);

                // Get the raw pixel data from the bitmap
                var dummyTransform = new BitmapTransform();
                PixelDataProvider pixelDataProvider = await bitmapDecoder.GetPixelDataAsync(
                    BitmapPixelFormat.Bgra8,
                    BitmapAlphaMode.Straight,
                    dummyTransform,
                    ExifOrientationMode.RespectExifOrientation,
                    ColorManagementMode.DoNotColorManage);

                byte[] pixelData = pixelDataProvider.DetachPixelData();

                // We now have direct access to the pixels.
                for (uint row = 0; row < bitmapDecoder.PixelHeight; row++)
                {
                    for (uint col = 0; col < bitmapDecoder.PixelWidth; col++)
                    {
                        var offset = (row * (int)bitmapDecoder.PixelWidth * 4) + (col * 4);

                        // Replace the pixel with newColor if it is our color key.
                        if ((pixelData[offset] <= 0x01) &&
                            (pixelData[offset + 1] <= 0x01) &&
                            (pixelData[offset + 2] <= 0x01) &&
                            (pixelData[offset + 3] != 0x00))
                        {
                            pixelData[offset]     = newColor.B;
                            pixelData[offset + 1] = newColor.G;
                            pixelData[offset + 2] = newColor.R;
                            pixelData[offset + 3] = newColor.A;
                        }
                    }
                }

                // Create a bitmap from our modified pixel data.
                var bitmap = new WriteableBitmap((int)bitmapDecoder.PixelWidth, (int)bitmapDecoder.PixelHeight);

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

                    pixelStream.Flush();
                    bitmap.Invalidate();
                }

                CustomButtonFill.Source = bitmap;
            }
        }
Example #29
0
        public async Task <Byte[]> ImageFileToByteArray(StorageFile file)
        {
            IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read);

            BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);

            PixelDataProvider pixelData = await decoder.GetPixelDataAsync();

            return(pixelData.DetachPixelData());
        }
Example #30
0
        // Zone File

        public async void LoadFile(ushort[] photo, uint w, uint h, string name)
        {
            StorageFile srcfile = await StorageFile.GetFileFromApplicationUriAsync(new Uri(name));

            using (IRandomAccessStream fileStream = await srcfile.OpenAsync(Windows.Storage.FileAccessMode.Read))
            {
                BitmapDecoder decoder = await BitmapDecoder.CreateAsync(fileStream);

                BitmapTransform transform = new BitmapTransform()
                {
                    ScaledWidth  = Convert.ToUInt32(w),
                    ScaledHeight = Convert.ToUInt32(h)
                };

                PixelDataProvider pixelData = await decoder.GetPixelDataAsync(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, transform, ExifOrientationMode.IgnoreExifOrientation, ColorManagementMode.DoNotColorManage);

                byte[] sourcePixels = pixelData.DetachPixelData();

                if (sourcePixels.Length == w * h * 4)
                {
                    int  pi = 0;
                    int  i = 0;
                    byte red = 0, green = 0, blue = 0;

                    foreach (byte b in sourcePixels)
                    {
                        switch (i)
                        {
                        case 0:
                            blue = b;
                            break;

                        case 1:
                            green = b;
                            break;

                        case 2:
                            red = b;
                            break;

                        case 3:
                            photo[pi] = RGB888ToRGB565(red, green, blue);
                            pi++;
                            break;
                        }

                        i = (i + 1) % 4;
                    }
                }
                else
                {
                    return;
                }
            }
        }