gpt4 book ai didi

c# - 从流中加载图像而不保持流打开

转载 作者:可可西里 更新时间:2023-11-01 07:53:54 25 4
gpt4 key购买 nike

是否可以使用 System.Drawing.Image 的 FromStream 方法而不必在图像的生命周期内保持流打开?

我有一个应用程序,它使用 Image.FromStream 的组合从资源文件中加载一堆工具栏图形。和 Assembly.GetManifestResourceStream .

我遇到的问题是,虽然这在 Windows 7 上运行良好,但在 Windows XP 上,如果链接到这些图像之一的用户界面元素被禁用,应用程序就会崩溃。在 Windows 7 上,图像以灰度呈现。在 XP 上,它会因内存不足异常而崩溃。

经过一番纠结后,我终于找到了图像的初始加载。当然,如果我创建任何实现 IDisposable 的对象,它也用相同的方法销毁,我将它包装在一个 using 语句中,例如

using (Stream resourceStream = assembly.GetManifestResourceStream(resourceName))
{
image = Image.FromStream(resourceStream);
}

如果我删除 using 语句以便不释放流,那么应用程序将不再在 XP 上崩溃。但是我现在有一堆“孤儿”流 - 图像存储在命令类中,这些图像在它们自己被处理时正确地处理图像,但原始流不是。

我检查了 FromStream 的文档并确认流需要保持打开状态。然而,为什么它没有在 Windows 7 开发系统上崩溃和烧毁是一个谜!

我真的不想让这个流四处闲逛,我当然不想存储对这个流的引用以及图像,以便我以后可以处理它。我只需要那个流一次,所以我想摆脱它:)

是否可以创建图像然后在那里终止流?

最佳答案

流需要打开的原因是 following :

GDI+, and therefore the System.Drawing namespace, may defer the decoding of raw image bits until the bits are required by the image. Additionally, even after the image has been decoded, GDI+ may determine that it is more efficient to discard the memory for a large Bitmap and to re-decode later. Therefore, GDI+ must have access to the source bits for the image for the life of the Bitmap or the Image object.

已记录的解决方法是使用 Graphics.DrawImage 创建非索引图像,或从原始图像创建索引 Bitmap,如下所述:

Bitmap and Image constructor dependencies

关于c# - 从流中加载图像而不保持流打开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3845456/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com