Beispiel #1
0
        public async Task <SoftwareBitmap> GetSampleBitmap()
        {
            FileOpenPicker fileOpenPicker = new FileOpenPicker();

            fileOpenPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            fileOpenPicker.FileTypeFilter.Add(".jpg");
            fileOpenPicker.ViewMode = PickerViewMode.Thumbnail;

            var inputFile = await fileOpenPicker.PickSingleFileAsync();

            if (inputFile == null)
            {
                // The user cancelled the picking operation
                return(null);
            }
            using (IRandomAccessStream stream = await inputFile.OpenAsync(FileAccessMode.Read))
            {
                // Create the decoder from the stream
                BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);

                // Get the SoftwareBitmap representation of the file
                return(await decoder.GetSoftwareBitmapAsync());
            }
        }
Beispiel #2
0
        /// <summary>
        /// Decode an image file into a VideoFrame
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        private async Task GetFrameFromFileAsync(StorageFile file)
        {
            // Decoding image file content into a SoftwareBitmap, and wrap into VideoFrame
            SoftwareBitmap softwareBitmap = null;

            using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read))
            {
                // Create the decoder from the stream
                BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);

                // Get the SoftwareBitmap representation of the file in BGRA8 format
                softwareBitmap = await decoder.GetSoftwareBitmapAsync();

                // Convert to preferred format if specified and encapsulate the image in a VideoFrame instance
                var convertedSoftwareBitmap = m_desiredImageDescriptor == null?SoftwareBitmap.Convert(softwareBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore)
                                                  : SoftwareBitmap.Convert(softwareBitmap, m_desiredImageDescriptor.SupportedBitmapPixelFormat, m_desiredImageDescriptor.SupportedBitmapAlphaMode);

                m_videoFrame = VideoFrame.CreateWithSoftwareBitmap(convertedSoftwareBitmap);
            }

            // Extract frame dimensions
            FrameWidth  = (uint)softwareBitmap.PixelWidth;
            FrameHeight = (uint)softwareBitmap.PixelHeight;
        }
        private async Task <string> ReencodeAndSavePhotoAsync(IRandomAccessStream stream, PhotoOrientation photoOrientation)
        {
            using (var inputStream = stream)
            {
                var decoder = await BitmapDecoder.CreateAsync(inputStream);

                var file = await ApplicationData.Current.LocalFolder.CreateFileAsync("photo.jpeg", CreationCollisionOption.GenerateUniqueName);

                using (var outputStream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    var encoder = await BitmapEncoder.CreateForTranscodingAsync(outputStream, decoder);

                    var properties = new BitmapPropertySet {
                        { "System.Photo.Orientation", new BitmapTypedValue(photoOrientation, PropertyType.UInt16) }
                    };

                    await encoder.BitmapProperties.SetPropertiesAsync(properties);

                    await encoder.FlushAsync();
                }

                return(file.Path);
            }
        }
Beispiel #4
0
            public async Task <ImageSource> InitializeAsync(IRandomAccessStream streamSource)
            {
                var bitmapDecoder = await BitmapDecoder.CreateAsync(BitmapDecoder.GifDecoderId, streamSource);

                var imageProperties = await RetrieveImagePropertiesAsync(bitmapDecoder);

                var frameProperties = new List <FrameProperties>();

                for (var i = 0u; i < bitmapDecoder.FrameCount; i++)
                {
                    var bitmapFrame = await bitmapDecoder.GetFrameAsync(i);

                    frameProperties.Add(await RetrieveFramePropertiesAsync(bitmapFrame));
                }

                _frameProperties = frameProperties;
                _bitmapDecoder   = bitmapDecoder;
                _imageProperties = imageProperties;

                CreateCanvasResources();

                _isInitialized = true;
                return(_canvasImageSource);
            }
