Esempio n. 1
0
        /// <summary>
        /// Write the location metadata to the image file
        /// </summary>
        public async static Task WriteSurveyPhotoMetaData(StorageFile file, Geoposition pos, string surveyId = "")
        {
            using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                var decoder = await BitmapDecoder.CreateAsync(stream);
                var encoder = await BitmapEncoder.CreateForTranscodingAsync(stream, decoder);
                
                // Write the gps data
                var propertySet = new BitmapPropertySet();
                var latitudeNumerator = new BitmapTypedValue(CoordDoubleToIntArray(pos.Coordinate.Latitude), PropertyType.Int32Array);
                var latitudeRef = new BitmapTypedValue("N", PropertyType.String);
                var longitudeNumerator = new BitmapTypedValue(CoordDoubleToIntArray(pos.Coordinate.Longitude), PropertyType.Int32Array);
                var longitudeRef = new BitmapTypedValue("W", PropertyType.String);

                propertySet.Add("System.GPS.LatitudeNumerator", latitudeNumerator);
                propertySet.Add("System.GPS.LatitudeRef", latitudeRef);
                propertySet.Add("System.GPS.LatitudeDenominator", new BitmapTypedValue(new [] { 1, 1, 10000 }, PropertyType.Int32Array));

                propertySet.Add("System.GPS.LongitudeNumerator", longitudeNumerator);
                propertySet.Add("System.GPS.LongitudeRef", longitudeRef);
                propertySet.Add("System.GPS.LongitudeDenominator", new BitmapTypedValue(new[] { 1, 1, 10000 }, PropertyType.Int32Array));

                // Write the surveyId data
                if (!string.IsNullOrEmpty(surveyId))
                {
                    var surveyIdTyped = new BitmapTypedValue(surveyId, Windows.Foundation.PropertyType.String);
                    propertySet.Add("System.Comment", surveyIdTyped);
                }

                await encoder.BitmapProperties.SetPropertiesAsync(propertySet);
                await encoder.FlushAsync();
            }
        }
 private BitmapPropertySet CreateBitmapPropertySet()
 {
     var propertySet = new BitmapPropertySet();
     var qualityValue = new BitmapTypedValue(configuration.VideoQuality, PropertyType.Single);
     propertySet.Add("ImageQuality", qualityValue);
     return propertySet;
 }
 private void OnStreamingValueChanged(object sender, bool e)
 {
     if (properties == null)
     {
         properties = CreateBitmapPropertySet();
     }
 }
Esempio n. 4
0
        internal static async Task LoadTileImageInternalAsync(string imagePath)
        {
            string tileName = "dreaming";
            uint MaxImageWidth =360;
            uint MaxImageHeight = 600;

            StorageFile origFile = await ApplicationData.Current.LocalFolder.GetFileAsync(imagePath);

            // open file for the new tile image file
            StorageFile tileFile = await Windows.Storage.KnownFolders.PicturesLibrary.CreateFileAsync(tileName, CreationCollisionOption.GenerateUniqueName);
            using (IRandomAccessStream tileStream = await tileFile.OpenAsync(FileAccessMode.ReadWrite))
            {
                // get width and height from the original image
                IRandomAccessStreamWithContentType stream = await origFile.OpenReadAsync();
                ImageProperties properties = await origFile.Properties.GetImagePropertiesAsync();
                uint width = properties.Width;
                uint height = properties.Height;

                // get proper decoder for the input file - jpg/png/gif
                BitmapDecoder decoder = await GetProperDecoder(stream, origFile );
                if (decoder == null) return; // should not happen
                // get byte array of actual decoded image
                PixelDataProvider data = await decoder.GetPixelDataAsync();
                byte[] bytes = data.DetachPixelData();

                // create encoder for saving the tile image
                BitmapPropertySet propertySet = new BitmapPropertySet();
                // create class representing target jpeg quality - a bit obscure, but it works
                BitmapTypedValue qualityValue = new BitmapTypedValue(0.5, PropertyType.Single);
                propertySet.Add("ImageQuality", qualityValue);
                // create the target jpeg decoder
                BitmapEncoder be = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, tileStream, propertySet);
                be.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Straight, width, height, 96.0, 96.0, bytes);

                // crop the image, if it's too big
                if (width > MaxImageWidth || height > MaxImageHeight)
                {
                    BitmapBounds bounds = new BitmapBounds();
                    if (width > MaxImageWidth)
                    {
                        bounds.Width = MaxImageWidth;
                        bounds.X = (width - MaxImageWidth) / 2;
                    }
                    else bounds.Width = width;
                    if (height > MaxImageHeight)
                    {
                        bounds.Height = MaxImageHeight;
                        bounds.Y = (height - MaxImageHeight) / 2;
                    }
                    else bounds.Height = height;
                    be.BitmapTransform.Bounds = bounds;
                }
                // save the target jpg to the file
                await be.FlushAsync();
            }
           
        }
Esempio n. 5
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();

            });
        }
        /// <summary>
        /// Encodes a WriteableBitmap object into a JPEG stream, with parameters for setting the target quality of the JPEG file.
        /// </summary>
        /// <param name="writeableBitmap">The WriteableBitmap object.</param>
        /// <param name="outputStream">The image data stream.</param>
        /// <param name="quality">This parameter represents the quality of the JPEG photo with a range between 0 and 100, with 100 being the best photo quality. We recommend that you do not fall lower than a value of 70. because JPEG picture quality diminishes significantly below that level. </param>
        /// <returns>The <see cref="Task"/> object representing the asynchronous operation.</returns>
        public static async Task SaveJpegAsync(this WriteableBitmap writeableBitmap, Stream outputStream, int quality)
        {
            var propertySet = new BitmapPropertySet
            {
                { "ImageQuality", new BitmapTypedValue(quality, PropertyType.Single) }
            };

            var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, outputStream.AsRandomAccessStream(), propertySet);
            var pixels = writeableBitmap.PixelBuffer.ToArray();

            encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied, (uint)writeableBitmap.PixelWidth, (uint)writeableBitmap.PixelHeight, ResolutionDpi, ResolutionDpi, pixels);

            await encoder.FlushAsync();
        }
Esempio n. 7
0
        private static async Task ReencodeAndSavePhotoAsync(IRandomAccessStream stream, StorageFile file, Windows.Storage.FileProperties.PhotoOrientation photoOrientation)
        {
            using (var inputStream = stream)
            {
                var decoder = await BitmapDecoder.CreateAsync(inputStream);

                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();
                }
            }
        }
        /// <summary>
        /// Converts SoftwareBitmap to base64 string
        /// </summary>
        /// <param name="bitmap"></param>
        /// <returns></returns>
        public static async Task <string> ConvertToBase64(SoftwareBitmap bitmap)
        {
            byte[] array  = null;
            string base64 = "";

            using (var ms = new InMemoryRandomAccessStream())
            {
                SoftwareBitmap compatibleBitmap = null;
                if (bitmap.BitmapPixelFormat != BitmapPixelFormat.Bgra8 ||
                    bitmap.BitmapAlphaMode != BitmapAlphaMode.Ignore)
                {
                    compatibleBitmap = SoftwareBitmap.Convert(bitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore);
                }
                else
                {
                    compatibleBitmap = bitmap;
                }
                var encodingOptions = new BitmapPropertySet();
                encodingOptions.Add("ImageQuality", new BitmapTypedValue(
                                        1.0, // Maximum quality
                                        Windows.Foundation.PropertyType.Single));

                BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, ms, encodingOptions);

                encoder.SetSoftwareBitmap(compatibleBitmap);

                try
                {
                    await encoder.FlushAsync();
                }
                catch (Exception ex) { }

                array = new byte[ms.Size];
                await ms.ReadAsync(array.AsBuffer(), (uint)ms.Size, InputStreamOptions.None);

                base64 = Convert.ToBase64String(array);
                compatibleBitmap.Dispose();
            }

            return(base64);
        }
        private static async Task <InMemoryRandomAccessStream> ReencodeAndSavePhotoAsync(IRandomAccessStream stream, PhotoOrientation photoOrientation)
        {
            using (var inputStream = stream)
            {
                var decoder = await BitmapDecoder.CreateAsync(inputStream);

                var memoryStream = new InMemoryRandomAccessStream();

                var encoder = await BitmapEncoder.CreateForTranscodingAsync(memoryStream, decoder);

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

                await encoder.BitmapProperties.SetPropertiesAsync(properties);

                await encoder.FlushAsync();

                return(memoryStream);
            }
        }
Esempio n. 10
0
        /// <summary>
        /// Encodes a WriteableBitmap object into a JPEG stream, with parameters for setting the target quality of the JPEG file.
        /// </summary>
        /// <param name="writeableBitmap">The WriteableBitmap object.</param>
        /// <param name="outputStream">The image data stream.</param>
        /// <param name="quality">This parameter represents the quality of the JPEG photo with a range between 0 and 100, with 100 being the best photo quality. We recommend that you do not fall lower than a value of 70. because JPEG picture quality diminishes significantly below that level. </param>
        /// <returns>The <see cref="Task"/> object representing the asynchronous operation.</returns>
        public static async Task SaveJpegAsync(this WriteableBitmap writeableBitmap, Stream outputStream, int quality)
        {
#if WINDOWS_PHONE
            writeableBitmap.SaveJpeg(outputStream, writeableBitmap.PixelWidth, writeableBitmap.PixelHeight, 0, quality);

            await Task.FromResult(0);
#else
            var propertySet = new BitmapPropertySet
            {
                { "ImageQuality", new BitmapTypedValue(quality, PropertyType.Single) }
            };

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

            var pixels = writeableBitmap.PixelBuffer.ToArray();

            encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied, (uint)writeableBitmap.PixelWidth, (uint)writeableBitmap.PixelHeight, ResolutionDpi, ResolutionDpi, pixels);

            await encoder.FlushAsync();
