如何将 CanvasBitmap.CreateFromBytes 与来自 jpg 图像的 byte[] 一起使用
How to use CanvasBitmap.CreateFromBytes with a byte[] coming from a jpg image
我在内存中有一个 JPG 图像作为 byte[]。
我需要创建一个 CanvasBitmap 来绘制此图像,最终创建一个我可以分配给 SpriteVisual 的 CompositionDrawingSurface。我需要一种超快速的方法来做到这一点!!
我使用CanvasBitmap.LoadAsync(ICanvasResourceCreator, IRandomAccessStream)
成功完成了任务,但是这种方法耗时太多(超过10毫秒),而使用CanvasBitmap.CreateFromBytes(ICanvasResourceCreator, byte[], int, int, DirectXPixelFormat)
只需要1毫秒,这符合我的性能要求.
不幸的是,使用 CanvasBitmap.CreateFromBytes
结果不是正确的图像,而是一堆点,这让我觉得图像的编码/解码有问题。
这是我试过的代码:
byte[] imgBytes = await ReadBinaryFile(path); // read the binary content of a JPG image, for the example purpose (in the real environment, the byte[] comes from in memory caches...)
using (CanvasBitmap canvasBitmap = CanvasBitmap.CreateFromBytes(s_canvasDevice, imgBytes, 600, 800, DirectXPixelFormat.B8G8R8A8UIntNormalized))
{
// Draw the image to the surface
using (CanvasDrawingSession session = CanvasComposition.CreateDrawingSession(surface))
{
session.Clear(Color.FromArgb(0, 0, 0, 0));
session.DrawImage(canvasBitmap, new Rect(0, 0, 600, 800), new Rect(0, 0, 600, 800));
}
}
我错过了什么?
我如何处理 byte[] imgBytes
以便它可以用作 CanvasBitmap.CreateFromBytes
的输入?
谢谢!
您需要先将 JPEG(压缩)格式转换为原始字节数组。您不能使用 ReadBinaryFile()
直接从磁盘读取 JPEG 图像并显示它。
我猜测大部分性能问题是由于 LoadAsync()
解压缩 JPEG 所花费的时间。您可以通过以不同的未压缩图像格式保存来提高性能。
此外,如果您确实需要读取 JPEG,或者即使使用其他图像格式它仍然很慢:可能有一些方法可以利用 LoadAsync()
并行加载多个文件。但是我不知道该怎么做,而且如果您遇到文件 I/O 的瓶颈,它可能没有多大帮助。只是一个想法。
我在内存中有一个 JPG 图像作为 byte[]。
我需要创建一个 CanvasBitmap 来绘制此图像,最终创建一个我可以分配给 SpriteVisual 的 CompositionDrawingSurface。我需要一种超快速的方法来做到这一点!!
我使用CanvasBitmap.LoadAsync(ICanvasResourceCreator, IRandomAccessStream)
成功完成了任务,但是这种方法耗时太多(超过10毫秒),而使用CanvasBitmap.CreateFromBytes(ICanvasResourceCreator, byte[], int, int, DirectXPixelFormat)
只需要1毫秒,这符合我的性能要求.
不幸的是,使用 CanvasBitmap.CreateFromBytes
结果不是正确的图像,而是一堆点,这让我觉得图像的编码/解码有问题。
这是我试过的代码:
byte[] imgBytes = await ReadBinaryFile(path); // read the binary content of a JPG image, for the example purpose (in the real environment, the byte[] comes from in memory caches...)
using (CanvasBitmap canvasBitmap = CanvasBitmap.CreateFromBytes(s_canvasDevice, imgBytes, 600, 800, DirectXPixelFormat.B8G8R8A8UIntNormalized))
{
// Draw the image to the surface
using (CanvasDrawingSession session = CanvasComposition.CreateDrawingSession(surface))
{
session.Clear(Color.FromArgb(0, 0, 0, 0));
session.DrawImage(canvasBitmap, new Rect(0, 0, 600, 800), new Rect(0, 0, 600, 800));
}
}
我错过了什么?
我如何处理 byte[] imgBytes
以便它可以用作 CanvasBitmap.CreateFromBytes
的输入?
谢谢!
您需要先将 JPEG(压缩)格式转换为原始字节数组。您不能使用 ReadBinaryFile()
直接从磁盘读取 JPEG 图像并显示它。
我猜测大部分性能问题是由于 LoadAsync()
解压缩 JPEG 所花费的时间。您可以通过以不同的未压缩图像格式保存来提高性能。
此外,如果您确实需要读取 JPEG,或者即使使用其他图像格式它仍然很慢:可能有一些方法可以利用 LoadAsync()
并行加载多个文件。但是我不知道该怎么做,而且如果您遇到文件 I/O 的瓶颈,它可能没有多大帮助。只是一个想法。