Beispiel #5
0
        private async void SetImportPath(object sender, RoutedEventArgs e)
        {
            FileOpenPicker fileOpenPicker = new FileOpenPicker
            {
                ViewMode = PickerViewMode.Thumbnail,
                SuggestedStartLocation = PickerLocationId.PicturesLibrary
            };

            fileOpenPicker.FileTypeFilter.Add(".bmp");

            StorageFile image = await fileOpenPicker.PickSingleFileAsync();

            if (image != null)
            {
                using (IRandomAccessStream stream = await image.OpenAsync(FileAccessMode.Read))
                {
                    BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);

                    this.PixelData = await decoder.GetPixelDataAsync();

                    this.Bitmap = await decoder.GetSoftwareBitmapAsync();

                    if (this.Bitmap.BitmapPixelFormat != BitmapPixelFormat.Bgra8 || this.Bitmap.BitmapAlphaMode == BitmapAlphaMode.Straight)
                    {
                        this.Bitmap = SoftwareBitmap.Convert(this.Bitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied);
                    }
                }
                SoftwareBitmapSource source = new SoftwareBitmapSource();
                await source.SetBitmapAsync(this.Bitmap);

                this.ImagePreview.Source   = source;
                this.ImportName            = image.Name;
                this.ImportPath.Text       = image.Path;
                this.StartButton.IsEnabled = true;
            }
        }
Beispiel #6
0
        /// <inheritdoc/>
        public async Task <string> WriteBitmapAsync(Stream stream, string nameWithExt)
        {
            StorageFile storageFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(
                nameWithExt,
                CreationCollisionOption.ReplaceExisting);

            // ref: https://codedocu.com/Details?d=1592&a=9&f=181&l=0&v=d
            using (IRandomAccessStream s = stream.AsRandomAccessStream())
            {
                // Create the decoder from the stream
                BitmapDecoder decoder = await BitmapDecoder.CreateAsync(s);

                // Get the SoftwareBitmap representation of the file
                var softwareBitmap = await decoder.GetSoftwareBitmapAsync();

                BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, await storageFile.OpenAsync(FileAccessMode.ReadWrite));

                encoder.SetSoftwareBitmap(softwareBitmap);

                await encoder.FlushAsync();

                return(storageFile.Path);
            }
        }
Beispiel #7
0
        /// <summary>
        ///     Extracts the pixel data from file.
        /// </summary>
        /// <param name="file">The file.</param>
        /// <returns>The byte array of pixel information from the file</returns>
        public static async Task <byte[]> ExtractPixelDataFromFile(StorageFile file)
        {
            var copyBitmapImage = await FileBitmapConverter.ConvertFileToBitmap(file);

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

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

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

                return(pixelData.DetachPixelData());
            }
        }
Beispiel #8
0
        private async Task<StorageFile> RescaleImage(StorageFile sourceFile, StorageFile resizedImageFile, uint width, uint height)
        {
            var writeableBitmap = new WriteableBitmap(1, 1);
            using (var stream = await sourceFile.OpenReadAsync())
                await writeableBitmap.SetSourceAsync(stream);
            using (var imageStream = await sourceFile.OpenReadAsync())
            {
                var decoder = await BitmapDecoder.CreateAsync(imageStream);
                using (var sourceStream = writeableBitmap.PixelBuffer.AsStream())
                using (var resizedStream = await resizedImageFile.OpenAsync(FileAccessMode.ReadWrite))
                {
                    var buffer = new byte[sourceStream.Length];
                    await sourceStream.ReadAsync(buffer, 0, buffer.Length);
                    var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, resizedStream);
                    encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied, width, height, 96.0, 96.0, buffer);

                    encoder.BitmapTransform.InterpolationMode = BitmapInterpolationMode.NearestNeighbor;
                    encoder.BitmapTransform.ScaledWidth = width;
                    encoder.BitmapTransform.ScaledHeight = height;
                    await encoder.FlushAsync();
                }
            }
            return resizedImageFile;
        }
        private async Task <Stream> ConvertToJpeg(IRandomAccessStream stream)
        {
            var decoder = await BitmapDecoder.CreateAsync(stream);

            var pixels = await decoder.GetPixelDataAsync();

            var outStream = new InMemoryRandomAccessStream();
            // create encoder for saving the tile image
            var propertySet = new BitmapPropertySet();
            // create class representing target jpeg quality - a bit obscure, but it works
            var qualityValue = new BitmapTypedValue(.7, PropertyType.Single);

            propertySet.Add("ImageQuality", qualityValue);

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

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

            return(outStream.AsStream());
        }
