如何从另一个 SoftwareBitmap (UWP) 的区域创建 SoftwareBitmap [英] How to create a SoftwareBitmap from region of another SoftwareBitmap (UWP)
问题描述
创建具有另一个区域副本(例如BitmapBounds
)的新Windows.Graphics.Imaging.SoftwareBitmap
对象的最有效(最简单)方法是什么?SoftwareBitmap
对象(深拷贝),用于 Windows UWP 应用程序?
What is the most efficient (easiest) way to create a new Windows.Graphics.Imaging.SoftwareBitmap
object with a copy of region (BitmapBounds
for example) of another SoftwareBitmap
object (deep copy), for Windows UWP application?
SoftwareBitmap
没有这样的构造函数或静态方法.所有 Copy* 方法都复制整个位图.
There is no such constructor or static method for SoftwareBitmap
. All Copy* methods copies whole bitmap.
我使用 WriteableBitmap
来实现这一点:
I played with WriteableBitmap
to achieve this:
SoftwareBitmap CreateFromBitmap(SoftwareBitmap bmp, Rect rect)
{
WriteableBitmap wbmpIn = new WriteableBitmap(bmp.PixelWidth, bmp.PixelHeight);
bmp.CopyToBuffer(wbmpIn.PixelBuffer);
WriteableBitmap wbmpOut = new WriteableBitmap((int)rect.Width, (int)rect.Height);
wbmpOut.Blit(new Rect(0, 0, rect.Width, rect.Height), wbmpIn, rect);
SoftwareBitmap ret = new SoftwareBitmap(bmp.BitmapPixelFormat, (int)rect.Width, (int)rect.Height);
ret.CopyFromBuffer(wbmpOut.PixelBuffer);
return ret;
}
但它看起来并不有效 - 涉及两个 CopyFromBuffer() 和一个 Blit().
But it doesn't look effective - involves two CopyFromBuffer() and one Blit().
有没有更有效的解决方案?
Is there a more efficient solution?
推荐答案
您可以参考以下代码,它可以从现有的 SoftwareBitmap 创建一个新的裁剪 SoftwareBitmap.
You can refer to following code, it can create a new cropped SoftwareBitmap from an existing SoftwareBitmap.
private async Task<SoftwareBitmap> CreateFromBitmap(SoftwareBitmap softwareBitmap, Rect rect)
{
using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream())
{
BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.BmpEncoderId, stream);
encoder.SetSoftwareBitmap(softwareBitmap);
encoder.BitmapTransform.Bounds = new BitmapBounds()
{
X = (uint)rect.X,
Y = (uint)rect.Y,
Height = (uint)rect.Height,
Width = (uint)rect.Width
};
await encoder.FlushAsync();
BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);
return await decoder.GetSoftwareBitmapAsync(softwareBitmap.BitmapPixelFormat, softwareBitmap.BitmapAlphaMode);
}
}
var croppedBitmap = await CreateFromBitmap(sourceSoftwareBmp, new Rect(0, 0, 200, 100));
这篇关于如何从另一个 SoftwareBitmap (UWP) 的区域创建 SoftwareBitmap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!