//设置源图ImageSource为WriteableBitmap类型 BitmapImage himage = this.imageTarget2.Source as BitmapImage; RandomAccessStreamReference random = RandomAccessStreamReference.CreateFromUri(himage.UriSource); using (IRandomAccessStream stream = await random.OpenReadAsync()) { stream.Seek(0); BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream); BitmapFrame bitmapFrame = await decoder.GetFrameAsync(0); // Get the pixels var transform = new BitmapTransform { ScaledWidth = decoder.PixelWidth, ScaledHeight = decoder.PixelHeight }; PixelDataProvider dataProvider = await bitmapFrame.GetPixelDataAsync(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, transform, ExifOrientationMode.RespectExifOrientation, ColorManagementMode.ColorManageToSRgb); var image_array = dataProvider.DetachPixelData(); var image_array_width = (int)decoder.PixelWidth; var image_array_height = (int)decoder.PixelHeight; var writeableBitmap = new WriteableBitmap(image_array_width, image_array_height); stream.Seek(0); await writeableBitmap.SetSourceAsync(stream); this.imageSource1.Source = writeableBitmap;//WriteableBitmap 类型很重要 }
//裁切方法 public async static Task<SoftwareBitmap> GetCroppedBitmapAsync(SoftwareBitmap softwareBitmap, uint x, uint y, uint width, uint height) { using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream()) { BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.BmpEncoderId, stream); encoder.SetSoftwareBitmap(softwareBitmap); encoder.BitmapTransform.Bounds = new BitmapBounds() { X = x, Y = y, Height = height, Width = width }; await encoder.FlushAsync(); BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream); return await decoder.GetSoftwareBitmapAsync(softwareBitmap.BitmapPixelFormat, softwareBitmap.BitmapAlphaMode); } }
//实例: WriteableBitmap wb = this.imageSource1.Source as WriteableBitmap; ; SoftwareBitmap sb = new SoftwareBitmap(BitmapPixelFormat.Bgra8, wb.PixelWidth, wb.PixelHeight); sb.CopyFromBuffer(wb.PixelBuffer);//WriteableBitmap转为SoftwareBitmap var sbmp = await GetCroppedBitmapAsync(sb, 0, 50, 100, 100);//调用裁切方法 WriteableBitmap writeableBitmap = new WriteableBitmap(sbmp.PixelWidth, sbmp.PixelHeight); sbmp.CopyToBuffer(writeableBitmap.PixelBuffer);//SoftwareBitmap转为WriteableBitmap this.imageTarget2.Source = writeableBitmap;//设置目标图ImageSource为WriteableBitmap类型