Beispiel #10
0
        private static async Task <string> OCRInternal(Bitmap bmp, string languageTag)
        {
            Language language = new Language(languageTag);

            if (!OcrEngine.IsLanguageSupported(language))
            {
                throw new Exception($"{language.LanguageTag} is not supported in this system.");
            }

            OcrEngine engine = OcrEngine.TryCreateFromLanguage(language);

            using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream())
            {
                bmp.Save(stream.AsStream(), ImageFormat.Bmp);
                BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);

                using (SoftwareBitmap softwareBitmap = await decoder.GetSoftwareBitmapAsync())
                {
                    OcrResult ocrResult = await engine.RecognizeAsync(softwareBitmap);

                    return(string.Join("\r\n", ocrResult.Lines.Select(x => x.Text)));
                }
            }
        }
Beispiel #11
0
        private async void SaveEdit(object sender, RoutedEventArgs e)
        {
            if (grdImageEditor.DataContext != null && grdImageEditor.DataContext is ViewImageEditorMetadata)
            {
                using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream())
                {
                    // get bits from edited image
                    await imgCropper.SaveAsync(stream, BitmapFileFormat.Jpeg, true);

                    BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);

                    var editedBitmap = await decoder.GetSoftwareBitmapAsync();

                    // create bitmaps for persisting in models
                    var source = new SoftwareBitmapSource();
                    await source.SetBitmapAsync(FixBitmapForBGRA8(editedBitmap));

                    // store bitmap in models
                    var currentSelectedSnapshot = (ViewImageEditorMetadata)grdImageEditor.DataContext;
                    currentSelectedSnapshot.Bitmap = editedBitmap;
                    currentSelectedSnapshot.Source = source;

                    // force col to be updated
                    for (int i = 0; i < snapshots.Count(); i++)
                    {
                        if (snapshots[i].Number == currentSelectedSnapshot.Number)
                        {
                            snapshots[i] = currentSelectedSnapshot;
                            break;
                        }
                    }

                    SendSystemNotification("Snapshot updated!");
                }
            }
        }
Beispiel #12
0
        private async void AppBarButton_Click(object sender, RoutedEventArgs e)
        {
            FileOpenPicker openPicker = new FileOpenPicker();

            openPicker.ViewMode = PickerViewMode.Thumbnail;
            openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            openPicker.FileTypeFilter.Add(".jpg");
            openPicker.FileTypeFilter.Add(".jpeg");
            openPicker.FileTypeFilter.Add(".png");
            openPicker.FileTypeFilter.Add(".gif");
            openPicker.FileTypeFilter.Add(".tiff");
            openPicker.FileTypeFilter.Add(".bmp");

            StorageFile file = await openPicker.PickSingleFileAsync();

            CurrentPic = file;
            if (file != null)
            {
                SoftwareBitmap      softwareBitmap;
                IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read);

                BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);

                softwareBitmap = await decoder.GetSoftwareBitmapAsync();

                if (softwareBitmap.BitmapPixelFormat != BitmapPixelFormat.Bgra8 ||
                    softwareBitmap.BitmapAlphaMode == BitmapAlphaMode.Straight)
                {
                    softwareBitmap = SoftwareBitmap.Convert(softwareBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied);
                }
                var source = new SoftwareBitmapSource();
                await source.SetBitmapAsync(softwareBitmap);

                personPic.ProfilePicture = source;
            }
        }
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            //File picker
            var fileOpenPicker = new FileOpenPicker();

            fileOpenPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            fileOpenPicker.FileTypeFilter.Add(".bmp");
            fileOpenPicker.FileTypeFilter.Add(".jpg");
            fileOpenPicker.FileTypeFilter.Add(".png");
            fileOpenPicker.ViewMode = PickerViewMode.Thumbnail;
            var selectedStorageFile = await fileOpenPicker.PickSingleFileAsync();

            //Check file selected
            if (selectedStorageFile == null)
            {
                return;
            }
            SoftwareBitmap softwareBitmap;

            using (var stream = await selectedStorageFile.OpenAsync(FileAccessMode.Read))

            {
                // Create the decoder from the stream
                var decoder = await BitmapDecoder.CreateAsync(stream);

                // Get the SoftwareBitmap representation of the file in BGRA8 format
                softwareBitmap = await decoder.GetSoftwareBitmapAsync();

                softwareBitmap = SoftwareBitmap.Convert(softwareBitmap, BitmapPixelFormat.Bgra8,
                                                        BitmapAlphaMode.Premultiplied);
            }

            var inputImage = VideoFrame.CreateWithSoftwareBitmap(softwareBitmap);

            EvaluateVideoFrameAsync(inputImage);
        }
