C# 如何使用CanvasBitmap.CreateFromBytes和来自jpg图像的字节[]

C# 如何使用CanvasBitmap.CreateFromBytes和来自jpg图像的字节[],c#,image,uwp,win2d,C#,Image,Uwp,Win2d,我在内存中有一个JPG图像作为字节[]可用 我需要创建一个画布位图来绘制此图像,最终创建一个可指定给SpriteVisual的CompositionDrawingSurface。我需要一个超快速的方法来做这个 我使用CanvasBitmap.LoadAsync(ICanvasResourceCreator,irandomaccesstream)成功地完成了任务,但是这种方法花费太多(超过10毫秒),而使用CanvasBitmap.CreateFromBytes(ICanvasResourceCr

我在内存中有一个JPG图像作为字节[]可用

我需要创建一个画布位图来绘制此图像,最终创建一个可指定给SpriteVisual的CompositionDrawingSurface。我需要一个超快速的方法来做这个

我使用
CanvasBitmap.LoadAsync(ICanvasResourceCreator,irandomaccesstream)
成功地完成了任务,但是这种方法花费太多(超过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所束缚,这可能没有多大帮助。只是想一想。

您不需要先将JPEG(压缩)格式转换为原始字节数组吗?谢谢@nbura,您有一个快速的方法来实现这一点吗?很遗憾,我不知道一个快速的方法,很抱歉。但是,如果你想避免花在解压上的时间,为什么不将图像保存为JPEG以外的其他格式呢?@nbura成功了!你愿意把答案写下来,让我把它标记为接受吗?当然!很高兴听到它起作用了