Inheritance: IBitmapTypedValue
Example #1
0
        // </SnippetReadImageMetadata>
        // <SnippetWriteImageMetadata>
        private async void WriteImageMetadata(BitmapEncoder bitmapEncoder)
        {
            var propertySet      = new Windows.Graphics.Imaging.BitmapPropertySet();
            var orientationValue = new Windows.Graphics.Imaging.BitmapTypedValue(
                1, // Defined as EXIF orientation = "normal"
                Windows.Foundation.PropertyType.UInt16
                );

            propertySet.Add("System.Photo.Orientation", orientationValue);

            try
            {
                await bitmapEncoder.BitmapProperties.SetPropertiesAsync(propertySet);
            }
            catch (Exception err)
            {
                switch (err.HResult)
                {
                case unchecked ((int)0x88982F41):    // WINCODEC_ERR_PROPERTYNOTSUPPORTED
                                                     // The file format does not support this property.
                    break;

                default:
                    throw err;
                }
            }
        }
Example #2
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 async void WriteImageMetadata(BitmapEncoder bitmapEncoder, BitmapPropertiesView inputProperties)
        {
            var propertySet = new Windows.Graphics.Imaging.BitmapPropertySet();

            var requests = new System.Collections.Generic.List <string>();

            requests.Add("System.Photo.Orientation");

            var retrievedProps = await inputProperties.GetPropertiesAsync(requests);

            if (retrievedProps.ContainsKey("System.Photo.Orientation"))
            {
                propertySet.Add("System.Photo.Orientation", retrievedProps["System.Photo.Orientation"]);
            }
            else
            {
                var orientationValue = new Windows.Graphics.Imaging.BitmapTypedValue(
                    1, // Defined as EXIF orientation = "normal"
                    Windows.Foundation.PropertyType.UInt16
                    );
                propertySet.Add("System.Photo.Orientation", orientationValue);
            }
            if (date.Date != null)
            {
                var datetaken = new Windows.Graphics.Imaging.BitmapTypedValue(
                    date.Date,
                    Windows.Foundation.PropertyType.DateTime
                    );
                propertySet.Add("System.Photo.DateTaken", datetaken);
            }
            var qualityValue = new Windows.Graphics.Imaging.BitmapTypedValue(
                1.0, // Maximum quality
                Windows.Foundation.PropertyType.Single
                );
            var location = new Windows.Graphics.Imaging.BitmapTypedValue(
                1.0, // Maximum quality
                Windows.Foundation.PropertyType.Single
                );

            propertySet.Add("ImageQuality", qualityValue);
            try
            {
                await bitmapEncoder.BitmapProperties.SetPropertiesAsync(propertySet);
            }
            catch (Exception err)
            {
                switch (err.HResult)
                {
                case unchecked ((int)0x88982F41):    // WINCODEC_ERR_PROPERTYNOTSUPPORTED
                                                     // The file format does not support the requested metadata.
                    break;

                case unchecked ((int)0x88982F81):    // WINCODEC_ERR_UNSUPPORTEDOPERATION
                                                     // The file format does not support any metadata.
                    break;
                }
            }
        }
Example #5
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();
            }
           
        }
Example #6
0
        public static async Task WriteableBitmapToStorageFile(WriteableBitmap WB, FileFormat fileFormat, int compression, StorageFile file)
        {
            string FileName          = "YourFile.";
            Guid   BitmapEncoderGuid = BitmapEncoder.JpegEncoderId;

            switch (fileFormat)
            {
            case FileFormat.Jpeg:
                FileName         += "jpeg";
                BitmapEncoderGuid = BitmapEncoder.JpegEncoderId;
                break;

            case FileFormat.Png:
                FileName         += "png";
                BitmapEncoderGuid = BitmapEncoder.PngEncoderId;
                break;

            case FileFormat.Bmp:
                FileName         += "bmp";
                BitmapEncoderGuid = BitmapEncoder.BmpEncoderId;
                break;

            case FileFormat.Tiff:
                FileName         += "tiff";
                BitmapEncoderGuid = BitmapEncoder.TiffEncoderId;
                break;

            case FileFormat.Gif:
                FileName         += "gif";
                BitmapEncoderGuid = BitmapEncoder.GifEncoderId;
                break;
            }
            using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                var propertySet  = new Windows.Graphics.Imaging.BitmapPropertySet();
                var qualityValue = new Windows.Graphics.Imaging.BitmapTypedValue(
                    1 - (compression / 100),
                    Windows.Foundation.PropertyType.Single
                    );

                propertySet.Add("ImageQuality", qualityValue);

                BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoderGuid, stream, propertySet);

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

                encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)WB.PixelWidth, (uint)WB.PixelHeight,
                                     96.0,
                                     96.0,
                                     pixels);

                await encoder.FlushAsync();
            }
        }