Beispiel #14
0
        private async Task <SoftwareBitmap> CreateFromBitmap(SoftwareBitmap softwareBitmap, uint width, uint heigth, byte[] data)
        {
            using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream())
            {
                BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);


                encoder.SetSoftwareBitmap(softwareBitmap);
                encoder.BitmapTransform.InterpolationMode = BitmapInterpolationMode.Linear;

                var ancho = width * (0.2);
                var alto  = heigth * (0.2);


                encoder.BitmapTransform.ScaledWidth  = (uint)ancho;
                encoder.BitmapTransform.ScaledHeight = (uint)alto;

                await encoder.FlushAsync();

                BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);

                return(await decoder.GetSoftwareBitmapAsync(softwareBitmap.BitmapPixelFormat, softwareBitmap.BitmapAlphaMode));
            }
        }
Beispiel #15
0
        // http://stackoverflow.com/questions/39618846/xamarin-forms-image-to-from-irandomaccessstreamreference/39632398#39632398
        public static async Task <RandomAccessStreamReference> ScaleTo(this IRandomAccessStreamReference imageStream, uint width, uint height)
        {
            using (IRandomAccessStream fileStream = await imageStream.OpenReadAsync())
            {
                var decoder = await BitmapDecoder.CreateAsync(fileStream);

                //create a RandomAccessStream as output stream
                var memStream = new InMemoryRandomAccessStream();

                //creates a new BitmapEncoder and initializes it using data from an existing BitmapDecoder
                BitmapEncoder encoder = await BitmapEncoder.CreateForTranscodingAsync(memStream, decoder);

                //resize the image
                encoder.BitmapTransform.ScaledWidth       = width;
                encoder.BitmapTransform.ScaledHeight      = height;
                encoder.BitmapTransform.InterpolationMode = BitmapInterpolationMode.Cubic;

                //commits and flushes all of the image data
                await encoder.FlushAsync();

                //return the output stream as RandomAccessStreamReference
                return(RandomAccessStreamReference.CreateFromStream(memStream));
            }
        }
Beispiel #16
0
        public static async Task <List <ColorThiefDotNet.QuantizedColor> > GeneratePalette(Uri path)
        {
            if (path == null)
            {
                throw new ArgumentNullException();
            }
            //get the file
            if (path.IsFile)
            {
                var file = await StorageFile.GetFileFromPathAsync(path.LocalPath);

                using (IRandomAccessStream stream = await file.OpenReadAsync())
                {
                    var decoder = await BitmapDecoder.CreateAsync(stream);

                    return(await colorThief.GetPalette(decoder, 8, 1, false));
                }
            }
            else
            {
                try
                {
                    RandomAccessStreamReference random = RandomAccessStreamReference.CreateFromUri(path);
                    using (IRandomAccessStream stream = await random.OpenReadAsync())
                    {
                        var decoder = await BitmapDecoder.CreateAsync(stream);

                        return(await colorThief.GetPalette(decoder, 8, 1, false));
                    }
                }
                catch (Exception)
                {
                    return(null);
                }
            }
        }
