Inheritance: IBitmapTransform
        private async Task<byte[]> ImageToBytes(IRandomAccessStream sourceStream)
        {
            byte[] imageArray;

            BitmapDecoder decoder = await BitmapDecoder.CreateAsync(sourceStream);

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

            using (var destinationStream = new InMemoryRandomAccessStream())
            {
                BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, destinationStream);
                encoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Premultiplied, decoder.PixelWidth,
                    decoder.PixelHeight, 96, 96, pixelData.DetachPixelData());
                await encoder.FlushAsync();

                BitmapDecoder outputDecoder = await BitmapDecoder.CreateAsync(destinationStream);
                await destinationStream.FlushAsync();
                imageArray = (await outputDecoder.GetPixelDataAsync()).DetachPixelData();
            }
            return imageArray;
        }
        public static async Task<Color> GetDominantColorFromFile(StorageFile file)
        {
            //get the file

            using (var stream = await file.OpenAsync(FileAccessMode.Read))
            {
                //Create a decoder for the image
                var decoder = await BitmapDecoder.CreateAsync(stream);

                //Create a transform to get a 1x1 image
                var myTransform = new BitmapTransform { ScaledHeight = 1, ScaledWidth = 1 };

                //Get the pixel provider
                var pixels = await decoder.GetPixelDataAsync(
                    BitmapPixelFormat.Rgba8,
                    BitmapAlphaMode.Ignore,
                    myTransform,
                    ExifOrientationMode.IgnoreExifOrientation,
                    ColorManagementMode.DoNotColorManage);

                //Get the bytes of the 1x1 scaled image
                var bytes = pixels.DetachPixelData();

                //read the color 
                var myDominantColor = Color.FromArgb(255, bytes[0], bytes[1], bytes[2]);

                return myDominantColor;
            }
        }
		/// <summary>
		/// Use BitmapTransform to define the region to crop, and then get the pixel data in the region.
		/// If you want to get the pixel data of a scaled image, set the scaledWidth and scaledHeight
		/// of the scaled image.
		/// </summary>
		/// <returns></returns>
		async static private Task<byte[]> GetPixelData(BitmapDecoder decoder, uint startPointX, uint startPointY,
			uint width, uint height, uint scaledWidth, uint scaledHeight)
		{

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

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

			// Get the cropped pixels within the bounds of transform.
			PixelDataProvider pix = await decoder.GetPixelDataAsync(
				BitmapPixelFormat.Bgra8,
				BitmapAlphaMode.Straight,
				transform,
				ExifOrientationMode.IgnoreExifOrientation,
				ColorManagementMode.ColorManageToSRgb);
			byte[] pixels = pix.DetachPixelData();
			return pixels;
		}
		public async Task ConverterBitmapToTargetStreamAsync(IRandomAccessStream bitmapSourceStream, IRandomAccessStream saveTargetStream)
		{
			BitmapDecoder decoder = await BitmapDecoder.CreateAsync(bitmapSourceStream);
			// Scale image to appropriate size
			BitmapTransform transform = new BitmapTransform()
			{
				//ScaledWidth = Convert.ToUInt32(bi.PixelWidth),
				//ScaledHeight = Convert.ToUInt32(bi.PixelHeight) 
			};

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

			var BitmapEncoderGuid = BitmapEncoder.PngEncoderId;

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

			encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore,
					  (uint)decoder.PixelWidth,
					  (uint)decoder.PixelHeight,
					  96.0,
					  96.0,
					  pixelData.DetachPixelData());
			await encoder.FlushAsync();
		}
Beispiel #5
0
 async Task<WriteableBitmap> ResizeImage(WriteableBitmap baseWriteBitmap, uint width, uint height)
 {
     Stream stream = baseWriteBitmap.PixelBuffer.AsStream();
     byte[] pixels = new byte[(uint)stream.Length];
     await stream.ReadAsync(pixels, 0, pixels.Length);
     var inMemoryRandomStream = new InMemoryRandomAccessStream();
     var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, inMemoryRandomStream);
     encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)baseWriteBitmap.PixelWidth, (uint)baseWriteBitmap.PixelHeight, 96, 96, pixels);
     await encoder.FlushAsync();
     var transform = new BitmapTransform
     {
         ScaledWidth = width,
         ScaledHeight = height
     };
     inMemoryRandomStream.Seek(0);
     var decoder = await BitmapDecoder.CreateAsync(inMemoryRandomStream);
     var pixelData = await decoder.GetPixelDataAsync(
                     BitmapPixelFormat.Bgra8,
                     BitmapAlphaMode.Straight,
                     transform,
                     ExifOrientationMode.IgnoreExifOrientation,
                     ColorManagementMode.DoNotColorManage);
     var sourceDecodedPixels = pixelData.DetachPixelData();
     var inMemoryRandomStream2 = new InMemoryRandomAccessStream();
     var encoder2 = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, inMemoryRandomStream2);
     encoder2.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, width, height, 96, 96, sourceDecodedPixels);
     await encoder2.FlushAsync();
     inMemoryRandomStream2.Seek(0);
     var bitmap = new WriteableBitmap((int)width, (int)height);
     await bitmap.SetSourceAsync(inMemoryRandomStream2);
     return bitmap;
 }
 private static async Task<WriteableBitmap> read()
 {
     using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read))
     {
         BitmapDecoder decoder = await BitmapDecoder.CreateAsync(BitmapDecoder.JpegDecoderId, stream);
         uint width = decoder.PixelWidth;
         uint height = decoder.PixelHeight;
         if (angle % 180 != 0)
         {
             width = decoder.PixelHeight;
             height = decoder.PixelWidth;
         }
         Dictionary<int, BitmapRotation> angles = new Dictionary<int, BitmapRotation>()
         {
             { 0, BitmapRotation.None },
             { 90,  BitmapRotation.Clockwise90Degrees },
             { 180,  BitmapRotation.Clockwise180Degrees },
             { 270, BitmapRotation.Clockwise270Degrees },
             { 360, BitmapRotation.None }
         };
         BitmapTransform transform = new BitmapTransform();
         transform.Rotation = angles[angle];
         PixelDataProvider data = await decoder.GetPixelDataAsync(
         BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, transform,
         ExifOrientationMode.IgnoreExifOrientation, ColorManagementMode.DoNotColorManage);
         bitmap = new WriteableBitmap((int)width, (int)height);
         byte[] buffer = data.DetachPixelData();
         using (Stream pixels = bitmap.PixelBuffer.AsStream())
         {
             pixels.Write(buffer, 0, (int)pixels.Length);
         }
     }
     return bitmap;
 }