#endif
        }
Esempio n. 11
0
        private async Task<string> ReencodeAndSavePhotoAsync(IRandomAccessStream stream, PhotoOrientation photoOrientation)
        {
            using (var inputStream = stream)
            {
                var decoder = await BitmapDecoder.CreateAsync(inputStream);

                var file = await Package.Current.InstalledLocation.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;
            }
        }
Esempio n. 12
0
    public async void SendImage(byte[] image, int width, int height, bool logResult = false)
    {
        if (connected)
        {
#if !UNITY_EDITOR
            using (var stream = new InMemoryRandomAccessStream())
            {
                var propertySet = new BitmapPropertySet();
                propertySet.Add("ImageQuality", new BitmapTypedValue(0.5, Windows.Foundation.PropertyType.Single));
                var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream, propertySet);

                encoder.BitmapTransform.InterpolationMode = BitmapInterpolationMode.Cubic;
                encoder.BitmapTransform.ScaledHeight      = 320;
                encoder.BitmapTransform.ScaledWidth       = (uint)((float)width / height * encoder.BitmapTransform.ScaledHeight);
                encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)width, (uint)height, 72, 72, image);
                try
                {
                    await encoder.FlushAsync();
                }
                catch { LoggingManager.LogError("Couldn't encode image"); }

                var data = new byte[stream.Size];
                await stream.ReadAsync(data.AsBuffer(), (uint)stream.Size, InputStreamOptions.None);

                videoOut.WriteInt32((int)stream.Size);
                await videoOut.StoreAsync();

                videoOut.WriteBytes(data);
                await videoOut.StoreAsync();

                await videoOut.FlushAsync();

                if (logResult)
                {
                    LoggingManager.Log("Sent image of size " + stream.Size + " to " + serverName + " (" + serverAddress + ")");
                }
            }
#endif
        }
    }
        public async void TakePhotoAsync()
        {
            mediaCapture = new MediaCapture();
            await mediaCapture.InitializeAsync();

            //mediaCapture.Failed += MediaCapture_Failed;

            // Prepare and capture photo
            var lowLagCapture = await mediaCapture.PrepareLowLagPhotoCaptureAsync(ImageEncodingProperties.CreateUncompressed(MediaPixelFormat.Bgra8));

            var capturedPhoto = await lowLagCapture.CaptureAsync();

            var softwareBitmap = capturedPhoto.Frame.SoftwareBitmap;

            await lowLagCapture.FinishAsync();

            var myPictures = await Windows.Storage.StorageLibrary.GetLibraryAsync(Windows.Storage.KnownLibraryId.Pictures);

            StorageFile file = await myPictures.SaveFolder.CreateFileAsync("frontview.jpg", CreationCollisionOption.ReplaceExisting);

            using (var captureStream = new InMemoryRandomAccessStream())
            {
                await mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), captureStream);

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

                    var encoder = await BitmapEncoder.CreateForTranscodingAsync(fileStream, decoder);

                    var properties = new BitmapPropertySet {
                        { "System.Photo.Orientation", new BitmapTypedValue(PhotoOrientation.Normal, PropertyType.UInt16) }
                    };
                    await encoder.BitmapProperties.SetPropertiesAsync(properties);

                    await encoder.FlushAsync();
                }
            }
        }
Esempio n. 14
0
        private async void Capture_button_Click(object sender, RoutedEventArgs e)
        {
            _mediaCapture = new MediaCapture();
            await _mediaCapture.InitializeAsync();

            // Prepare and capture photo
            var lowLagCapture = await _mediaCapture.PrepareLowLagPhotoCaptureAsync(ImageEncodingProperties.CreateUncompressed(MediaPixelFormat.Bgra8));

            var capturedPhoto = await lowLagCapture.CaptureAsync();

            var softwareBitmap = capturedPhoto.Frame.SoftwareBitmap;

            await lowLagCapture.FinishAsync();

            var myPictures = await Windows.Storage.StorageLibrary.GetLibraryAsync(Windows.Storage.KnownLibraryId.Pictures);

            StorageFile file = await myPictures.SaveFolder.CreateFileAsync("photo.jpg", CreationCollisionOption.GenerateUniqueName);

            using (var captureStream = new InMemoryRandomAccessStream())
            {
                await _mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), captureStream);

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

                    var encoder = await BitmapEncoder.CreateForTranscodingAsync(fileStream, decoder);

                    var properties = new BitmapPropertySet {
                        { "System.Photo.Orientation", new BitmapTypedValue(PhotoOrientation.Normal, PropertyType.UInt16) }
                    };
                    await encoder.BitmapProperties.SetPropertiesAsync(properties);

                    await encoder.FlushAsync();
                }
            }

            Comfirmation.Text = "Picture Saved!";
        }
        /// <summary>
        /// Applies the given orientation to a photo stream and saves it as a StorageFile
        /// </summary>
        /// <param name="stream">The photo stream</param>
        /// <param name="photoOrientation">The orientation metadata to apply to the photo</param>
        /// <returns></returns>
        private static async Task ReencodeAndSavePhotoAsync(IRandomAccessStream stream, PhotoOrientation photoOrientation)
        {
            using (var inputStream = stream)
            {
                var decoder = await BitmapDecoder.CreateAsync(inputStream);

                var file = await KnownFolders.PicturesLibrary.CreateFileAsync("SimplePhoto.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();
                }
            }
        }
        private async void TakePhoto()
        {
            if (_mediaCapture != null && _isPreviewing)
            {
                // Start the animation
                captureButtonStoryboard.Begin();

                // Play the shutter sound
                string filename = @"Sounds\camera-sound.mp3";
                PlaySound(filename);

                StorageFile file = await Storage.CreateNewFile();

                using (var captureStream = new InMemoryRandomAccessStream())
                {
                    await _mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), captureStream);

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

                        var encoder = await BitmapEncoder.CreateForTranscodingAsync(fileStream, decoder);

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

                        await encoder.BitmapProperties.SetPropertiesAsync(properties);

                        await encoder.FlushAsync();

                        if (tsLocation.IsOn)
                        {
                            GeoTagImageFile(file);
                        }
                    }
                }
            }
        }
Esempio n. 17
0
        private async void EditFile(StorageFile file)
        {
            IRandomAccessStream ras = null;
            string name = "照片";
            try
            {
                ras = await file.OpenAsync(FileAccessMode.ReadWrite);
                BitmapDecoder decoder = await BitmapDecoder.CreateAsync(ras);

                try
                {
                    BitmapEncoder encoder = await BitmapEncoder.CreateForInPlacePropertyEncodingAsync(decoder);
                    var propertySet = new BitmapPropertySet
                    {
                        {"System.ApplicationName", new BitmapTypedValue(name, PropertyType.String)}
                    };
                    await encoder.BitmapProperties.SetPropertiesAsync(propertySet);
                    await encoder.FlushAsync();
                }
                catch (Exception e)
                {
                    BitmapEncoder encoder = await BitmapEncoder.CreateForTranscodingAsync(ras, decoder);
                    var propertySet = new BitmapPropertySet
                    {
                        {"System.ApplicationName", new BitmapTypedValue(name, PropertyType.String)}
                    };
                    await encoder.BitmapProperties.SetPropertiesAsync(propertySet);
                    await encoder.FlushAsync();
                }

            }
            catch (Exception e)
            {
            }
            finally
            {
                ras?.Dispose();
            }
        }
Esempio n. 18
0
        private async Task <byte[]> Bitmap2JPEG(SoftwareBitmap bitmap)
        {
            // JPEG quality
            var propertySet  = new BitmapPropertySet();
            var qualityValue = new BitmapTypedValue(
                0.67, // Maximum quality
                PropertyType.Single
                );

            propertySet.Add("ImageQuality", qualityValue);

            // JPEG compression into memory
            var           memStream = new InMemoryRandomAccessStream();
            BitmapEncoder encoder   = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, memStream, propertySet);

            // the SetSoftwareBitmap may cause a memory leak, but only for debugging (it's a bug in VS)
            // See http://stackoverflow.com/questions/35528030/bitmapencoder-memoryleak-with-softwarebitmap
            encoder.SetSoftwareBitmap(bitmap);
            await encoder.FlushAsync();

            // Send the data to network
            byte[] imageData;
            using (var inputStream = memStream.GetInputStreamAt(0))
            {
                using (var dataReader = new DataReader(inputStream))
                {
                    // Once we have written the contents successfully we load the stream.
                    await dataReader.LoadAsync((uint)memStream.Size);

                    imageData = new byte[(uint)memStream.Size];
                    dataReader.ReadBytes(imageData);
                }
            }

            // Clean...
            memStream.Dispose();

            return(imageData);
        }
        internal async void SaveImage()
        {
            try
            {
                var myPictures = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Pictures);

                var motionPictures = await myPictures.SaveFolder.CreateFolderAsync("MotionPictures", CreationCollisionOption.OpenIfExists);

                StorageFile file = await motionPictures.CreateFileAsync("motionPhoto.jpg", CreationCollisionOption.GenerateUniqueName);

                var stream = new InMemoryRandomAccessStream();

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

                encoder.SetSoftwareBitmap(MainPage.oldImg);
                await encoder.FlushAsync();

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

                    var encoder1 = await BitmapEncoder.CreateForTranscodingAsync(fileStream, decoder);

                    var properties = new BitmapPropertySet {
                        { "System.Photo.Orientation", new BitmapTypedValue(PhotoOrientation.Normal, PropertyType.UInt16) }
                    };
                    await encoder1.BitmapProperties.SetPropertiesAsync(properties);

                    await encoder1.FlushAsync();
                }

                //ms.Dispose();
                stream.Dispose();
            }
            catch (Exception)
            {
                //throw;
            }
        }
        /// <summary>
        /// Takes a photo to a StorageFile and adds rotation metadata to it
        /// </summary>
        /// <returns></returns>
        private async Task <StorageFile> SavePhotoAsync()
        {
            var file = await KnownFolders.PicturesLibrary.CreateFileAsync($"{Guid.NewGuid()}.jpeg", CreationCollisionOption.GenerateUniqueName);

            try
            {
                using (var stream = new InMemoryRandomAccessStream())
                    using (var inputStream = stream)
                        using (var outputStream = await file.OpenAsync(FileAccessMode.ReadWrite))
                        {
                            _log.WriteLine("Taking photo...");
                            await _mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream);

                            _log.WriteLine("Photo taken!");

                            var photoOrientation = ConvertOrientationToPhotoOrientation(GetCameraOrientation());

                            var decoder = await BitmapDecoder.CreateAsync(inputStream);

                            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);
                        }
            }
            catch (Exception ex)
            {
                _log.WriteLine($"Exception when taking a photo: {ex.ToString()}");
                throw;
            }
        }