Beispiel #17
0
        /*
         * Metodo responsavel por capturar uma imagem e enviar a MainPage
         * Mais informações: https://docs.microsoft.com/pt-br/windows/uwp/audio-video-camera/capture-photos-and-video-with-cameracaptureui
         */
        private async void take_photo(object sender, RoutedEventArgs e)
        {
            try
            {
                //Captura assincrona
                photo = await this.captureUI.CaptureFileAsync(CameraCaptureUIMode.Photo);

                // Se o Usuario cancelou a captura da foto
                if (photo == null)
                {
                    return;
                }
                else
                {
                    //Carrego a foto
                    this.imageStream = await photo.OpenAsync(FileAccessMode.Read);

                    BitmapDecoder decoder = await BitmapDecoder.CreateAsync(imageStream);

                    SoftwareBitmap softBitmap = await decoder.GetSoftwareBitmapAsync();

                    //Converto com as exigencias de exibição na pagina XAML
                    SoftwareBitmap       softBitmapBGR8 = SoftwareBitmap.Convert(softBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied);
                    SoftwareBitmapSource bitmapSource   = new SoftwareBitmapSource();
                    await bitmapSource.SetBitmapAsync(softBitmapBGR8);

                    //Anexo ao campo "image" a foto armazenada
                    image.Source = bitmapSource;
                }
            }
            catch
            {
                //Envio a mensagem de erro pelo campo text que criei na tela
                output.Text = "Erro: taking photo";
            }
        }
Beispiel #18
0
    private static async Task <WriteableBitmap> read()
    {
        using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read))
        {
            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;
            }
            Dictionary <int, BitmapRotation> angles = new Dictionary <int, BitmapRotation>()
            {
                { 0, BitmapRotation.None },
                { 90, BitmapRotation.Clockwise90Degrees },
                { 180, BitmapRotation.Clockwise180Degrees },
                { 270, BitmapRotation.Clockwise270Degrees },
                { 360, BitmapRotation.None }
            };
            BitmapTransform transform = new BitmapTransform();
            transform.Rotation = angles[angle];
            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);
    }
        private async void DetectObjectPoseFromPicFile(StorageFile inputFile)
        {
            openedFile = inputFile;
            var file = inputFile;

            //var transform = new BitmapTransform() { ScaledWidth = 416, ScaledHeight = 416, InterpolationMode = BitmapInterpolationMode.Fant };

            using (var stream = await file.OpenAsync(FileAccessMode.Read))
            {
                BitmapSource bitmapSource = new BitmapImage();
                bitmapSource.SetSource(stream);
                InputImage.Source = bitmapSource;

                BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);

                using (var imageTensor = await ConvertImageToTensorAsync(decoder).ConfigureAwait(true))
                    using (var input = new SingelObjectApeModelV8Input()
                    {
                        Image = imageTensor
                    })
                        using (var output = await model.EvaluateAsync(input).ConfigureAwait(true))
                        {
                            var            shape     = output.Grid.Shape;
                            var            content   = output.Grid.GetAsVectorView().ToArray();
                            List <float[]> rawOutput = new List <float[]>
                            {
                                content
                            };
                            using (OutputParser outputParser = new OutputParser(rawOutput, classCount, anchorCount, confThresh))
                            {
                                var boxes = outputParser.BoundingBoxes;
                                DrawBoxes(stream, boxes);
                            }
                        }
            }
        }