Beispiel #7
0
 private async void OnClick(object sender, RoutedEventArgs e)
 {
     Button btn = sender as Button;
     btn.IsEnabled = false;
     // 项目中的图像文件
     Uri gifUri = new Uri("ms-appx:///Assets/1.gif");
     StorageFile gifFile = await StorageFile.GetFileFromApplicationUriAsync(gifUri);
     using (IRandomAccessStream inputStream = await gifFile.OpenReadAsync()) // 打开文件流
     {
         // 创建图像解码器实例
         BitmapDecoder decoder = await BitmapDecoder.CreateAsync(BitmapDecoder.GifDecoderId, inputStream);
         // 获取图像文件中的总帧数
         uint frameCount = decoder.FrameCount;
         // 分别读取各个帧中的图像,并添加到 ListView 控件中
         for(uint n = 0; n < frameCount; ++n)
         {
             BitmapFrame curFrame = await decoder.GetFrameAsync(n);
             // 获取图像的像素数据
             // 在获取数据时,对图像进行变换处理
             // 将宽度和高度变为原来的 1/3
             BitmapTransform btf = new BitmapTransform();
             btf.ScaledWidth = curFrame.PixelWidth / 3;
             btf.ScaledHeight = curFrame.PixelHeight / 3;
             var pxprd = await curFrame.GetPixelDataAsync(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, btf, ExifOrientationMode.IgnoreExifOrientation, ColorManagementMode.DoNotColorManage);
             byte[] data = pxprd.DetachPixelData();
             // 创建内存位图图像
             WriteableBitmap bmp = new WriteableBitmap((int)btf.ScaledWidth, (int)btf.ScaledHeight);
             data.CopyTo(bmp.PixelBuffer);
             lvimgs.Items.Add(bmp);
         }
     }
     btn.IsEnabled = true;
 }
        /// <summary>
        /// This function rotates the passed WriteableBitmap clockwise or counter-clockwise
        /// </summary>
        /// <param name="baseWriteBitmap"> WriteableBitmap to be rotated </param>
        /// <param name="width"> Width of the WriteableBitmap </param>
        /// <param name="height"> Height of the WriteableBitmap </param>
        /// <param name="position"> If 'right', it rotates clockwise, if 'left' - counterclockwise </param>
        public async Task<WriteableBitmap> RotateImage(WriteableBitmap baseWriteBitmap, uint width, uint height, string position)
        {
            // Get the pixel buffer of the writable bitmap in bytes
            Stream stream = baseWriteBitmap.PixelBuffer.AsStream();
            byte[] pixels = new byte[(uint)stream.Length];
            await stream.ReadAsync(pixels, 0, pixels.Length);

            //Encoding the data of the PixelBuffer we have from the writable bitmap
            var inMemoryRandomStream = new InMemoryRandomAccessStream();
            var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, inMemoryRandomStream);
            encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)baseWriteBitmap.PixelWidth, (uint)baseWriteBitmap.PixelHeight, 96, 96, pixels);
            await encoder.FlushAsync();

            // At this point we have an encoded image in inMemoryRandomStream
            // We apply the transform and decode

            BitmapRotation rotateTo = BitmapRotation.None;

            if (position == "right")
            {
                rotateTo = BitmapRotation.Clockwise90Degrees;
            }
            else if (position == "left")
            {
                rotateTo = BitmapRotation.Clockwise270Degrees;
            }

            var transform = new BitmapTransform
            {
                ScaledWidth = width,
                ScaledHeight = height,
                Rotation = rotateTo
            };
            inMemoryRandomStream.Seek(0);
            var decoder = await BitmapDecoder.CreateAsync(inMemoryRandomStream);
            var pixelData = await decoder.GetPixelDataAsync(
                            BitmapPixelFormat.Bgra8,
                            BitmapAlphaMode.Straight,
                            transform,
                            ExifOrientationMode.IgnoreExifOrientation,
                            ColorManagementMode.DoNotColorManage);

            // An array containing the decoded image data
            var sourceDecodedPixels = pixelData.DetachPixelData();

            // We encode the image buffer again:

            // Encoding data
            var inMemoryRandomStream2 = new InMemoryRandomAccessStream();
            var encoder2 = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, inMemoryRandomStream2);
            encoder2.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, height, width, 96, 96, sourceDecodedPixels);
            await encoder2.FlushAsync();
            inMemoryRandomStream2.Seek(0);

            // Finally the resized WritableBitmap
            var bitmap = new WriteableBitmap((int)width, (int)height);
            await bitmap.SetSourceAsync(inMemoryRandomStream2);
            return bitmap;
        }
        /// <summary>
        /// 改变图片大小
        /// </summary>
        /// <param name="sourceStream">包含图片数据的数据流</param>
        /// <param name="scaleLong">如果图片长大于宽,那么此为改编后的长度,反之是改变后的高度</param>
        /// <returns></returns>
        public static async Task<IRandomAccessStream> ResizeImage(IRandomAccessStream sourceStream,uint scaleLong)
        {
            try
            {
                BitmapDecoder decoder = await BitmapDecoder.CreateAsync(sourceStream);
                uint height = decoder.PixelHeight;
                uint weight = decoder.PixelWidth;

                double rate;
                uint destHeight = height;
                uint destWeight = weight;

                if (weight > height)
                {
                    rate = scaleLong / (double)weight;
                    destHeight = weight > scaleLong ? (uint)(rate * height) : height;
                    destWeight = scaleLong;
                }
                else
                {
                    rate = scaleLong / (double)height;
                    destWeight = height > scaleLong ? (uint)(rate * weight) : weight;
                    destHeight = scaleLong;
                }

                BitmapTransform transform = new BitmapTransform()
                {
                    ScaledWidth = destWeight,
                    ScaledHeight = destHeight
                };

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

                var folder = ApplicationData.Current.TemporaryFolder;
                var tempfile = await folder.CreateFileAsync("temp.jpg", CreationCollisionOption.GenerateUniqueName);
                IRandomAccessStream destStream = await tempfile.OpenAsync(FileAccessMode.ReadWrite);

                BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, destStream);
                encoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Straight, transform.ScaledWidth, transform.ScaledHeight, 100, 100, pixelData.DetachPixelData());
                await encoder.FlushAsync();

                //REMEMBER
                destStream.Seek(0);

                await tempfile.DeleteAsync(StorageDeleteOption.PermanentDelete);

                return destStream;
            }
            catch(Exception e)
            {
                var task = ExceptionHelper.WriteRecordAsync(e, nameof(BitmapHandleHelper), nameof(ResizeImage));
                return null;
            }
        }