Example #7
0
        // </SnippetSaveSoftwareBitmapToFile>

        private async void UseEncodingOptions(StorageFile outputFile)
        {
            using (IRandomAccessStream stream = await outputFile.OpenAsync(FileAccessMode.ReadWrite))
            {
                // <SnippetUseEncodingOptions>
                var propertySet  = new Windows.Graphics.Imaging.BitmapPropertySet();
                var qualityValue = new Windows.Graphics.Imaging.BitmapTypedValue(
                    1.0, // Maximum quality
                    Windows.Foundation.PropertyType.Single
                    );

                propertySet.Add("ImageQuality", qualityValue);

                await Windows.Graphics.Imaging.BitmapEncoder.CreateAsync(
                    Windows.Graphics.Imaging.BitmapEncoder.JpegEncoderId,
                    stream,
                    propertySet
                    );

                // </SnippetUseEncodingOptions>
            }
        }
Example #8
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();
       
       
       
       
       }
        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;
        }
Example #10
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();
            }
        }
        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();
        }
Example #12
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
        }
        public async Task CaptureFrame()
        {
            try
            {
                using (var ms = new InMemoryRandomAccessStream())
                {
                    SoftwareBitmap bitmap       = null;
                    var            propertySet  = new Windows.Graphics.Imaging.BitmapPropertySet();
                    var            qualityValue = new Windows.Graphics.Imaging.BitmapTypedValue(
                        0.5, // Quality percentage.
                        Windows.Foundation.PropertyType.Single
                        );
                    propertySet.Add("ImageQuality", qualityValue);

                    var frameReference = this.CameraFrameReader.TryAcquireLatestFrame();
                    var frame          = frameReference?.VideoMediaFrame?.SoftwareBitmap;
                    this.CameraFrameReader.AcquisitionMode = MediaFrameReaderAcquisitionMode.Realtime;

                    if (frame == null)
                    {
                        var surface = frameReference?.VideoMediaFrame?.Direct3DSurface;
                        if (surface != null)
                        {
                            bitmap = await SoftwareBitmap.CreateCopyFromSurfaceAsync(surface, BitmapAlphaMode.Ignore).AsTask().ConfigureAwait(false);

                            // JPEG Encoder no likey YUY2.
                            if (bitmap.BitmapPixelFormat != BitmapPixelFormat.Bgra8)
                            {
                                bitmap = SoftwareBitmap.Convert(bitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore);
                            }
                        }
                    }
                    else
                    {
                        bitmap = SoftwareBitmap.Convert(frame, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore);
                    }

                    if (bitmap == null)
                    {
                        return;
                    }

                    using (bitmap)
                    {
                        var jpegEncoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, ms, propertySet).AsTask().ConfigureAwait(false);

                        jpegEncoder.SetSoftwareBitmap(bitmap);

                        // No thumbnail for just "streaming".
                        //jpegEncoder.IsThumbnailGenerated = false;

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

                            default:
                                throw err;
                            }
                        }

                        if (ms.Size > 0)
                        {
                            // TODO: make this more efficient.
                            byte[] data = (byte[])Array.CreateInstance(typeof(byte), (int)ms.Size);
                            ms.AsStreamForRead().Read(data, 0, (int)ms.Size);
                            this.CapturedFrame = new Frame()
                            {
                                Data   = data,
                                Format = "jpeg",
                                Width  = (uint)bitmap.PixelWidth,
                                Height = (uint)bitmap.PixelHeight
                            };
                        }
                    }
                }
            }
            catch (Exception e)
            {
                this.Log.Error(() => "Exception while capturing frame.", e);
            }
        }
Example #14
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());
              
            }

        }