Beispiel #20
0
        //public static async Task<byte[]> SaveToBytesAsync(ImageSource imageSource)
        //{
        //    BitmapImage source = imageSource as BitmapImage;

        //    StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(source.UriSource);
        //    using (var inputStream = await file.OpenSequentialReadAsync())
        //    {
        //        var readStream = inputStream.AsStreamForRead();

        //        var byteArray = new byte[readStream.Length];
        //        await readStream.ReadAsync(byteArray, 0, byteArray.Length);
        //        return byteArray;
        //    }
        //}

        //public static byte[] SavetoBytes(ImageSource imageSource)
        //{
        //    WriteableBitmap source = imageSource as WriteableBitmap;
        //    var byteArray = source.PixelBuffer;
        //    return byteArray.ToArray();
        //}

        //public static byte[] ImageSourceToBytes(BitmapEncoder encoder, ImageSource imageSource)
        //{
        //    byte[] bytes = null;
        //    var bitmapSource = imageSource as BitmapSource;

        //    if (bitmapSource != null)
        //    {
        //        encoder.Frames.Add(BitmapFrame.Create(bitmapSource));

        //        using (var stream = new MemoryStream())
        //        {
        //            encoder.Save(stream);
        //            bytes = stream.ToArray();
        //        }
        //    }

        //    return bytes;
        //}
        //public static Byte[] ImageToByte(WriteableBitmap imageSource)
        //{
        //    Stream stream = imageSource.PixelBuffer.AsStream();
        //    Byte[] buffer = null;
        //    if (stream != null && stream.Length > 0)
        //    {
        //        using (BinaryReader br = new BinaryReader(stream))
        //        {
        //            buffer = br.ReadBytes((Int32)stream.Length);
        //        }
        //    }

        //    return buffer;
        //}

        public static async Task <ImageSource> SaveToImageSource(byte[] imageBuffer)
        {
            ImageSource imageSource = null;

            try
            {
                using (MemoryStream stream = new MemoryStream(imageBuffer))
                {
                    var           ras     = stream.AsRandomAccessStream();
                    BitmapDecoder decoder = await BitmapDecoder.CreateAsync(BitmapDecoder.JpegDecoderId, ras);

                    var provider = await decoder.GetPixelDataAsync();

                    byte[]          buffer = provider.DetachPixelData();
                    WriteableBitmap bitmap = new WriteableBitmap((int)decoder.PixelWidth, (int)decoder.PixelHeight);
                    await bitmap.PixelBuffer.AsStream().WriteAsync(buffer, 0, buffer.Length);

                    imageSource = bitmap;
                }
                //using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream())
                //{
                //    using (DataWriter writer = new DataWriter(stream.GetOutputStreamAt(0)))
                //    {
                //        writer.WriteBytes(imageBuffer);
                //        await writer.StoreAsync();
                //    }
                //    BitmapImage image = new BitmapImage();
                //    await image.SetSourceAsync(stream);
                //    return image;
                //}
            }
            catch (Exception ex)
            {
            }
            return(imageSource);
        }
        /// <summary>
        /// Loads the data from an image stream and returns a new WriteableBitmap.
        /// </summary>
        /// <param name="stream">The stream with the image data.</param>
        /// <param name="pixelFormat">The pixel format of the stream data. If Unknown is provided as param, the default format of the BitmapDecoder is used.</param>
        /// <returns>A new WriteableBitmap containing the pixel data.</returns>
        public static async Task <WriteableBitmap> FromStream(IRandomAccessStream stream, BitmapPixelFormat pixelFormat = BitmapPixelFormat.Unknown)
        {
            var decoder = await BitmapDecoder.CreateAsync(stream);

            var transform = new BitmapTransform();

            if (pixelFormat == BitmapPixelFormat.Unknown)
            {
                pixelFormat = decoder.BitmapPixelFormat;
            }
            var pixelData = await decoder.GetPixelDataAsync(pixelFormat, decoder.BitmapAlphaMode, transform, ExifOrientationMode.RespectExifOrientation, ColorManagementMode.ColorManageToSRgb);

            var pixels = pixelData.DetachPixelData();

            // Copy to WriteableBitmap
            var bmp = new WriteableBitmap((int)decoder.OrientedPixelWidth, (int)decoder.OrientedPixelHeight);

            using (var bmpStream = bmp.PixelBuffer.AsStream())
            {
                bmpStream.Seek(0, SeekOrigin.Begin);
                bmpStream.Write(pixels, 0, (int)bmpStream.Length);
                return(bmp);
            }
        }
Beispiel #22
0
        private async void cancelButton_Click(object sender, RoutedEventArgs e)
        {
            title.Text  = "";
            detail.Text = "";
            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);
                    }
                }
            }
            image.Source           = defaultimage;
            date.Date              = DateTime.Today;
            ViewModel.SelectedItem = null;
            CUButton.Content       = "Create";
        }