Beispiel #10
0
     private async Task<BitmapSource> resize(int width, int height, Windows.Storage.Streams.IRandomAccessStream source)
 {
         WriteableBitmap small = new WriteableBitmap(width, height);
     BitmapDecoder decoder = await BitmapDecoder.CreateAsync(source);
     BitmapTransform transform = new BitmapTransform();
     transform.ScaledHeight = (uint)height; transform.ScaledWidth = (uint)width;
     PixelDataProvider pixelData = await decoder.GetPixelDataAsync(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, transform, ExifOrientationMode.RespectExifOrientation, ColorManagementMode.DoNotColorManage);
     pixelData.DetachPixelData().CopyTo(small.PixelBuffer);
     return small;
     }
Beispiel #11
0
        /// <summary>
        /// 异步从网络下载图片
        /// </summary>
        /// <param name="outfileName">下载保存到本地的图片文件名</param>
        /// <param name="downloadUriString">图片uri</param>
        /// <param name="scaleSize">图片尺寸</param>
        /// <returns></returns>
        public static async Task DownloadAndScale(string outfileName, string downloadUriString, Size scaleSize)
        {
            try
            {
                Uri        downLoadingUri = new Uri(downloadUriString); //创建uri对象
                HttpClient client         = new HttpClient();           //实例化httpclient对象
                using (var response = await client.GetAsync(downLoadingUri))
                {
                    var buffer = await response.Content.ReadAsBufferAsync();//从返回的数据中读取buffer

                    var memoryStream = new InMemoryRandomAccessStream();
                    await memoryStream.WriteAsync(buffer);                                                //将buffer写入memorystream

                    await memoryStream.FlushAsync();                                                      //刷新

                    var decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(memoryStream); //解密文件流

                    //确定图片大小
                    var bt = new Windows.Graphics.Imaging.BitmapTransform();
                    bt.ScaledWidth  = (uint)scaleSize.Width;
                    bt.ScaledHeight = (uint)scaleSize.Height;
                    //得到像素数值
                    var pixelProvider = await decoder.GetPixelDataAsync(
                        decoder.BitmapPixelFormat, decoder.BitmapAlphaMode, bt,
                        ExifOrientationMode.IgnoreExifOrientation, ColorManagementMode.ColorManageToSRgb);


                    //下面保存图片
                    // Now that we have the pixel data, get the destination file
                    var localFolder = ApplicationData.Current.LocalFolder;
                    //var resultsFolder = await localFolder.CreateFolderAsync("Results", CreationCollisionOption.OpenIfExists);
                    var scaledFile = await localFolder.CreateFileAsync(outfileName, CreationCollisionOption.ReplaceExisting);

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

                        var pixels = pixelProvider.DetachPixelData();
                        encoder.SetPixelData(
                            decoder.BitmapPixelFormat,
                            decoder.BitmapAlphaMode,
                            (uint)scaleSize.Width,
                            (uint)scaleSize.Height,
                            decoder.DpiX,
                            decoder.DpiY,
                            pixels
                            );
                        await encoder.FlushAsync();
                    }
                }
            }
            catch (Exception) { Debug.WriteLine("工具,图片异常"); }
        }
        /// <summary>
        /// IRandomAccessStreamからWriteableBitmapを生成する
        /// </summary>
        /// <param name="stream">ランダムアクセスストリーム</param>
        /// <returns>WriteableBitmapオブジェクト</returns>
        public static async Task<WriteableBitmap> FromStreamAsync(IRandomAccessStream stream)
        {
            // ストリームからピクセルデータを読み込む
            var decoder = await BitmapDecoder.CreateAsync(stream);
            var transform = new BitmapTransform();
            var pixelData = await decoder.GetPixelDataAsync(decoder.BitmapPixelFormat, decoder.BitmapAlphaMode,
                transform, ExifOrientationMode.RespectExifOrientation, ColorManagementMode.ColorManageToSRgb);
            var pixels = pixelData.DetachPixelData();

            // ピクセルデータからWriteableBitmapオブジェクトを生成する
            return WriteableBitmapExtensions.FromArray((int)decoder.OrientedPixelWidth, (int)decoder.OrientedPixelHeight, pixels);
        }