Esempio n. 21
0
        private async void takeSnapBtn_Click(object sender, RoutedEventArgs e)
        {
            if (mediaCapture == null)
            {
                MessageDialog messageDialog = new MessageDialog("Please start camera");
                await messageDialog.ShowAsync();

                return;
            }

            using (mediaCapture)
            {
                var myPictures = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Pictures);

                StorageFile file = await myPictures.SaveFolder.CreateFileAsync("photo.jpg", CreationCollisionOption.GenerateUniqueName);

                using (var captureStream = new InMemoryRandomAccessStream())
                {
                    await mediaCapture.InitializeAsync();

                    await mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), captureStream);

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

                        var encoder = await BitmapEncoder.CreateForTranscodingAsync(fileStream, decoder);

                        var properties = new BitmapPropertySet {
                            { "System.Photo.Orientation", new BitmapTypedValue(PhotoOrientation.Normal, PropertyType.UInt16) }
                        };
                        await encoder.BitmapProperties.SetPropertiesAsync(properties);

                        await encoder.FlushAsync();
                    }
                }
            }
        }
        /// <summary>
        /// Takes a photo to a StorageFile and adds rotation metadata to it
        /// </summary>
        /// <returns></returns>
        private async Task TakePhotoAsync()
        {
            try
            {
                var stream = new InMemoryRandomAccessStream();
                Debug.WriteLine("Taking photo...");
                await _mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream);

                var photoOrientation = CameraRotationHelper.ConvertSimpleOrientationToPhotoOrientation(_rotationHelper.GetCameraCaptureOrientation());

                var decoder = await BitmapDecoder.CreateAsync(stream);

                var encoder = await BitmapEncoder.CreateForInPlacePropertyEncodingAsync(decoder);

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

                await encoder.FlushAsync();

                Debug.WriteLine("Photo saved in stream with orientation set!");

                using (var dr = new DataReader(stream.GetInputStreamAt(0)))
                {
                    var bytes = new byte[stream.Size];
                    await dr.LoadAsync((uint)stream.Size);

                    dr.ReadBytes(bytes);
                    SendEvent(deviceClient, Convert.ToBase64String(bytes));
                }
                stream.Dispose();
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Exception when taking a photo: " + ex.ToString());
            }
        }
        public static async Task <Stream> AsJpegStreamAsync(this WriteableBitmap bitmap, int quality = 90)
        {
            byte[] pixels;
            using (var stream = bitmap.PixelBuffer.AsStream())
            {
                pixels = new byte[(uint)stream.Length];
                await stream.ReadAsync(pixels, 0, pixels.Length);
            }

            var propertySet  = new BitmapPropertySet();
            var qualityValue = new BitmapTypedValue((double)quality / 100d, Windows.Foundation.PropertyType.Single);

            propertySet.Add("ImageQuality", qualityValue);

            var raStream = new InMemoryRandomAccessStream();
            // Encode pixels into stream
            var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, raStream, propertySet);

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

            return(raStream.AsStreamForRead());
        }
Esempio n. 24
0
        private async void captureBtn_Click(object sender, RoutedEventArgs e)
        {
            ////Sample Code 3
            captureStart = true;
            MediaCapture _mediaCapture;

            while (captureStart)
            {
                _mediaCapture = new MediaCapture();
                bool _isPreviewing;
                await _mediaCapture.InitializeAsync();

                //_mediaCapture.Failed += MediaCapture_Failed;
                var myPictures = await Windows.Storage.StorageLibrary.GetLibraryAsync(Windows.Storage.KnownLibraryId.Pictures);

                StorageFile file = await myPictures.SaveFolder.CreateFileAsync("photo.jpg", CreationCollisionOption.ReplaceExisting);

                using (var captureStream = new InMemoryRandomAccessStream())
                {
                    await _mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), captureStream);

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

                        var encoder = await BitmapEncoder.CreateForTranscodingAsync(fileStream, decoder);

                        var properties = new BitmapPropertySet {
                            { "System.Photo.Orientation", new BitmapTypedValue(PhotoOrientation.Normal, PropertyType.UInt16) }
                        };
                        await encoder.BitmapProperties.SetPropertiesAsync(properties);

                        await encoder.FlushAsync();
                    }
                }
            }
        }
        private static async Task EncodeImageAsync(ushort delayTime, BitmapEncoder encoder, ZipArchiveEntry entry)
        {
            using (var imageStream = entry.Open())
            {
                using (var pixelStream = new MemoryStream())
                {
                    await imageStream.CopyToAsync(pixelStream);

                    pixelStream.Seek(0, SeekOrigin.Begin);

                    var decoder = await BitmapDecoder.CreateAsync(pixelStream.AsRandomAccessStream());

                    var pixels = await decoder.GetPixelDataAsync();

                    encoder.SetPixelData(
                        decoder.BitmapPixelFormat,
                        BitmapAlphaMode.Ignore,
                        decoder.PixelWidth,
                        decoder.PixelHeight,
                        decoder.DpiX,
                        decoder.DpiY,
                        pixels.DetachPixelData());

                    var properties = new BitmapPropertySet
                    {
                        {
                            "/grctlext/Delay",
                            new BitmapTypedValue(delayTime / 10, PropertyType.UInt16)
                        }
                    };

                    await encoder.BitmapProperties.SetPropertiesAsync(properties);

                    await encoder.GoToNextFrameAsync();
                }
            }
        }
Esempio n. 26
0
        private async Task <Stream> ConvertToStreamAsync(WriteableBitmap bitmap)
        {
            var stream  = new InMemoryRandomAccessStream();
            var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);

            // Get pixels of the WriteableBitmap object
            var pixelStream = bitmap.PixelBuffer.AsStream();
            var pixels      = new byte[pixelStream.Length];
            await pixelStream.ReadAsync(pixels, 0, pixels.Length);

            // Save the image file with jpg extension
            encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)bitmap.PixelWidth, (uint)bitmap.PixelHeight, 96.0, 96.0, pixels);

            var photoOrientation = this.ConvertOrientationToPhotoOrientation(this.GetCameraOrientation());
            var properties       = new BitmapPropertySet {
                { "System.Photo.Orientation", new BitmapTypedValue(photoOrientation, PropertyType.UInt16) }
            };
            await encoder.BitmapProperties.SetPropertiesAsync(properties);

            await encoder.FlushAsync();

            stream.Seek(0);
            return(stream.AsStreamForRead());
        }
        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());
        }
Esempio n. 28
0
        /// <summary>
        /// Method that will generate an ObjectState for the provided deck information.
        /// </summary>
        /// <param name="deckCardIds">List of strings representing card Ids.</param>
        /// <param name="strBackCard">Direct image url representing the back of the card.</param>
        /// <returns>A ObjectState representing the deck.</returns>
        private async Task <ObjectState> generateDeck(List <string> deckCardIds, string strBackCard)
        {
            // Generate WriteableBitmaps for deck.
            Guid            BitmapEncoderGuid = BitmapEncoder.JpegEncoderId;
            WriteableBitmap deckBitmap        = await generateWriteableBitmapForDeck(deckCardIds);

            //var file = await Windows.Storage.ApplicationData.Current.TemporaryFolder.CreateFileAsync("combine.jpg", CreationCollisionOption.ReplaceExisting);
            using (IRandomAccessStream stream = new InMemoryRandomAccessStream())//await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                BitmapPropertySet propertySet = new BitmapPropertySet();
                BitmapTypedValue  quality     = new BitmapTypedValue(1.0, PropertyType.Single);
                propertySet.Add("ImageQuality", quality);
                BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoderGuid, stream, propertySet);

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

                encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)deckBitmap.PixelWidth, (uint)deckBitmap.PixelHeight, 96, 96, pixels);
                await encoder.FlushAsync();

                // Upload WriteableBitmaps to Imgur and save their direct urls (requires Imgur API).
                string deckUrl = await uploadPhotoToImgur(stream);

                // Get list of card names for deck.
                List <string> deckCardNames = await generateCardNamesForDeck(deckCardIds);

                // Get the number of rows and columns that are in the WriteableBitmap.
                Tuple <int, int> deckSize = getDeckSize(deckCardIds);

                // Build out ObjectState objects for deck.
                ObjectState deckObjectState = buildObjectState(deckCardIds, deckSize, deckUrl, strBackCard, deckCardNames, 1);

                return(deckObjectState);
            }
        }
        public async void CapturePhoto_Click(object sender, RoutedEventArgs e)
        {
            //Getting access to Pictures folder
            var myPictures = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Pictures);

            //Createing the file that will be saved
            StorageFile file = await myPictures.SaveFolder.CreateFileAsync("night-photo.jpg", CreationCollisionOption.GenerateUniqueName);

            //Capture a photo to the stream
            using (var captureStream = new InMemoryRandomAccessStream())
            {
                //Common encoding with JPEG format
                await _mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), captureStream);

                using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    //Decode the image from the memory stream
                    var decoder = await BitmapDecoder.CreateAsync(captureStream);

                    //Encode the image to file
                    var encoder = await BitmapEncoder.CreateForTranscodingAsync(fileStream, decoder);

                    //Getting the current orientation of the device
                    var photoOrientation = CameraRotationHelper.ConvertSimpleOrientationToPhotoOrientation(_rotationHelper.GetCameraCaptureOrientation());

                    //Including metadata about the photo in the image file
                    var properties = new BitmapPropertySet
                    {
                        { "System.Photo.Orientation", new BitmapTypedValue(photoOrientation, PropertyType.UInt16) }
                    };
                    await encoder.BitmapProperties.SetPropertiesAsync(properties);

                    await encoder.FlushAsync();
                }
            }
        }