Beispiel #23
0
        public static async Task <StorageFile> TranscodeAsync(IRandomAccessStream imageStream, StorageFile resizedImageFile, Guid encoderId)
        {
            var decoder = await BitmapDecoder.CreateAsync(imageStream);

            //if (decoder.FrameCount > 1)
            //{
            //    throw new InvalidCastException();
            //}

            var originalPixelWidth  = decoder.PixelWidth;
            var originalPixelHeight = decoder.PixelHeight;

            using (var resizedStream = await resizedImageFile.OpenAsync(FileAccessMode.ReadWrite))
            {
                var pixelData = await decoder.GetSoftwareBitmapAsync(decoder.BitmapPixelFormat, decoder.BitmapAlphaMode, new BitmapTransform(), ExifOrientationMode.RespectExifOrientation, ColorManagementMode.DoNotColorManage);

                var encoder = await BitmapEncoder.CreateAsync(encoderId, resizedStream);

                encoder.SetSoftwareBitmap(pixelData);
                await encoder.FlushAsync();
            }

            return(resizedImageFile);
        }
        private async void OnDeferredImageRequestedHandler(DataProviderRequest request)
        {
            // In this delegate we provide updated Bitmap data using delayed rendering.

            if (_imageFile != null)
            {
                // If the delegate is calling any asynchronous operations it needs to acquire
                // the deferral first. This lets the system know that you are performing some
                // operations that might take a little longer and that the call to SetData
                // could happen after the delegate returns. Once you acquired the deferral object
                // you must call Complete on it after your final call to SetData.
                DataProviderDeferral       deferral       = request.GetDeferral();
                InMemoryRandomAccessStream inMemoryStream = new InMemoryRandomAccessStream();

                // Make sure to always call Complete when finished with the deferral.
                try
                {
                    // Decode the image and re-encode it at 50% width and height.
                    IRandomAccessStream imageStream = await _imageFile.OpenAsync(FileAccessMode.Read);

                    BitmapDecoder imageDecoder = await BitmapDecoder.CreateAsync(imageStream);

                    BitmapEncoder imageEncoder = await BitmapEncoder.CreateForTranscodingAsync(inMemoryStream, imageDecoder);

                    imageEncoder.BitmapTransform.ScaledWidth  = (uint)(imageDecoder.OrientedPixelWidth * 0.5);
                    imageEncoder.BitmapTransform.ScaledHeight = (uint)(imageDecoder.OrientedPixelHeight * 0.5);
                    await imageEncoder.FlushAsync();

                    request.SetData(RandomAccessStreamReference.CreateFromStream(inMemoryStream));
                }
                finally
                {
                    deferral.Complete();
                }
            }
        }
Beispiel #25
0
        private async void TranscodeImage_Click(object sender, RoutedEventArgs e)
        {
            FileSystemStorageFile Item = PhotoCollection[Flip.SelectedIndex].PhotoFile;

            TranscodeImageDialog Dialog = null;

            using (IRandomAccessStream OriginStream = await Item.GetRandomAccessStreamFromFileAsync(FileAccessMode.Read).ConfigureAwait(true))
            {
                BitmapDecoder Decoder = await BitmapDecoder.CreateAsync(OriginStream);

                Dialog = new TranscodeImageDialog(Decoder.PixelWidth, Decoder.PixelHeight);
            }

            if (await Dialog.ShowAsync().ConfigureAwait(true) == ContentDialogResult.Primary)
            {
                TranscodeLoadingControl.IsLoading = true;

                await GeneralTransformer.TranscodeFromImageAsync(Item, Dialog.TargetFile, Dialog.IsEnableScale, Dialog.ScaleWidth, Dialog.ScaleHeight, Dialog.InterpolationMode).ConfigureAwait(true);

                await Task.Delay(1000).ConfigureAwait(true);

                TranscodeLoadingControl.IsLoading = false;
            }
        }
        private async void Gif(IRandomAccessStream fileStream)
        {
            BitmapDecoder decoder = await BitmapDecoder.CreateAsync(fileStream);

            BitmapFrame frame = await decoder.GetFrameAsync(0);

            var frameProperties = await frame.BitmapProperties.GetPropertiesAsync(new List <string>());

            var imageDescriptionProperties = await(frameProperties["/imgdesc"].Value as BitmapPropertiesView).GetPropertiesAsync(new List <string>()
            {
                "/Top", "/Left", "/Width", "/Height"
            });
            int top    = Int32.Parse(imageDescriptionProperties["/Top"].Value.ToString());
            int left   = Int32.Parse(imageDescriptionProperties["/Left"].Value.ToString());
            int width  = Int32.Parse(imageDescriptionProperties["/Width"].Value.ToString());
            int height = Int32.Parse(imageDescriptionProperties["/Height"].Value.ToString());

            var gifControlExtensionProperties = await(frameProperties["/grctlext"].Value as BitmapPropertiesView).GetPropertiesAsync(new List <string>()
            {
                "/Delay", "/UserInputFlag"
            });
            TimeSpan delay         = TimeSpan.FromSeconds(Double.Parse(gifControlExtensionProperties["/Delay"].Value.ToString()) / 100); // delay is in 1/100s of a second
            bool     userInputFlag = bool.Parse(gifControlExtensionProperties["/UserInputFlag"].Value.ToString());
        }