Beispiel #13
0
        public async Task SaveBitmapAsync(string albumFolder, uint size, string songPath)
        {
            var songFile = await StorageFile.GetFileFromPathAsync(songPath);

            using (var thumbnail = await songFile.GetThumbnailAsync(ThumbnailMode.MusicView, size) ??
                                   await songFile.GetThumbnailAsync(ThumbnailMode.VideosView, size))
            {
                if (thumbnail == null)
                    return;

                var reader = new DataReader(thumbnail);
                var fileLength = (uint)thumbnail.Size;
                await reader.LoadAsync(fileLength);

                var buffer = reader.ReadBuffer(fileLength);

                var memStream = new InMemoryRandomAccessStream();

                await memStream.WriteAsync(buffer);
                await memStream.FlushAsync();
                memStream.Seek(0);

                await ApplicationData.Current.LocalFolder.CreateFolderAsync(AlbumArtFolderName(albumFolder), CreationCollisionOption.OpenIfExists);

                var albumArtFileName = AlbumArtFileName(albumFolder, size);
                var outputFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(albumArtFileName, CreationCollisionOption.ReplaceExisting);

                // http://social.msdn.microsoft.com/Forums/windowsapps/en-US/1dda3a15-d299-40e0-b668-ec690a683f6e/how-to-resize-an-image-as-storagefile?forum=winappswithcsharp
                var decoder = await BitmapDecoder.CreateAsync(memStream);
                var transform = new BitmapTransform { ScaledHeight = size, ScaledWidth = size };
                var pixelData = await decoder.GetPixelDataAsync(
                    BitmapPixelFormat.Rgba8,
                    BitmapAlphaMode.Straight,
                    transform,
                    ExifOrientationMode.RespectExifOrientation,
                    ColorManagementMode.DoNotColorManage);

                using (var destinationStream = await outputFile.OpenAsync(FileAccessMode.ReadWrite))
                {
                    BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, destinationStream);
                    encoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Premultiplied, size, size, 96, 96, pixelData.DetachPixelData());
                    await encoder.FlushAsync();
                }
            }
        }
Beispiel #14
0
 public async Task WriteImageAsync(IRandomAccessStream sourceStream, string filename)
 {
     // 维持横纵比的重置图像大小
     BitmapDecoder decoder = await BitmapDecoder.CreateAsync(sourceStream);
     uint scaledWidth = 0;
     uint scaledHeight = 0;
     
     if (decoder.PixelWidth > decoder.PixelHeight)
     {
         scaledWidth = 600;
         double relation = (double)decoder.PixelHeight / decoder.PixelWidth;
         scaledHeight = Convert.ToUInt32(relation * scaledWidth);
     }
     else
     {
         scaledHeight = 600;
         double relation = decoder.PixelWidth / decoder.PixelHeight;
         scaledWidth = Convert.ToUInt32(relation * scaledHeight);
     }
     var transform = new BitmapTransform() { ScaledWidth = scaledWidth, ScaledHeight = scaledHeight };
     PixelDataProvider pixelData = await decoder.GetPixelDataAsync(
         BitmapPixelFormat.Rgba8,
         BitmapAlphaMode.Straight,
         transform,
         ExifOrientationMode.RespectExifOrientation,
         ColorManagementMode.DoNotColorManage);
     var folder = ApplicationData.Current.RoamingFolder;
     StorageFile destinationFile = await folder.CreateFileAsync(filename);
     using (var destinationStream = await destinationFile.OpenAsync(
       FileAccessMode.ReadWrite))
     {
         BitmapEncoder encoder = await BitmapEncoder.CreateAsync(
           BitmapEncoder.PngEncoderId, destinationStream);
         encoder.SetPixelData(BitmapPixelFormat.Rgba8,
           BitmapAlphaMode.Premultiplied,
           scaledWidth, scaledHeight, 96, 96, pixelData.DetachPixelData());
         await encoder.FlushAsync();
     }
 }
        public static async Task<Color> GetDominantColorAsync(this DataModel.Api.Image entity)
        {
            using (var ms = new InMemoryRandomAccessStream())
            {
                using (var writer = new DataWriter(ms.GetOutputStreamAt(0)))
                {
                    writer.WriteBytes(entity.Content);
                    writer.StoreAsync().GetResults();
                }

                var decoder = await BitmapDecoder.CreateAsync(ms);
                var myTransform = new BitmapTransform { ScaledHeight = 1, ScaledWidth = 1 };
                var pixels = await decoder.GetPixelDataAsync(
                    BitmapPixelFormat.Rgba8,
                    BitmapAlphaMode.Ignore,
                    myTransform,
                    ExifOrientationMode.IgnoreExifOrientation,
                    ColorManagementMode.DoNotColorManage);
                var bytes = pixels.DetachPixelData();

                return Color.FromArgb(255, bytes[0], bytes[1], bytes[2]);
            }
        }
        /// <summary>
        ///     Resizes the image presented by the <paramref name="imageData"/> to a <paramref name="newSize"/>.
        /// </summary>
        /// <param name="imageData">
        ///     The binary data of the image to resize.
        /// </param>
        /// <param name="newSize">
        ///     The size to which to resize the image.
        /// </param>
        /// <param name="keepAspectRatio">
        ///     A flag indicating whether to save original aspect ratio.
        /// </param>
        /// <returns>
        ///     The structure which contains binary data of resized image and the actial size of resized image depending on <paramref name="keepAspectRatio"/> value.
        /// </returns>
        public static async Task<ImageInfo> ResizeAsync(this byte[] imageData, Size newSize, bool keepAspectRatio)
        {
            var result = new ImageInfo();

            var decoder = await BitmapDecoder.CreateAsync(await imageData.AsRandomAccessStreamAsync());
            var percentWidth = (double)newSize.Width / (double)decoder.PixelWidth;
            var percentHeight = (double)newSize.Height / (double)decoder.PixelHeight;

            if (keepAspectRatio)
            {
                result.Size = percentWidth < percentHeight
                                    ? new Size(newSize.Width, (int)(decoder.PixelHeight * percentWidth))
                                    : new Size((int)(decoder.PixelWidth * percentHeight), newSize.Height);
            }
            else
            {
                result.Size = newSize;
            }

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

            using (var destinationStream = new InMemoryRandomAccessStream())
            {
                var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, destinationStream);
                encoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Premultiplied, (uint)result.Size.Width, (uint)result.Size.Height, 96, 96, pixelData.DetachPixelData());
                await encoder.FlushAsync();

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

                result.Data = data;
            }

            return result;
        }