Esempio n. 30
0
        private async void TakePhotoAsyncV2()
        {
            globalObject.SetCurrentFile(globalObject.GetPID().ToString("0000") + "-OH2019OriginalPhoto.jpg");
            StorageFile file = await storageFolder.CreateFileAsync(globalObject.GetCurrentFile(), CreationCollisionOption.GenerateUniqueName);

            using (var captureStream = new InMemoryRandomAccessStream())
            {
                await mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), captureStream);

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

                    var encoder = await BitmapEncoder.CreateForTranscodingAsync(fileStream, decoder);

                    var properties = new BitmapPropertySet {
                        { "System.Photo.Orientation", new BitmapTypedValue(PhotoOrientation.Normal, PropertyType.UInt16) }
                    };
                    await encoder.BitmapProperties.SetPropertiesAsync(properties);

                    await encoder.FlushAsync();
                }
            }
        }
        private async Task<IRandomAccessStream> ResizeJpegStreamAsync(int maxPixelDimension, int percentQuality, IRandomAccessStream input)
        {
            var decoder = await BitmapDecoder.CreateAsync(input);

            int targetHeight;
            int targetWidth;
            MvxPictureDimensionHelper.TargetWidthAndHeight(maxPixelDimension, (int)decoder.PixelWidth, (int)decoder.PixelHeight, out targetWidth, out targetHeight);

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

            var destinationStream = new InMemoryRandomAccessStream();
            var bitmapPropertiesSet = new BitmapPropertySet();
            bitmapPropertiesSet.Add("ImageQuality", new BitmapTypedValue(((double)percentQuality) / 100.0, PropertyType.Single));
            var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, destinationStream, bitmapPropertiesSet);
            encoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Premultiplied, (uint)targetWidth, (uint)targetHeight, decoder.DpiX, decoder.DpiY, pixelData.DetachPixelData());
            await encoder.FlushAsync();
            destinationStream.Seek(0L);
            return destinationStream;
        }
Esempio n. 32
0
        public static async Task <TLPhotoSizeBase> GetVideoThumbnailAsync(StorageFile file, VideoProperties props, VideoTransformEffectDefinition effect)
        {
            double originalWidth  = props.GetWidth();
            double originalHeight = props.GetHeight();

            if (effect != null && !effect.CropRectangle.IsEmpty)
            {
                file = await CropAsync(file, effect.CropRectangle);

                originalWidth  = effect.CropRectangle.Width;
                originalHeight = effect.CropRectangle.Height;
            }

            TLPhotoSizeBase result;
            var             fileLocation = new TLFileLocation
            {
                VolumeId = TLLong.Random(),
                LocalId  = TLInt.Random(),
                Secret   = TLLong.Random(),
                DCId     = 0
            };

            var desiredName = string.Format("{0}_{1}_{2}.jpg", fileLocation.VolumeId, fileLocation.LocalId, fileLocation.Secret);
            var desiredFile = await FileUtils.CreateTempFileAsync(desiredName);

            using (var fileStream = await OpenReadAsync(file))
                using (var outputStream = await desiredFile.OpenAsync(FileAccessMode.ReadWrite))
                {
                    var decoder = await BitmapDecoder.CreateAsync(fileStream);

                    double ratioX = (double)90 / originalWidth;
                    double ratioY = (double)90 / originalHeight;
                    double ratio  = Math.Min(ratioX, ratioY);

                    uint width  = (uint)(originalWidth * ratio);
                    uint height = (uint)(originalHeight * ratio);

                    var transform = new BitmapTransform();
                    transform.ScaledWidth       = width;
                    transform.ScaledHeight      = height;
                    transform.InterpolationMode = BitmapInterpolationMode.Linear;

                    if (effect != null)
                    {
                        transform.Flip = effect.Mirror == MediaMirroringOptions.Horizontal ? BitmapFlip.Horizontal : BitmapFlip.None;
                    }

                    var pixelData = await decoder.GetSoftwareBitmapAsync(decoder.BitmapPixelFormat, decoder.BitmapAlphaMode, transform, ExifOrientationMode.RespectExifOrientation, ColorManagementMode.DoNotColorManage);

                    var propertySet  = new BitmapPropertySet();
                    var qualityValue = new BitmapTypedValue(0.77, PropertyType.Single);
                    propertySet.Add("ImageQuality", qualityValue);

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

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

                    result = new TLPhotoSize
                    {
                        W        = (int)width,
                        H        = (int)height,
                        Size     = (int)outputStream.Size,
                        Type     = string.Empty,
                        Location = fileLocation
                    };
                }

            return(result);
        }
        private async Task DetectPhotoAsync(IRandomAccessStream stream, PhotoOrientation photoOrientation)
        {
            using (var inputStream = stream)
            {
                var decoder = await BitmapDecoder.CreateAsync(inputStream);

                var file = await KnownFolders.PicturesLibrary.CreateFileAsync("SimplePhoto.jpeg", CreationCollisionOption.GenerateUniqueName);

                using (var outputStream = new InMemoryRandomAccessStream())
                {
                    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();

                    var faces = await _instance.DetectAsync(outputStream.AsStream(), false, true, true, false);
                }
            }
        }
