Esempio n. 1
0
        public async static Task <BitmapSource> LoadImageAsync(Stream imageStream)
        {
            if (imageStream == null)
            {
                return(null);
            }

#if WINDOWS_PHONE
            BitmapImage bmp = null;
            try
            {
                bmp = new BitmapImage();
                bmp.SetSource(imageStream);
            }
            catch (Exception ex)
            {
                Log.WriteLine("LoadImageAsync failed: " + ex.Message);
            }
            await Task.Delay(1);
#else
            WriteableBitmap bmp = null;
            try
            {
                var stream = await ConvertStream(imageStream);

                BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);

                // convert to a writable bitmap so we can get the PixelBuffer back out later...
                // in case we need to edit and/or re-encode the image.
                bmp = new WriteableBitmap((int)decoder.PixelHeight, (int)decoder.PixelWidth);

                // remember the format of this image
                PixelBufferObject.SetBitmapPixelFormat(bmp, decoder.BitmapPixelFormat);
                PixelBufferObject.SetBitmapAlphaMode(bmp, decoder.BitmapAlphaMode);

                stream.Seek(0);
                bmp.SetSource(stream);

                imageStream.Dispose();
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
#endif
            return(bmp);
        }
Esempio n. 2
0
        public async static Task SaveImageAsync(BitmapSource image, IRandomAccessStream file)
        {
            BitmapEncoder encoder = await BitmapEncoder.CreateAsync(Windows.Graphics.Imaging.BitmapEncoder.PngEncoderId, file);

            WriteableBitmap writeable = image as WriteableBitmap;

            if (writeable == null)
            {
                return;
            }

            // remember the format of this image
            BitmapPixelFormat format = PixelBufferObject.GetBitmapPixelFormat(writeable);
            BitmapAlphaMode   mode   = PixelBufferObject.GetBitmapAlphaMode(writeable);

            IBuffer    buffer     = writeable.PixelBuffer;
            DataReader dataReader = DataReader.FromBuffer(buffer);

            byte[] pixels = new byte[buffer.Length];
            dataReader.ReadBytes(pixels);

            encoder.SetPixelData(format, mode, (uint)image.PixelWidth, (uint)image.PixelHeight, 96, 96, pixels);
            await encoder.FlushAsync();
        }