Beispiel #17
0
		protected override async void init(Stream stream, bool flip, Loader.LoadedCallbackMethod loadedCallback)
		{
			try
			{
				using (var memoryStream = new InMemoryRandomAccessStream())
				{
					await RandomAccessStream.CopyAsync(stream.AsInputStream(), memoryStream);

					var decoder = await BitmapDecoder.CreateAsync(memoryStream);
					var frame = await decoder.GetFrameAsync(0);

					var transform = new BitmapTransform();
					transform.InterpolationMode = BitmapInterpolationMode.NearestNeighbor;
					transform.Rotation = BitmapRotation.None;
					var dataProvider = await decoder.GetPixelDataAsync(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Straight, transform, ExifOrientationMode.IgnoreExifOrientation, ColorManagementMode.ColorManageToSRgb);
					var data = dataProvider.DetachPixelData();
			
					int width = (int)decoder.PixelWidth;
					int height = (int)decoder.PixelHeight;
					Mipmaps = new Mipmap[1];
					Size = new Size2(width, height);

					Mipmaps[0] = new Mipmap(data, width, height, 1, 4);
					if (flip) Mipmaps[0].FlipVertical();
				}
			}
			catch (Exception e)
			{
				FailedToLoad = true;
				Loader.AddLoadableException(e);
				if (loadedCallback != null) loadedCallback(this, false);
				return;
			}

			Loaded = true;
			if (loadedCallback != null) loadedCallback(this, true);
		}
Beispiel #18
0
        public static async Task<string> SaveStreamAsync(IRandomAccessStream streamToSave, uint width, uint height, string fileName)
        {
            FolderPicker folderPicker = new FolderPicker();
            folderPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            folderPicker.ViewMode = PickerViewMode.List;
            folderPicker.FileTypeFilter.Add(".jpg");
            folderPicker.FileTypeFilter.Add(".jpeg");
            folderPicker.FileTypeFilter.Add(".png");
            StorageFolder newFolder = await folderPicker.PickSingleFolderAsync();

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

            BitmapTransform transform = new BitmapTransform();

            BitmapDecoder bmpDecoder = await BitmapDecoder.CreateAsync(streamToSave);
            PixelDataProvider pixelData = await bmpDecoder.GetPixelDataAsync(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Straight, transform, ExifOrientationMode.RespectExifOrientation, ColorManagementMode.DoNotColorManage);
            using (var destFileStream = await destination.OpenAsync(FileAccessMode.ReadWrite))
            {
                BitmapEncoder bmpEncoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, destFileStream);
                bmpEncoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Straight, width, height, 300, 300, pixelData.DetachPixelData());
                await bmpEncoder.FlushAsync();
            }
            return destination.Path;
        }