Esempio n. 34
0
        public static async Task <StorageFile> CropAsync(StorageFile sourceFile, StorageFile file, Rect cropRectangle, int min = 1280, int max = 0, double quality = 0.77, BitmapRotation rotation = BitmapRotation.None, BitmapFlip flip = BitmapFlip.None)
        {
            if (file == null)
            {
                file = await ApplicationData.Current.TemporaryFolder.CreateFileAsync("crop.jpg", CreationCollisionOption.ReplaceExisting);
            }

            using (var fileStream = await OpenReadAsync(sourceFile))
                using (var outputStream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    var decoder = await BitmapDecoder.CreateAsync(fileStream);

                    var cropWidth  = (double)decoder.PixelWidth;
                    var cropHeight = (double)decoder.PixelHeight;

                    if (decoder.PixelWidth > 1280 || decoder.PixelHeight > 1280)
                    {
                        double ratioX = 1280d / cropWidth;
                        double ratioY = 1280d / cropHeight;
                        double ratio  = Math.Min(ratioX, ratioY);

                        cropWidth  *= ratio;
                        cropHeight *= ratio;
                    }

                    cropRectangle = new Rect(
                        cropRectangle.X * decoder.PixelWidth,
                        cropRectangle.Y * decoder.PixelHeight,
                        cropRectangle.Width * decoder.PixelWidth,
                        cropRectangle.Height * decoder.PixelHeight);

                    if (rotation != BitmapRotation.None)
                    {
                        cropRectangle = RotateArea(cropRectangle, decoder.PixelWidth, decoder.PixelHeight, (int)rotation);
                    }

                    if (flip == BitmapFlip.Horizontal)
                    {
                        cropRectangle = FlipArea(cropRectangle, decoder.PixelWidth);
                    }

                    var(scaledCrop, scaledSize) = Scale(cropRectangle, new Size(decoder.PixelWidth, decoder.PixelHeight), new Size(cropWidth, cropHeight), min, max);

                    var bounds = new BitmapBounds();
                    bounds.X      = (uint)scaledCrop.X;
                    bounds.Y      = (uint)scaledCrop.Y;
                    bounds.Width  = (uint)scaledCrop.Width;
                    bounds.Height = (uint)scaledCrop.Height;

                    var transform = new BitmapTransform();
                    transform.ScaledWidth       = (uint)scaledSize.Width;
                    transform.ScaledHeight      = (uint)scaledSize.Height;
                    transform.Bounds            = bounds;
                    transform.InterpolationMode = BitmapInterpolationMode.Linear;
                    transform.Rotation          = rotation;
                    transform.Flip = flip;

                    var pixelData = await decoder.GetSoftwareBitmapAsync(decoder.BitmapPixelFormat, decoder.BitmapAlphaMode, transform, ExifOrientationMode.RespectExifOrientation, ColorManagementMode.DoNotColorManage);

                    var propertySet  = new BitmapPropertySet();
                    var qualityValue = new BitmapTypedValue(quality, PropertyType.Single);
                    propertySet.Add("ImageQuality", qualityValue);

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

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

            return(file);
        }
Esempio n. 35
0
        /// <summary>
        /// Applies the user-provided scale and rotation operation to the original image file.
        /// The "Transcoding" mode is used which preserves image metadata and performs other
        /// optimizations when possible.
        /// 
        /// This method attempts to perform "soft" rotation using the EXIF orientation flag when possible,
        /// but falls back to a hard rotation of the image pixels.
        /// </summary>
        private async void Save_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                rootPage.NotifyUser("Saving file...", NotifyType.StatusMessage);

                // Create a new encoder and initialize it with data from the original file.
                // The encoder writes to an in-memory stream, we then copy the contents to the file.
                // This allows the application to perform in-place editing of the file: any unedited data
                // is copied to the destination, and the original file is overwritten
                // with updated data.
                StorageFile file = await m_futureAccess.GetFileAsync(m_fileToken);
                using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.ReadWrite),
                                           memStream = new InMemoryRandomAccessStream())
                {
                    BitmapDecoder decoder = await BitmapDecoder.CreateAsync(fileStream);

                    // Use the native (no orientation applied) image dimensions because we want to handle
                    // orientation ourselves.
                    uint originalWidth = decoder.PixelWidth;
                    uint originalHeight = decoder.PixelHeight;

                    // Set the encoder's destination to the temporary, in-memory stream.
                    BitmapEncoder encoder = await BitmapEncoder.CreateForTranscodingAsync(memStream, decoder);

                    // Scaling occurs before flip/rotation, therefore use the original dimensions
                    // (no orientation applied) as parameters for scaling.
                    // Dimensions are rounded down by BitmapEncoder to the nearest integer.
                    if (m_scaleFactor != 1.0)
                    {
                        encoder.BitmapTransform.ScaledWidth = (uint)(originalWidth * m_scaleFactor);
                        encoder.BitmapTransform.ScaledHeight = (uint)(originalHeight * m_scaleFactor);

                        // Fant is a relatively high quality interpolation mode.
                        encoder.BitmapTransform.InterpolationMode = BitmapInterpolationMode.Fant;
                    }

                    // If the file format supports EXIF orientation ("System.Photo.Orientation") then
                    // update the orientation flag to reflect any user-specified rotation.
                    // Otherwise, perform a hard rotate using BitmapTransform.
                    if (m_disableExifOrientation == false)
                    {
                        BitmapPropertySet properties = new BitmapPropertySet();
                        ushort netExifOrientation = Helpers.ConvertToExifOrientationFlag(
                            Helpers.AddPhotoOrientation(m_userRotation, m_exifOrientation)
                            );

                        // BitmapProperties requires the application to explicitly declare the type
                        // of the property to be written - this is different from FileProperties which
                        // automatically coerces the value to the correct type. System.Photo.Orientation
                        // is defined as an unsigned 16 bit integer.
                        BitmapTypedValue orientationTypedValue = new BitmapTypedValue(
                            netExifOrientation,
                            Windows.Foundation.PropertyType.UInt16
                            );

                        properties.Add("System.Photo.Orientation", orientationTypedValue);
                        await encoder.BitmapProperties.SetPropertiesAsync(properties);
                    }
                    else
                    {
                        encoder.BitmapTransform.Rotation = Helpers.ConvertToBitmapRotation(m_userRotation);
                    }

                    // Attempt to generate a new thumbnail to reflect any rotation operation.
                    encoder.IsThumbnailGenerated = true;

                    try
                    {
                        await encoder.FlushAsync();
                    }
                    catch (Exception err)
                    {
                        switch (err.HResult)
                        {
                            case WINCODEC_ERR_UNSUPPORTEDOPERATION:
                                // If the encoder does not support writing a thumbnail, then try again
                                // but disable thumbnail generation.
                                encoder.IsThumbnailGenerated = false;
                                break;
                            default:
                                throw;
                        }
                    }

                    if (encoder.IsThumbnailGenerated == false)
                    {
                        await encoder.FlushAsync();
                    }

                    // Now that the file has been written to the temporary stream, copy the data to the file.
                    memStream.Seek(0);
                    fileStream.Seek(0);
                    fileStream.Size = 0;
                    await RandomAccessStream.CopyAsync(memStream, fileStream);
                }

                // Because the original file has been overwritten, reload it in the UI.
                ResetSessionState();
                await DisplayImageFileAsync(file);

                rootPage.NotifyUser("Successfully saved file: " + file.Name, NotifyType.StatusMessage);
            }
            catch (Exception err)
            {
                if (err.HResult == WINCODEC_ERR_COMPONENTNOTFOUND)
                {
                    // Some image formats (e.g. ICO) do not have encoders.
                    rootPage.NotifyUser("Error: this file format may not support editing.", NotifyType.ErrorMessage);
                }
                else
                {
                    rootPage.NotifyUser("Error: " + err.Message, NotifyType.ErrorMessage);
                }

                ResetPersistedState();
                ResetSessionState();
            }
        }
Esempio n. 36
0
       public static async Task<string> HttpPost(StorageFile inFile)
       {
           HttpClient httpClient = new HttpClient();
           uint MaxImageWidth = 480;
           uint MaxImageHeight = 800;
           uint width;
           uint height;
           string posturi = Config.apiChatImage;
           HttpMultipartFormDataContent fileContent = new HttpMultipartFormDataContent();

                        var inStream = await inFile.OpenReadAsync();
                        InMemoryRandomAccessStream outStream = new InMemoryRandomAccessStream();
                        BitmapDecoder decoder = await ImageHelp.GetProperDecoder(inStream,inFile);
                       


                        if (decoder.OrientedPixelWidth > MaxImageWidth && decoder.OrientedPixelHeight > MaxImageHeight)
                        {
                            width = MaxImageWidth;
                            height = MaxImageHeight;
                        }
                        else
                        {
                            width = decoder.OrientedPixelWidth;
                            height = decoder.OrientedPixelHeight;
                        }

                        


                        PixelDataProvider provider = await decoder.GetPixelDataAsync();
                        byte[] data = provider.DetachPixelData(); //获取像素数据的字节数组
                               

                        BitmapPropertySet propertySet = new BitmapPropertySet();
                        BitmapTypedValue qualityValue = new BitmapTypedValue(0.5, PropertyType.Single);
                        propertySet.Add("ImageQuality", qualityValue);


                        var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, outStream, propertySet);//建立编码器
                                encoder.SetPixelData(decoder.BitmapPixelFormat,
                                                     decoder.BitmapAlphaMode,
                                                     decoder.OrientedPixelWidth,
                                                     decoder.OrientedPixelHeight,
                                                      decoder.DpiX,
                                                      decoder.DpiY,
                                                      data
                                    );

                                encoder.BitmapTransform.ScaledWidth = width;
                                encoder.BitmapTransform.ScaledHeight = height;
                                await encoder.FlushAsync(); 
                                HttpStreamContent streamContent1 = new HttpStreamContent(outStream);
                                fileContent.Add(streamContent1, "pic", inFile.Name);
                                HttpResponseMessage response = await httpClient.PostAsync(new Uri(posturi), fileContent);
                             
                             return await response.Content.ReadAsStringAsync();
       
       
       
       
       }