Beispiel #27
0
        public static async Task <Mat> 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()))
                {
                    Mat m = new Mat();
                    CvInvoke.CvtColor(img, m, ColorConversion.Bgra2Bgr);
                    handle.Free();
                    return(m);
                }
            }
        }
Beispiel #28
0
        private async void zrobFoto()
        {
            CameraCaptureUI captureUI = new CameraCaptureUI();

            captureUI.PhotoSettings.Format = CameraCaptureUIPhotoFormat.Jpeg;
            captureUI.PhotoSettings.CroppedSizeInPixels = new Size(400, 400);
            captureUI.PhotoSettings.AllowCropping       = true;

            // nasza apka czeka, na zrobienie zdjęcia prze aplikację CameraCaptureUI
            photo = await captureUI.CaptureFileAsync(CameraCaptureUIMode.Photo);

            if (photo == null)
            {
                // Gdy klikniemy cancel na aplikacji do robienia zdjęć
                return;
            }

            // ciąg bitów ze zdjęcia
            IRandomAccessStream stream = await photo.OpenAsync(FileAccessMode.Read);

            // dekodujemy na bitmapę
            BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);

            // zmieniamy rodzaj bitmapy na software
            SoftwareBitmap softwareBitmap = await decoder.GetSoftwareBitmapAsync();

            // konwertujemy bitmape na taką, która nam odpowiada do tego zadania
            SoftwareBitmap softwareBitmapBGR8 = SoftwareBitmap.Convert(softwareBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied);

            // ustawaimy obiekt typu źródło bitmap i wciskamy tam nasze wcześniej skonwertowane zdjęcie
            SoftwareBitmapSource bitmapSource = new SoftwareBitmapSource();
            await bitmapSource.SetBitmapAsync(softwareBitmapBGR8);

            // na koniec przypisujemy zdjęcie do kontrolki aby wyświetlić
            imageControl.Source = bitmapSource;
        }
Beispiel #29
0
        public static async Task <StorageFile> SaveCacheFile(this IRandomAccessStreamReference reference,
                                                             string name = null)
        {
            var file = await ApplicationData.Current.LocalCacheFolder.CreateFileAsync(name ?? $"{new Random().Next()}.jpg", CreationCollisionOption.GenerateUniqueName);

            using (var fstream = await file.OpenStreamForWriteAsync())
            {
                using var stream = await reference.OpenReadAsync();

                var decoder = await BitmapDecoder.CreateAsync(stream);

                var pixels = await decoder.GetPixelDataAsync();

                var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, fstream.AsRandomAccessStream());

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

            return(file);
        }
Beispiel #30
0
        private static async Task <TileImageCollection> CreateTileImages(Uri imageUri)
        {
            var file = await StorageFile.GetFileFromApplicationUriAsync(imageUri);

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

            WriteableBitmap squareBitmap, wideBitmap;

            (Point squarePoint, Size squareSize) = GetCropDetails(decoder, 1.0);
            squareBitmap = await CropBitmap.GetCroppedBitmapAsync(file, squarePoint, squareSize, 1.0);

            (Point widePoint, Size wideSize) = GetCropDetails(decoder, 310.0 / 150.0);
            wideBitmap = await CropBitmap.GetCroppedBitmapAsync(file, widePoint, wideSize, 1.0);

            var squareFile = await ImageSaveHelper.SaveWritableBitmapToTileImageCache(squareBitmap, "square");

            var wideFile = await ImageSaveHelper.SaveWritableBitmapToTileImageCache(wideBitmap, "wide");

            return(new TileImageCollection
            {
                SquareImage = squareFile,
                WideImage = wideFile,
            });
        }