Beispiel #19
0
        public async Task<IBitmap> Load(Stream sourceStream, float? desiredWidth, float? desiredHeight)
        {
            using (var rwStream = new InMemoryRandomAccessStream()) {
                await sourceStream.CopyToAsync(rwStream.AsStreamForWrite());

                var decoder = await BitmapDecoder.CreateAsync(rwStream);

                var transform = new BitmapTransform();
                if (desiredWidth != null) {
                    transform.ScaledWidth = (uint)desiredWidth;
                    transform.ScaledHeight = (uint)desiredHeight;
                }

                var pixelData = await decoder.GetPixelDataAsync(decoder.BitmapPixelFormat, decoder.BitmapAlphaMode, transform, ExifOrientationMode.RespectExifOrientation, ColorManagementMode.ColorManageToSRgb);
                var pixels = pixelData.DetachPixelData();

                WriteableBitmap bmp = new WriteableBitmap((int)decoder.OrientedPixelWidth, (int)decoder.OrientedPixelHeight);
                using (var bmpStream = bmp.PixelBuffer.AsStream()) {
                    bmpStream.Seek(0, SeekOrigin.Begin);
                    bmpStream.Write(pixels, 0, (int)bmpStream.Length);
                    return (IBitmap) new WriteableBitmapImageBitmap(bmp);
                }
            }
        }
        private async void LoadImageUsingPixelBuffer_Click(object sender, RoutedEventArgs e)
        {
            // This method loads an image into the WriteableBitmap by decoding it into a byte stream
            // and copying the result into the WriteableBitmap's pixel buffer

            FileOpenPicker picker = new FileOpenPicker();
            picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            picker.FileTypeFilter.Add(".png");
            picker.FileTypeFilter.Add(".jpeg");
            picker.FileTypeFilter.Add(".jpg");
            picker.FileTypeFilter.Add(".bmp");

            StorageFile file = await picker.PickSingleFileAsync();

            // Ensure a file was selected
            if (file != null)
            {
                using (IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
                {
                    BitmapDecoder decoder = await BitmapDecoder.CreateAsync(fileStream);
                    
                    // Scale image to appropriate size
                    BitmapTransform transform = new BitmapTransform() { 
                        ScaledWidth = Convert.ToUInt32(Scenario4WriteableBitmap.PixelWidth),
                        ScaledHeight = Convert.ToUInt32(Scenario4WriteableBitmap.PixelHeight)};
                    
                    PixelDataProvider pixelData = await decoder.GetPixelDataAsync(
                        BitmapPixelFormat.Bgra8,    // WriteableBitmap uses BGRA format
                        BitmapAlphaMode.Straight,
                        transform,
                        ExifOrientationMode.IgnoreExifOrientation, // This sample ignores Exif orientation
                        ColorManagementMode.DoNotColorManage);

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

                    // Open a stream to copy the image contents to the WriteableBitmap's pixel buffer
                    using (Stream stream = Scenario4WriteableBitmap.PixelBuffer.AsStream())
                    {
                        await stream.WriteAsync(sourcePixels, 0, sourcePixels.Length);
                    }
                }

                // Redraw the WriteableBitmap
                Scenario4WriteableBitmap.Invalidate();
            }
        }
Beispiel #21
0
        /// <summary>
        /// 异步从网络下载图片
        /// </summary>
        /// <param name="outfileName">下载保存到本地的图片文件名</param>
        /// <param name="downloadUriString">图片uri</param>
        /// <param name="scaleSize">图片尺寸</param>
        /// <returns></returns>
        public static async Task DownloadAndScale(string outfileName, string downloadUriString, Size scaleSize)
        {
            try
            {
                Uri downLoadingUri = new Uri(downloadUriString);//创建uri对象
                HttpClient client = new HttpClient();//实例化httpclient对象
                using (var response = await client.GetAsync(downLoadingUri))
                {
                    var buffer = await response.Content.ReadAsBufferAsync();//从返回的数据中读取buffer
                    var memoryStream = new InMemoryRandomAccessStream();
                    await memoryStream.WriteAsync(buffer);//将buffer写入memorystream
                    await memoryStream.FlushAsync();//刷新
                    var decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(memoryStream);//解密文件流
                    //确定图片大小
                    var bt = new Windows.Graphics.Imaging.BitmapTransform();
                    bt.ScaledWidth = (uint)scaleSize.Width;
                    bt.ScaledHeight = (uint)scaleSize.Height;
                    //得到像素数值
                    var pixelProvider = await decoder.GetPixelDataAsync(
                        decoder.BitmapPixelFormat, decoder.BitmapAlphaMode, bt,
                        ExifOrientationMode.IgnoreExifOrientation, ColorManagementMode.ColorManageToSRgb);


                    //下面保存图片
                    // Now that we have the pixel data, get the destination file
                    var localFolder = ApplicationData.Current.LocalFolder;
                    //var resultsFolder = await localFolder.CreateFolderAsync("Results", CreationCollisionOption.OpenIfExists);
                    var scaledFile = await localFolder.CreateFileAsync(outfileName, CreationCollisionOption.ReplaceExisting);
                    using (var scaledFileStream = await scaledFile.OpenAsync(FileAccessMode.ReadWrite))
                    {
                        var encoder = await BitmapEncoder.CreateAsync(
                            BitmapEncoder.JpegEncoderId, scaledFileStream);
                        var pixels = pixelProvider.DetachPixelData();
                        encoder.SetPixelData(
                            decoder.BitmapPixelFormat,
                            decoder.BitmapAlphaMode,
                            (uint)scaleSize.Width,
                            (uint)scaleSize.Height,
                            decoder.DpiX,
                            decoder.DpiY,
                            pixels
                            );
                        await encoder.FlushAsync();
                    }
                }
            }
            catch (Exception) { Debug.WriteLine("工具,图片异常"); }
        }
        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;
        }
        private async void loadnew()
        {

            Assembly assembly = typeof(Clr_Pckr).GetTypeInfo().Assembly;
            //Stream imgStream =  assembly.GetManifestResourceStream("Color_Picker.Assets.c.png");


            InMemoryRandomAccessStream res = new InMemoryRandomAccessStream();

            using (var imgstream = assembly.GetManifestResourceStream("Dev.MartijnHoogendoorn.Inking.Behavior.Assets.c.png"))
            {
                await imgstream.CopyToAsync(res.AsStreamForWrite());
            }

           BitmapImage bmp  = new BitmapImage();
           

                                 
           
                using (IRandomAccessStream fileStream =res)// await( await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/c.png"))).OpenAsync(FileAccessMode.Read))
                {
                    BitmapDecoder decoder = await BitmapDecoder.CreateAsync(fileStream);

                    fileStream.Seek(0);


                    bmp.SetSource(fileStream);
                    ColorImg.Source = bmp;


                    BitmapTransform bt = new BitmapTransform();

                    bt.ScaledHeight = 100;
                    bt.ScaledWidth = 100;



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

                    //byte[] sourcePixels = pixelData.DetachPixelData();
                    tempBuffer = pixelData.DetachPixelData();
                }
           

        }
        async public void SaveAndCropCover(StorageFile originalImgFile)
        {


            using (IRandomAccessStream stream = await originalImgFile.OpenReadAsync())
            {


                // Create a decoder from the stream. With the decoder, we can get  
                // the properties of the image. 
                BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);




                var shortSide = Math.Min(decoder.PixelWidth, decoder.PixelHeight);
                double scale = Math.Min(1, shortSide / 480);
                Size corpSize = new Size(shortSide, shortSide);
                Point startPoint = new Point((decoder.PixelWidth - shortSide) / 2, (decoder.PixelHeight - shortSide) / 2);


                // Source: https://code.msdn.microsoft.com/windowsapps/CSWin8AppCropBitmap-52fa1ad7

                if (double.IsNaN(scale) || double.IsInfinity(scale))
                {
                    scale = 1;
                }


                // Convert start point and size to integer. 
                uint startPointX = (uint)Math.Floor(startPoint.X * scale);
                uint startPointY = (uint)Math.Floor(startPoint.Y * scale);
                uint height = (uint)Math.Floor(corpSize.Height * scale);
                uint width = (uint)Math.Floor(corpSize.Width * scale);





                // The scaledSize of original image. 
                uint scaledWidth = (uint)Math.Floor(decoder.PixelWidth * scale);
                uint scaledHeight = (uint)Math.Floor(decoder.PixelHeight * scale);



                // Refine the start point and the size.  
                if (startPointX + width > scaledWidth)
                {
                    startPointX = scaledWidth - width;
                }


                if (startPointY + height > scaledHeight)
                {
                    startPointY = scaledHeight - height;
                }


                // Create cropping BitmapTransform and define the bounds. 
                BitmapTransform transform = new BitmapTransform();
                BitmapBounds bounds = new BitmapBounds();
                bounds.X = startPointX;
                bounds.Y = startPointY;
                bounds.Height = height;
                bounds.Width = width;
                transform.Bounds = bounds;


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

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


                // Stream the bytes into a WriteableBitmap 
                WriteableBitmap cropBmp = new WriteableBitmap((int)width, (int)height);
                Stream pixStream = cropBmp.PixelBuffer.AsStream();
                pixStream.Write(pixels, 0, (int)(width * height * 4));

                this.SaveCover(cropBmp);
            }
        }