Esempio n. 37
0
        private async Task WriteToDiskAsync()
        {
            var diskWriteInputPackages = CollectedColorFrames.Concat(CollectedIlluminatedInfraredFrames).Concat(CollectedNonIlluminatedInfraredFrames)
                                         .AsParallel().Select(async frame =>
            {
                SoftwareBitmap compatibleBitmap = null;
                Action cleanupAction            = () => { };
                if (frame.SoftwareBitmap.BitmapPixelFormat != BitmapPixelFormat.Bgra8 ||
                    frame.SoftwareBitmap.BitmapAlphaMode != BitmapAlphaMode.Ignore)
                {
                    compatibleBitmap = SoftwareBitmap.Convert(frame.SoftwareBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore);
                    cleanupAction    = () => compatibleBitmap.Dispose();
                }
                else
                {
                    compatibleBitmap = frame.SoftwareBitmap;
                }

                var fileName        = ((ulong)frame.SystemRelativeTime?.Ticks).ToString("D10");
                var encodingOptions = new BitmapPropertySet();
                var encoderId       = Guid.Empty;

                if (frame.SourceKind == MediaFrameSourceKind.Color)
                {
                    fileName  = "RGB-" + fileName + ".jpg";
                    encoderId = BitmapEncoder.JpegEncoderId;
                    encodingOptions.Add("ImageQuality", new BitmapTypedValue(
                                            1.0, // Maximum quality
                                            Windows.Foundation.PropertyType.Single));
                }
                else if (frame.SourceKind == MediaFrameSourceKind.Infrared)
                {
                    if (frame.IsIlluminated == true)
                    {
                        fileName = "IIR-" + fileName;  // Illuminated IR
                    }
                    else
                    {
                        fileName = "AIR-" + fileName;  // Ambient IR
                    }

                    fileName += ".png";
                    encoderId = BitmapEncoder.PngEncoderId;
                }

                var memoryStream      = new InMemoryRandomAccessStream();
                BitmapEncoder encoder = await BitmapEncoder.CreateAsync(encoderId, memoryStream, encodingOptions);
                encoder.SetSoftwareBitmap(compatibleBitmap);
                await encoder.FlushAsync();
                return(new { Stream = memoryStream.AsStream(), CleanupAction = cleanupAction, FileName = fileName });
            })
                                         .Select(task => task.ToObservable()).Merge().ObserveOn(NewThreadScheduler.Default).ToEnumerable(); // sequentialize awaitables

            var zipPath = Path.Combine(WorkingFolder.Path, "CollectedData.zip");

            using (FileStream zipFileStream = new FileStream(zipPath, FileMode.Create))
            {
                using (ZipArchive archive = new ZipArchive(zipFileStream, ZipArchiveMode.Create))
                {
                    foreach (var input in diskWriteInputPackages)
                    {
                        ZipArchiveEntry zipImgFileEntry = archive.CreateEntry(input.FileName, CompressionLevel.NoCompression);
                        using (Stream zipEntryStream = zipImgFileEntry.Open())
                        {
                            await input.Stream.CopyToAsync(zipEntryStream);
                        }

                        ++WrittenToDiskFramesCount;
                    }

                    ZipArchiveEntry zipMetadataFileEntry = archive.CreateEntry("info.json", CompressionLevel.NoCompression);
                    using (Stream zipEntryStream = zipMetadataFileEntry.Open())
                    {
                        MetadataWriter.WriteSerialization(zipEntryStream.AsOutputStream(), MediaCapture.Properties);
                    }
                }
            }

            foreach (var input in diskWriteInputPackages)
            {
                input.CleanupAction();
                input.Stream.Dispose();
            }
        }
        private async Task ReencodeAndSavePhotoAsync(IRandomAccessStream stream, string filename, PhotoOrientation photoOrientation)
        {
            using (var inputStream = stream)
            {
                var decoder = await BitmapDecoder.CreateAsync(inputStream);
                var file = await KnownFolders.PicturesLibrary.CreateFileAsync(filename, 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();
                }
            }

            Functions.DisplayMessage((String)_resources["photoTaken"]);
            cameraButton.IsEnabled = true;
        }
        async Task <byte[]> GetImageAsByteAsync(Guid format, int quality, int desiredWidth, int desiredHeight)
        {
            if (Control == null || Control.Source == null)
            {
                return(null);
            }

            var bitmap = Control.Source as WriteableBitmap;

            if (bitmap == null)
            {
                return(null);
            }

            byte[] pixels       = null;
            uint   pixelsWidth  = (uint)bitmap.PixelWidth;
            uint   pixelsHeight = (uint)bitmap.PixelHeight;

            if (desiredWidth != 0 || desiredHeight != 0)
            {
                double widthRatio  = (double)desiredWidth / (double)bitmap.PixelWidth;
                double heightRatio = (double)desiredHeight / (double)bitmap.PixelHeight;

                double scaleRatio = Math.Min(widthRatio, heightRatio);

                if (desiredWidth == 0)
                {
                    scaleRatio = heightRatio;
                }

                if (desiredHeight == 0)
                {
                    scaleRatio = widthRatio;
                }

                uint aspectWidth  = (uint)((double)bitmap.PixelWidth * scaleRatio);
                uint aspectHeight = (uint)((double)bitmap.PixelHeight * scaleRatio);

                using (var tempStream = new InMemoryRandomAccessStream())
                {
                    byte[] tempPixels = await GetBytesFromBitmapAsync(bitmap);

                    var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, tempStream);

                    encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied,
                                         pixelsWidth, pixelsHeight, 96, 96, tempPixels);
                    await encoder.FlushAsync();

                    tempStream.Seek(0);

                    BitmapDecoder decoder = await BitmapDecoder.CreateAsync(tempStream);

                    BitmapTransform transform = new BitmapTransform()
                    {
                        ScaledWidth       = aspectWidth,
                        ScaledHeight      = aspectHeight,
                        InterpolationMode = BitmapInterpolationMode.Cubic
                    };
                    PixelDataProvider pixelData = await decoder.GetPixelDataAsync(
                        BitmapPixelFormat.Bgra8,
                        BitmapAlphaMode.Premultiplied,
                        transform,
                        ExifOrientationMode.RespectExifOrientation,
                        ColorManagementMode.DoNotColorManage);

                    pixels       = pixelData.DetachPixelData();
                    pixelsWidth  = aspectWidth;
                    pixelsHeight = aspectHeight;
                }
            }
            else
            {
                pixels = await GetBytesFromBitmapAsync(bitmap);
            }

            using (var stream = new InMemoryRandomAccessStream())
            {
                BitmapEncoder encoder;

                if (format == BitmapEncoder.JpegEncoderId)
                {
                    var propertySet  = new BitmapPropertySet();
                    var qualityValue = new BitmapTypedValue((double)quality / 100d, Windows.Foundation.PropertyType.Single);
                    propertySet.Add("ImageQuality", qualityValue);

                    encoder = await BitmapEncoder.CreateAsync(format, stream, propertySet);
                }
                else
                {
                    encoder = await BitmapEncoder.CreateAsync(format, stream);
                }

                encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied,
                                     pixelsWidth, pixelsHeight, 96, 96, pixels);
                await encoder.FlushAsync();

                stream.Seek(0);

                var bytes = new byte[stream.Size];
                await stream.ReadAsync(bytes.AsBuffer(), (uint)stream.Size, InputStreamOptions.None);

                return(bytes);
            }
        }
Esempio n. 40
0
		///// <summary>
		///// Attempts to find and return a device mounted on the panel specified, and on failure to find one it will return the first device listed
		///// </summary>
		///// <param name="desiredPanel">The desired panel on which the returned device should be mounted, if available</param>
		///// <returns></returns>
		//public static async Task<DeviceInformation> FindCameraDeviceByPanelAsync(Windows.Devices.Enumeration.Panel desiredPanel)
		//{
		//    // Get available devices for capturing pictures
		//    var allVideoDevices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);

		//    // Get the desired camera by panel
		//    DeviceInformation desiredDevice = allVideoDevices.FirstOrDefault(x => x.EnclosureLocation != null && x.EnclosureLocation.Panel == desiredPanel);

		//    // If there is no device mounted on the desired panel, return the first device found
		//    return desiredDevice ?? allVideoDevices.FirstOrDefault();
		//}

		/// <summary>
		/// Applies the given orientation to a photo stream and saves it as a StorageFile
		/// </summary>
		/// <param name="inputStream">The photo stream</param>
		/// <param name="photoOrientation">The orientation metadata to apply to the photo</param>
		/// <returns></returns>
		private async Task ReencodeAndSavePhotoAsync(IRandomAccessStream inputStream, PhotoOrientation photoOrientation)
		{
			try
			{
				// LOLLO this decoder already has 480 × 640. if i set a different size when capturing the pic,
				// this decoder will respect it.
				var decoder = await BitmapDecoder.CreateAsync(inputStream);

				//StorageFile file = await GetFileAsync();

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

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

					await encoder.BitmapProperties.SetPropertiesAsync(bitmapProperties);
					await encoder.FlushAsync();
				}
			}
			catch (Exception ex)
			{
				await Logger.AddAsync(ex.ToString(), Logger.ForegroundLogFilename);
				Debugger.Break();
			}
			//finally
			//{
			//	//VM?.ForceEndShootAsync();
			//}
		}
Esempio n. 41
0
        /// <summary>
        /// Encodes the specified bitmap data and outputs it to the specified
        /// <c>BinaryWriter</c>. Bitmap data should be in BGRA format.
        /// For internal use only.
        /// </summary>
        public async Task EncodeAsync(byte[] bytes, BinaryWriter writer)
        {
#if NETFX_CORE
            using (var jpegStream = new InMemoryRandomAccessStream())
            {
                var propertySet = new BitmapPropertySet();
                var qualityValue = new BitmapTypedValue(this.JpegQuality / 100.0, PropertyType.Single);
                propertySet.Add("ImageQuality", qualityValue);

                var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, jpegStream, propertySet);
                if (this.Width != this.OutputWidth)
                {
                    encoder.BitmapTransform.ScaledWidth = (uint)this.OutputWidth;
                    encoder.BitmapTransform.ScaledHeight = (uint)this.OutputHeight;
                }

                encoder.SetPixelData(
                    BitmapPixelFormat.Bgra8,
                    BitmapAlphaMode.Straight,
                    (uint)this.Width,
                    (uint)this.Height,
                    96,
                    96,
                    bytes);
                await encoder.FlushAsync();

                if (writer.BaseStream == null || writer.BaseStream.CanWrite == false)
                    return;

                // Header
                writer.Write(this.OutputWidth);
                writer.Write(this.OutputHeight);
                writer.Write((int)jpegStream.Size);

                // Data
                jpegStream.AsStreamForRead().CopyTo(writer.BaseStream);
            }
#else
            await Task.Run(() =>
            {
                var format = PixelFormats.Bgra32;
                int stride = (int)this.Width * format.BitsPerPixel / 8;
                var bmp = BitmapSource.Create(
                    this.Width,
                    this.Height,
                    96.0,
                    96.0,
                    format,
                    null,
                    bytes,
                    stride);
                BitmapFrame frame;
                if (this.Width != this.OutputWidth || this.Height != this.OutputHeight)
                {
                    var transform = new ScaleTransform((double)this.OutputHeight / this.Height, (double)this.OutputHeight / this.Height);
                    var scaledbmp = new TransformedBitmap(bmp, transform);
                    frame = BitmapFrame.Create(scaledbmp);
                }
                else
                {
                    frame = BitmapFrame.Create(bmp);
                }

                var encoder = new JpegBitmapEncoder()
                {
                    QualityLevel = this.JpegQuality
                };
                encoder.Frames.Add(frame);
                using (var jpegStream = new MemoryStream())
                {
                    encoder.Save(jpegStream);

                    if (writer.BaseStream == null || writer.BaseStream.CanWrite == false)
                        return;

                    // Header
                    writer.Write(this.OutputWidth);
                    writer.Write(this.OutputHeight);
                    writer.Write((int)jpegStream.Length);

                    // Data
                    jpegStream.Position = 0;
                    jpegStream.CopyTo(writer.BaseStream);
                }
            });
#endif
        }
        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();
        }
 private void OnVideoQualityChanged(object sender, EventArgs e)
 {
     properties = CreateBitmapPropertySet();
 }