Beispiel #25
0
        /// <summary>
        /// Scales an image down. Not a very good algo, but good enough.
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        public async Task<bool> scaleImage(string filename)
        {
            var applicationData = Windows.Storage.ApplicationData.Current;
            methodLibrary mlb = new methodLibrary();
            Image image = new Image();
            int height = 0;
            int scaledHeight = 80 ;
            int scaledWidth = 80;
            int width = 0;
           
            var localFolder = applicationData.LocalFolder;
            try
            {
                StorageFile sourceFile= await localFolder.GetFileAsync(filename + ".png");
                IRandomAccessStreamWithContentType stream = await sourceFile.OpenReadAsync();
                ImageProperties properties = await sourceFile.Properties.GetImagePropertiesAsync();
               
                height = (int)properties.Height;
                width = (int)properties.Width;
                double scaleBy = 0;
                for (int scale = 10; scale > 0; scale--)
                {
                    if (((height * scale *0.1) <= 80) || ((width * scale *0.1) <= 80))
                    {
                        scaleBy = scale + 1;
                        break;
                    }
                }
                if (height != 0)
                {
                    scaledHeight = (int)(height * scaleBy * 0.1);
                }
                if (width != 0)
                {
                    scaledWidth = (int)(width * scaleBy * 0.1);
                }
                if(scaleBy == 0)
                {
                    scaledHeight = (int)(height * 0.1);
                    scaledWidth = (int)(width * 0.1);
                }

                StorageFile destinationFile = await localFolder.CreateFileAsync(filename + "_scaled.png", CreationCollisionOption.ReplaceExisting);
                using (var sourceStream = await sourceFile.OpenAsync(FileAccessMode.Read))
                {
                    BitmapDecoder decoder = await BitmapDecoder.CreateAsync(sourceStream);
                    BitmapTransform transform = new BitmapTransform() { ScaledHeight = (uint)scaledHeight, ScaledWidth = (uint)scaledWidth };
                    PixelDataProvider pixelData = await decoder.GetPixelDataAsync(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Straight, transform, ExifOrientationMode.RespectExifOrientation, ColorManagementMode.DoNotColorManage);
                    
                    Debug.WriteLine("Actual height : " + height + "  Scaled height : " + scaledHeight);
                    Debug.WriteLine("Actual width : " + width+ "  Scaled width : " + scaledWidth);
                    using (var destinationStream = await destinationFile.OpenAsync(FileAccessMode.ReadWrite))
                    {
                        BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, destinationStream);
                        encoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Premultiplied, (uint)scaledWidth, (uint)scaledHeight, 96, 96, pixelData.DetachPixelData());
                        await encoder.FlushAsync();
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Exception in scaling image assets : " + ex);
                await mlb.writeToLogFile(DateTime.UtcNow.ToString() + "Exception in scaling image assets", false);
                return false;
            }
            return true;
        }
Beispiel #26
0
        /// <summary>
        /// Applies the user-provided scale and rotation operation to a new image file picked by the user.
        /// This method writes the edited pixel data to the new file without
        /// any regard to existing metadata or other information in the original file.
        /// </summary>
        private async void SaveAs_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                rootPage.NotifyUser("Saving to a new file...", NotifyType.StatusMessage);

                StorageFile inputFile = await m_futureAccess.GetFileAsync(m_fileToken);
                StorageFile outputFile = await Helpers.GetFileFromSavePickerAsync();
                Guid encoderId;

                switch (outputFile.FileType)
                {
                    case ".png":
                        encoderId = BitmapEncoder.PngEncoderId;
                        break;
                    case ".bmp":
                        encoderId = BitmapEncoder.BmpEncoderId;
                        break;
                    case ".jpg":
                    default:
                        encoderId = BitmapEncoder.JpegEncoderId;
                        break;
                }

                using (IRandomAccessStream inputStream = await inputFile.OpenAsync(FileAccessMode.Read),
                           outputStream = await outputFile.OpenAsync(FileAccessMode.ReadWrite))
                {
                    // BitmapEncoder expects an empty output stream; the user may have selected a
                    // pre-existing file.
                    outputStream.Size = 0;

                    // Get pixel data from the decoder. We apply the user-requested transforms on the
                    // decoded pixels to take advantage of potential optimizations in the decoder.
                    BitmapDecoder decoder = await BitmapDecoder.CreateAsync(inputStream);
                    BitmapTransform transform = new BitmapTransform();

                    // Scaling occurs before flip/rotation, therefore use the original dimensions
                    // (no orientation applied) as parameters for scaling.
                    transform.ScaledHeight = (uint)(decoder.PixelHeight * m_scaleFactor);
                    transform.ScaledWidth = (uint)(decoder.PixelWidth * m_scaleFactor);
                    transform.Rotation = Helpers.ConvertToBitmapRotation(m_userRotation);

                    // Fant is a relatively high quality interpolation mode.
                    transform.InterpolationMode = BitmapInterpolationMode.Fant;

                    // The BitmapDecoder indicates what pixel format and alpha mode best match the
                    // natively stored image data. This can provide a performance and/or quality gain.
                    BitmapPixelFormat format = decoder.BitmapPixelFormat;
                    BitmapAlphaMode alpha = decoder.BitmapAlphaMode;

                    PixelDataProvider pixelProvider = await decoder.GetPixelDataAsync(
                        format,
                        alpha,
                        transform,
                        ExifOrientationMode.RespectExifOrientation,
                        ColorManagementMode.ColorManageToSRgb
                        );

                    byte[] pixels = pixelProvider.DetachPixelData();

                    // Write the pixel data onto the encoder. Note that we can't simply use the
                    // BitmapTransform.ScaledWidth and ScaledHeight members as the user may have
                    // requested a rotation (which is applied after scaling).
                    BitmapEncoder encoder = await BitmapEncoder.CreateAsync(encoderId, outputStream);
                    encoder.SetPixelData(
                        format,
                        alpha,
                        (uint)((double)m_displayWidthNonScaled * m_scaleFactor),
                        (uint)((double)m_displayHeightNonScaled * m_scaleFactor),
                        decoder.DpiX,
                        decoder.DpiY,
                        pixels
                        );

                    await encoder.FlushAsync();

                    rootPage.NotifyUser("Successfully saved a copy: " + outputFile.Name, NotifyType.StatusMessage);
                }
            }
            catch (Exception err)
            {
                rootPage.NotifyUser("Error: " + err.Message, NotifyType.ErrorMessage);
                ResetPersistedState();
                ResetSessionState();
            }
        }
        /// <summary>
        /// Resizes the specified stream.
        /// </summary>
        /// <param name="sourceStream">The source stream to resize.</param>
        /// <param name="newWidth">The width of the resized image.</param>
        /// <param name="newHeight">The height of the resized image.</param>
        /// <returns>The resized image stream.</returns>
        public static async Task<InMemoryRandomAccessStream> Resize(IRandomAccessStream sourceStream, uint newWidth,
            uint newHeight)
        {
            var destinationStream = new InMemoryRandomAccessStream();

            var decoder = await BitmapDecoder.CreateAsync(sourceStream);
            var transform = new BitmapTransform { ScaledWidth = newWidth, ScaledHeight = newHeight };

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

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

            encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied, newWidth, newHeight, 96, 96,
                pixelData.DetachPixelData());
            await encoder.FlushAsync();

            return destinationStream;
        }