Esempio n. 44
0
        public  async void HttpPost(string uid, string uimage, string name, string content, List<string> imagePsthList, string songPath,string date,int type)
        {
            NotifyControl notify = new NotifyControl();
            notify.Text = "亲,努力发送中...";
            notify.Show();
            HttpClient httpClient = new HttpClient();
            uint MaxImageWidth = 480;
            uint MaxImageHeight = 800;
            uint width;
            uint height;
            try
            {
                string posturi = Config.apiDreamingPublish;
                HttpMultipartFormDataContent fileContent = new HttpMultipartFormDataContent();
                if (imagePsthList.Count > 0)
                {
                    for (int i = 0; i < imagePsthList.Count; i++)
                    {
                        StorageFile inFile = await StorageFile.GetFileFromPathAsync(imagePsthList[i]);
                        var inStream = await inFile.OpenReadAsync();
                        InMemoryRandomAccessStream outStream = new InMemoryRandomAccessStream();
                        BitmapDecoder decoder = await ImageHelp.GetProperDecoder(inStream,inFile);
                        if (decoder == null) return;


                        if (decoder.OrientedPixelWidth > MaxImageWidth && decoder.OrientedPixelHeight > MaxImageHeight)
                        {
                            width = MaxImageWidth;
                            height = MaxImageHeight;
                        }
                        else
                        {
                            width = decoder.OrientedPixelWidth;
                            height = decoder.OrientedPixelHeight;
                        }

                        


                        PixelDataProvider provider = await decoder.GetPixelDataAsync();
                        byte[] data = provider.DetachPixelData(); //获取像素数据的字节数组
                               

                        BitmapPropertySet propertySet = new BitmapPropertySet();
                        BitmapTypedValue qualityValue = new BitmapTypedValue(0.5, PropertyType.Single);
                        propertySet.Add("ImageQuality", qualityValue);


                        var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, outStream, propertySet);//建立编码器
                                encoder.SetPixelData(decoder.BitmapPixelFormat,
                                                     decoder.BitmapAlphaMode,
                                                     decoder.OrientedPixelWidth,
                                                     decoder.OrientedPixelHeight,
                                                      decoder.DpiX,
                                                      decoder.DpiY,
                                                      data
                                    );
                         
                                encoder.BitmapTransform.ScaledWidth = width;
                                encoder.BitmapTransform.ScaledHeight = height;
                                await encoder.FlushAsync(); 
                                HttpStreamContent streamContent1 = new HttpStreamContent(outStream);
                                fileContent.Add(streamContent1, "pic", inFile.Name);
                              }
                          }

              
                if (songPath != null)
                {
                    StorageFile file1 = await StorageFile.GetFileFromPathAsync(songPath);
                    IRandomAccessStreamWithContentType stream1 = await file1.OpenReadAsync();
                    HttpStreamContent streamContent1 = new HttpStreamContent(stream1);
                    fileContent.Add(streamContent1, "song", file1.Name);
                }

                HttpStringContent stringContent = new HttpStringContent(content);
                HttpStringContent stringName = new HttpStringContent(name);
                HttpStringContent stringUid = new HttpStringContent(uid);
                HttpStringContent stringUimage = new HttpStringContent(uimage);
                HttpStringContent stringTime = new HttpStringContent(date);
                HttpStringContent stringType = new HttpStringContent(type.ToString());
                

                fileContent.Add(stringContent, "content");
                fileContent.Add(stringUid, "phone");
                fileContent.Add(stringUimage, "uimage");

                fileContent.Add(stringName, "name");
                fileContent.Add(stringTime, "time");
                fileContent.Add(stringType, "type");

                HttpResponseMessage response = await httpClient.PostAsync(new Uri(posturi), fileContent);
              
                Init();
                notify.Hide();
                PostCommand.CanExecutes = true;
                NavigationHelp.NavigateTo(typeof(AllDreaming));
                



            }
            catch (Exception ex)
            {
                HelpMethods.Msg(ex.Message.ToString());
              
            }

        }
Esempio n. 45
0
        /// <summary>
        /// Applies the user-provided scale and rotation operation to the original image file.
        /// The "Transcoding" mode is used which preserves image metadata and performs other
        /// optimizations when possible.
        ///
        /// This method attempts to perform "soft" rotation using the EXIF orientation flag when possible,
        /// but falls back to a hard rotation of the image pixels.
        /// </summary>
        private async void Save_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                rootPage.NotifyUser("Saving file...", NotifyType.StatusMessage);

                // Create a new encoder and initialize it with data from the original file.
                // The encoder writes to an in-memory stream, we then copy the contents to the file.
                // This allows the application to perform in-place editing of the file: any unedited data
                // is copied to the destination, and the original file is overwritten
                // with updated data.
                StorageFile file = await m_futureAccess.GetFileAsync(m_fileToken);

                using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.ReadWrite),
                       memStream = new InMemoryRandomAccessStream())
                {
                    BitmapDecoder decoder = await BitmapDecoder.CreateAsync(fileStream);

                    // Use the native (no orientation applied) image dimensions because we want to handle
                    // orientation ourselves.
                    uint originalWidth  = decoder.PixelWidth;
                    uint originalHeight = decoder.PixelHeight;

                    // Set the encoder's destination to the temporary, in-memory stream.
                    BitmapEncoder encoder = await BitmapEncoder.CreateForTranscodingAsync(memStream, decoder);

                    // Scaling occurs before flip/rotation, therefore use the original dimensions
                    // (no orientation applied) as parameters for scaling.
                    // Dimensions are rounded down by BitmapEncoder to the nearest integer.
                    if (m_scaleFactor != 1.0)
                    {
                        encoder.BitmapTransform.ScaledWidth  = (uint)(originalWidth * m_scaleFactor);
                        encoder.BitmapTransform.ScaledHeight = (uint)(originalHeight * m_scaleFactor);
                    }

                    // If the file format supports EXIF orientation ("System.Photo.Orientation") then
                    // update the orientation flag to reflect any user-specified rotation.
                    // Otherwise, perform a hard rotate using BitmapTransform.
                    if (m_disableExifOrientation == false)
                    {
                        BitmapPropertySet properties         = new BitmapPropertySet();
                        ushort            netExifOrientation = Helpers.ConvertToExifOrientationFlag(
                            Helpers.AddPhotoOrientation(m_userRotation, m_exifOrientation)
                            );

                        // BitmapProperties requires the application to explicitly declare the type
                        // of the property to be written - this is different from FileProperties which
                        // automatically coerces the value to the correct type. System.Photo.Orientation
                        // is defined as an unsigned 16 bit integer.
                        BitmapTypedValue orientationTypedValue = new BitmapTypedValue(
                            netExifOrientation,
                            Windows.Foundation.PropertyType.UInt16
                            );

                        properties.Add("System.Photo.Orientation", orientationTypedValue);
                        await encoder.BitmapProperties.SetPropertiesAsync(properties);
                    }
                    else
                    {
                        encoder.BitmapTransform.Rotation = Helpers.ConvertToBitmapRotation(m_userRotation);
                    }

                    // Attempt to generate a new thumbnail to reflect any rotation operation.
                    encoder.IsThumbnailGenerated = true;

                    try
                    {
                        await encoder.FlushAsync();
                    }
                    catch (Exception err)
                    {
                        switch (err.HResult)
                        {
                        case WINCODEC_ERR_UNSUPPORTEDOPERATION:
                            // If the encoder does not support writing a thumbnail, then try again
                            // but disable thumbnail generation.
                            encoder.IsThumbnailGenerated = false;
                            break;

                        default:
                            throw err;
                        }
                    }

                    if (encoder.IsThumbnailGenerated == false)
                    {
                        await encoder.FlushAsync();
                    }

                    // Now that the file has been written to the temporary stream, copy the data to the file.
                    memStream.Seek(0);
                    fileStream.Seek(0);
                    fileStream.Size = 0;
                    await RandomAccessStream.CopyAsync(memStream, fileStream);

                    // Because the original file has been overwritten, reload it in the UI.
                    ResetSessionState();
                    await DisplayImageFileAsync(file);

                    rootPage.NotifyUser("Successfully saved file: " + file.Name, NotifyType.StatusMessage);
                }
            }
            catch (Exception err)
            {
                if (err.HResult == WINCODEC_ERR_COMPONENTNOTFOUND)
                {
                    // Some image formats (e.g. ICO) do not have encoders.
                    rootPage.NotifyUser("Error: this file format may not support editing.", NotifyType.ErrorMessage);
                }
                else
                {
                    rootPage.NotifyUser("Error: " + err.Message, NotifyType.ErrorMessage);
                }

                ResetPersistedState();
                ResetSessionState();
            }
        }