Beispiel #28
0
        /// <summary>
        /// rotates the image by the currentRotation value
        /// </summary>
        /// <param name="mrs">InMemoryRandomAccessStream containg the image data</param>
        /// <returns>byte [] to be sent through processing</returns>
        async private Task<byte[]> RotateImage(InMemoryRandomAccessStream mrs)
        {
            BitmapDecoder decoder = await BitmapDecoder.CreateAsync(mrs).AsTask().ConfigureAwait(false);
            uint w = decoder.PixelWidth; uint h = decoder.PixelHeight;
            if (currentRotation.Equals(VideoRotation.Clockwise90Degrees) || currentRotation.Equals(VideoRotation.Clockwise270Degrees))
            {
                w = decoder.PixelHeight;
                h = decoder.PixelWidth;
            }

            BitmapTransform transform = new BitmapTransform() { Rotation = (BitmapRotation)currentRotation };

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

            byte[] pixels = pixelData.DetachPixelData();

            BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, mrs);
            encoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Premultiplied, w, h, 96, 96, pixels);
            await encoder.FlushAsync().AsTask().ConfigureAwait(false);

            mrs.Seek(0);
            byte[] outBytes = new byte[mrs.Size];
            await mrs.AsStream().ReadAsync(outBytes, 0, outBytes.Length);

            MemoryStream ms = new MemoryStream(outBytes);
            var currentApp = (App)App.Current;
            currentApp.CurrentImageRecog = ms;

            return outBytes;
        }
        /// <summary>
        /// 改变图片的大小
        /// </summary>
        /// <param name="sourceStream">包含图片数据的流</param>
        /// <param name="expWidth">期望的宽度</param>
        /// <param name="expHeight">期望的高度</param>
        /// <returns></returns>
        public static async Task<IRandomAccessStream> ResizeImageHard(IRandomAccessStream sourceStream, uint expWidth,uint expHeight)
        {
            BitmapDecoder decoder = await BitmapDecoder.CreateAsync(sourceStream);
            uint height = decoder.PixelHeight;
            uint weight = decoder.PixelWidth;

            uint destHeight = height > expHeight ? expHeight : height;
            uint destWeight = weight> expWidth? expWidth : weight;

            BitmapTransform transform = new BitmapTransform()
            {
                ScaledWidth = destWeight,
                ScaledHeight = destHeight
            };

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

            var tempfile = await ApplicationData.Current.LocalFolder.CreateFileAsync("temp.jpg", CreationCollisionOption.ReplaceExisting);
            IRandomAccessStream destStream = await tempfile.OpenAsync(FileAccessMode.ReadWrite);

            BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, destStream);
            encoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Straight, transform.ScaledWidth, transform.ScaledHeight, 100, 100, pixelData.DetachPixelData());
            await encoder.FlushAsync();

            //把流的位置变为0,这样才能从头读出图片流
            destStream.Seek(0);

            return destStream;
        }
    private static async Task<WriteableBitmap> FromContentWinRt(this WriteableBitmap bmp, Uri uri)
    {
      if (bmp == null) throw new ArgumentNullException("bmp");
      // Decode pixel data
      var file = await StorageFile.GetFileFromApplicationUriAsync(uri);
      var decoder = await BitmapDecoder.CreateAsync(await file.OpenAsync(FileAccessMode.Read));
      var transform = new BitmapTransform();
      var pixelData = await decoder.GetPixelDataAsync(decoder.BitmapPixelFormat, decoder.BitmapAlphaMode, transform, ExifOrientationMode.RespectExifOrientation, ColorManagementMode.ColorManageToSRgb);

      // Swap R and B channels
      var pixels = pixelData.DetachPixelData();
      for (var i = 0; i < pixels.Length; i += 4)
      {
        var r = pixels[i];
        var b = pixels[i + 2];
        pixels[i] = b;
        pixels[i + 2] = r;
      }

      // Copy to WriteableBitmap
      bmp = new WriteableBitmap((int)decoder.PixelWidth, (int)decoder.PixelHeight);
      using (var bmpStream = bmp.PixelBuffer.AsStream())
      {
        bmpStream.Seek(0, SeekOrigin.Begin);
        bmpStream.Write(pixels, 0, (int)bmpStream.Length);
        return bmp;
      }
    }
Beispiel #31
0
        private async Task<byte[]> GetImageAsByteAsync(Guid format, int quality, int desiredWidth, int desiredHeight)
        {
            if (internalImage == null || internalImage.Source == null)
                return null;

            var bitmap = internalImage.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.Linear
                    };
                    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())
            {
                var 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;
            }
        }