Esempio n. 46
0
        public async Task <bool> Initialize(VideoSetting videoSetting)
        {
            try
            {
                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAndAwaitAsync(CoreDispatcherPriority.Normal, async() =>
                {
                    _threadsCount   = videoSetting.UsedThreads;
                    _stoppedThreads = videoSetting.UsedThreads;

                    _lastFrameAdded.Start();

                    _imageQuality         = new BitmapPropertySet();
                    var imageQualityValue = new BitmapTypedValue(videoSetting.VideoQuality, Windows.Foundation.PropertyType.Single);
                    _imageQuality.Add("ImageQuality", imageQualityValue);

                    _mediaCapture = new MediaCapture();

                    var frameSourceGroups = await MediaFrameSourceGroup.FindAllAsync();

                    var settings = new MediaCaptureInitializationSettings()
                    {
                        SharingMode = MediaCaptureSharingMode.ExclusiveControl,

                        //With CPU the results contain always SoftwareBitmaps, otherwise with GPU
                        //they preferring D3DSurface
                        MemoryPreference = MediaCaptureMemoryPreference.Cpu,

                        //Capture only video, no audio
                        StreamingCaptureMode = StreamingCaptureMode.Video
                    };

                    await _mediaCapture.InitializeAsync(settings);

                    var mediaFrameSource      = _mediaCapture.FrameSources.First().Value;
                    var videoDeviceController = mediaFrameSource.Controller.VideoDeviceController;

                    videoDeviceController.DesiredOptimization = Windows.Media.Devices.MediaCaptureOptimization.Quality;
                    videoDeviceController.PrimaryUse          = Windows.Media.Devices.CaptureUse.Video;

                    //Set exposure (auto light adjustment)
                    if (_mediaCapture.VideoDeviceController.Exposure.Capabilities.Supported &&
                        _mediaCapture.VideoDeviceController.Exposure.Capabilities.AutoModeSupported)
                    {
                        _mediaCapture.VideoDeviceController.Exposure.TrySetAuto(true);
                    }

                    var videoResolutionWidthHeight = new VideoResolutionWidthHeight
                    {
                        Width  = 640,
                        Height = 480
                    };
                    var videoSubType = VideoSubtype.NV12;

                    //Set resolution, frame rate and video subtyp
                    var videoFormat = mediaFrameSource.SupportedFormats.Where(sf => sf.VideoFormat.Width == videoResolutionWidthHeight.Width &&
                                                                              sf.VideoFormat.Height == videoResolutionWidthHeight.Height &&
                                                                              sf.Subtype == videoSubType.ToString())
                                      .OrderByDescending(m => m.FrameRate.Numerator / m.FrameRate.Denominator)
                                      .First();

                    await mediaFrameSource.SetFormatAsync(videoFormat);

                    _mediaFrameReader = await _mediaCapture.CreateFrameReaderAsync(mediaFrameSource);
                    await _mediaFrameReader.StartAsync();
                });

                return(true);
            }
            catch (Exception ex)
            {
                //TODO: Remove/edit this line
                Debug.WriteLine("Unable to initialize camera...");
                Debug.WriteLine("Melding: " + ex.Message);
                return(false);
            }
        }
        private async void ColorFrameReader_FrameArrivedAsync(MediaFrameReader sender, MediaFrameArrivedEventArgs args)
        {
            if (_skippedFrames < _skipFrameCount)
            {
                _skippedFrames++;
                return;
            }
            _skippedFrames = 0;

            var mediaFrameReference = sender.TryAcquireLatestFrame();
            var videoMediaFrame     = mediaFrameReference?.VideoMediaFrame;
            var softwareBitmap      = videoMediaFrame?.SoftwareBitmap;

            if (softwareBitmap != null)
            {
                var encoderId = BitmapEncoder.JpegEncoderId;

                InMemoryRandomAccessStream jpegStream = new InMemoryRandomAccessStream();

                var propertySet  = new BitmapPropertySet();
                var qualityValue = new BitmapTypedValue(_imageQuality, PropertyType.Single);

                propertySet.Add("ImageQuality", qualityValue);
                BitmapEncoder bitmapEncoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, jpegStream, propertySet);

                bitmapEncoder.BitmapTransform.Rotation = IntToBitmapRotation(_videoRotation);



                bitmapEncoder.SetSoftwareBitmap(softwareBitmap);
                await bitmapEncoder.FlushAsync();


                if (_activityCounter++ > 50)
                {
                    Debug.WriteLine(".");
                    _activityCounter = 0;
                }

                else
                {
                    Debug.Write(".");
                }

                Interlocked.Exchange(ref _jpegStreamBuffer, jpegStream);

                if (_previewVideoEnabled)
                {
                    // Changes to XAML ImageElement must happen on UI thread through Dispatcher
                    var task = imageElement.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                                                async() =>
                    {
                        // Don't let two copies of this task run at the same time.
                        if (taskRunning)
                        {
                            return;
                        }
                        taskRunning = true;

                        try
                        {
                            InMemoryRandomAccessStream imageElementJpegStream = _jpegStreamBuffer;
                            if (imageElementJpegStream != null)
                            {
                                BitmapImage bitmapImage = new BitmapImage();
                                await bitmapImage.SetSourceAsync(imageElementJpegStream);
                                imageElement.Source = bitmapImage;
                            }
                        } catch (Exception imageElementException)
                        {
                            Debug.WriteLine("Image Element writing exception. " + imageElementException.Message);
                        }

                        taskRunning = false;
                    });
                }
            }
            if (mediaFrameReference != null)
            {
                mediaFrameReference.Dispose();
            }
        }
        public async Task<string> GetImageAsBase64Encoded()
        {
            // Adapted from
            // http social.msdn.microsoft.com/Forums/wpapps/en-US/.../image-to-base64-encoding [Win Phone 7, 2010] and
            // <same site> /sharing-a-writeablebitmap and
            // www.charlespetzold.com/blog/2012/08/WritableBitmap-Pixel-Arrays-in-CSharp-and-CPlusPlus.html
            // example in WebcamPage.xaml.cs
            string results = "";
            try
            {
                //using (Stream stream = App.CurrentPatient.ImageWriteableBitmap.PixelBuffer.AsStream())
                using (Stream stream = ImageWriteableBitmap.PixelBuffer.AsStream()) //There are 4 bytes per pixel. 
                {
                    byte[] pixels = await ConvertStreamToByteArray(stream);

                    // Now render the object in a known format, e.g., jpeg:
                    //InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream();
                    IRandomAccessStream ms = new InMemoryRandomAccessStream();
                    // If calling from a synchronous function, add AsTask().ConfigureAwait(false) to avoid hanging UI thread

                    // If image as optionally cropped is over 1.5Mp, then apply aggressive compression to get it to that size (approximately)
                    double quality = 1.0;  //Max quality, the default.  For jpeg, 1.0 - quality = compression ratio
                    UInt64 totalPixels = (ulong)ImageWriteableBitmap.PixelWidth * (ulong)ImageWriteableBitmap.PixelHeight;
                    if (totalPixels > 1500000L)
                        quality = Math.Round(((double)1500000.0 / (double)totalPixels), 2, MidpointRounding.AwayFromZero); // for debug purposes, round quality to 2 fractional digits
                    // For encoding options, wee msdn.microsoft.com/en-us/library/windows/apps/jj218354.aspx "How to use encoding options".
                    var encodingOptions = new BitmapPropertySet();
                    var qualityValue = new BitmapTypedValue(quality, Windows.Foundation.PropertyType.Single);
                    encodingOptions.Add("ImageQuality", qualityValue);

                    BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, ms, encodingOptions); //.AsTask().ConfigureAwait(false);
                    /*
                                    BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.BmpEncoderId, ms); */
                    encoder.SetPixelData(
                        BitmapPixelFormat.Bgra8, //Rgba8, //Bgra8,
                        BitmapAlphaMode.Straight, // .Ignore
                        (uint)ImageWriteableBitmap.PixelWidth,//(uint)App.CurrentPatient.ImageWriteableBitmap.PixelWidth,
                        (uint)ImageWriteableBitmap.PixelHeight,//(uint)App.CurrentPatient.ImageWriteableBitmap.PixelHeight,
                        96.0, 96.0, pixels);

                    await encoder.FlushAsync(); //.AsTask().ConfigureAwait(false);
                    byte[] jpgEncoded = await ConvertMemoryStreamToByteArray(ms);
                    results = Convert.ToBase64String(jpgEncoded);
                    await ms.FlushAsync(); // cleanup
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Error when encoding image: " + ex.Message);
            }
            return results;
        }
Esempio n. 49
0
        private async void PhotoButton_Tapped(object sender, TappedRoutedEventArgs e)
        {
            TakePhotoEffect.Visibility = Visibility.Visible;
            BtnPhoto.IsEnabled = false;
            try
            {
                using (var stream = new InMemoryRandomAccessStream())
                {
                    await mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream);

                    var decoder = await BitmapDecoder.CreateAsync(stream);
                    var file = await KnownFolders.PicturesLibrary.CreateFileAsync("Photo.jpeg", CreationCollisionOption.GenerateUniqueName);


                    using (var outputStream = await file.OpenAsync(FileAccessMode.ReadWrite))
                    {
                        var encoder = await BitmapEncoder.CreateForTranscodingAsync(outputStream, decoder);
                        var photoOrientation = ConvertOrientationToPhotoOrientation(GetCameraOrientation());
                        var properties = new BitmapPropertySet { { "System.Photo.Orientation", new BitmapTypedValue(photoOrientation, PropertyType.UInt16) } };
                        await encoder.BitmapProperties.SetPropertiesAsync(properties);
                        await encoder.FlushAsync();
                    }
                }
            }
            catch { }

            TakePhotoEffect.Visibility = Visibility.Collapsed;
            BtnPhoto.IsEnabled = true;
        }
        /// <summary>
        /// Applies the given orientation to a photo stream and saves it as a StorageFile
        /// </summary>
        /// <param name="stream">The photo stream</param>
        /// <param name="photoOrientation">The orientation metadata to apply to the photo</param>
        /// <returns></returns>
        private static async Task ReencodeAndSavePhotoAsync(IRandomAccessStream stream, PhotoOrientation photoOrientation)
        {
            using (var inputStream = stream)
            {
                var decoder = await BitmapDecoder.CreateAsync(inputStream);

                var file = await KnownFolders.PicturesLibrary.CreateFileAsync("SimplePhoto.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();
                }
            }
        }
        /// <summary>
        /// Applies the given orientation to a photo stream and saves it as a StorageFile
        /// </summary>
        /// <param name="stream">The photo stream</param>
        /// <param name="file">The StorageFile in which the photo stream will be saved</param>
        /// <param name="photoOrientation">The orientation metadata to apply to the photo</param>
        /// <returns></returns>
        private static async Task ReencodeAndSavePhotoAsync(IRandomAccessStream stream, StorageFile file, PhotoOrientation photoOrientation)
        {
            using (var inputStream = stream)
            {
                var decoder = await BitmapDecoder.CreateAsync(inputStream);

                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();
                }
            }
        }