处理Image/Bitmap和PictureBox的正确方法

发布于 2024-09-01 06:23:39 字数 1253 浏览 9 评论 0原文

我正在尝试开发 Windows Mobile 6(在 WF/C# 中)应用程序。只有一种窗体,并且窗体上只有一个 PictureBox 对象。在上面我画了所有想要的控件或任何我想要的东西。

我正在做两件事。绘制自定义形状并从 .png 文件加载位图。

下一行在加载时锁定文件(这是不希望的情况):

Bitmap bmp = new Bitmap("file.png");

所以我使用另一种方式来加载位图。

public static Bitmap LoadBitmap(string path) {
    using (Bitmap original = new Bitmap(path))
    {
        return new Bitmap(original);
    }
}

我猜这要慢得多,但我不知道有什么更好的方法来加载图像,同时快速释放文件锁。

现在,在绘制图像时,我使用了一种方法:

public void Draw() {
    Bitmap bmp = new Bitmap(240,320);
    Graphics g = Graphics.FromImage(bmp);

    // draw something with Graphics here.
    g.Clear(Color.Black);
    g.DrawImage(Images.CloseIcon, 16, 48);
    g.DrawImage(Images.RefreshIcon, 46, 48);
    g.FillRectangle(new SolidBrush(Color.Black), 0, 100, 240, 103);

    pictureBox.Image = bmp; 
}

但这似乎是某种内存泄漏。如果我持续这样做太久,应用程序最终会崩溃。

因此,我有 3 个问题:

1.) 在不锁定文件的情况下从文件加载位图的更好方法是什么?

2.) 哪些对象需要在 Draw() 函数中手动处置(以及按什么顺序),这样就不会出现内存泄漏,也不会抛出 ObjectDisposeException?

3.) 如果 pictureBox.Image 设置为 bmp,如代码的最后一行,pictureBox.Image.Dispose() 将仅处理与维护 pictureBox.Image 或底层 Bitmap 相关的资源设置为它?

I am trying to develop a Windows Mobile 6 (in WF/C#) application. There is only one form and on the form there is only a PictureBox object. On it I draw all desired controls or whatever I want.

There are two things I am doing. Drawing custom shapes and loading bitmaps from .png files.

The next line locks the file when loading (which is an undesired scenario):

Bitmap bmp = new Bitmap("file.png");

So I am using another way to load bitmap.

public static Bitmap LoadBitmap(string path) {
    using (Bitmap original = new Bitmap(path))
    {
        return new Bitmap(original);
    }
}

This is I guess much slower, but I don't know any better way to load an image, while quickly releasing the file lock.

Now, when drawing an image there is method that I use:

public void Draw() {
    Bitmap bmp = new Bitmap(240,320);
    Graphics g = Graphics.FromImage(bmp);

    // draw something with Graphics here.
    g.Clear(Color.Black);
    g.DrawImage(Images.CloseIcon, 16, 48);
    g.DrawImage(Images.RefreshIcon, 46, 48);
    g.FillRectangle(new SolidBrush(Color.Black), 0, 100, 240, 103);

    pictureBox.Image = bmp; 
}

This however seems to be some kind of a memory leak. And if I keep doing it for too long, the application eventually crashes.

Therefore, I have 3 questions:

1.) What is the better way for loading bitmaps from files without locking the file?

2.) What objects needs to be manually disposed in the Draw() function (and in which order) so there's no memory leak and no ObjectDisposedException throwing?

3.) If pictureBox.Image is set to bmp, like in the last line of the code, would pictureBox.Image.Dispose() dispose only resources related to maintaining the pictureBox.Image or the underlying Bitmap set to it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

鲸落 2024-09-08 06:23:39

我认为不存在真正的内存泄漏。问题是你不处理旧的位图,而是由 GC 来清理这些东西。但没有确定的方法来说明这种情况何时会发生。

所以我认为如果你要循环浏览很多图片,你会看到一些内存增加,而在其他时候它会下降或在一个位置抵抗。

我没有测试它,但也许这会有所帮助,使其更具确定性:

public void Draw() {
    Bitmap bmp = new Bitmap(240,320);
    using(var g = Graphics.FromImage(bmp))
    using(var solidBrush = SolidBrush(Color.Black))
    {
        // draw something with Graphics here.
        g.Clear(Color.Black);
        g.DrawImage(Images.CloseIcon, 16, 48);
        g.DrawImage(Images.RefreshIcon, 46, 48);
        g.FillRectangle(solidBrush, 0, 100, 240, 103);

        //Backup old image in pictureBox
        var oldImage = pictureBox.Image;
        pictureBox.Image = bmp; 
        //Release resources from old image
        if(oldImage != null)
            ((IDisposable)oldImage).Dispose();            
    }
}

更新

和受 jack30lena 启发的另一个想法:

public static Bitmap LoadBitmap(string path)
{
    //Open file in read only mode
    using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read))
    //Get a binary reader for the file stream
    using (BinaryReader reader = new BinaryReader(stream))
    {
        //copy the content of the file into a memory stream
        var memoryStream = new MemoryStream(reader.ReadBytes((int)stream.Length));
        //make a new Bitmap object the owner of the MemoryStream
        return new Bitmap(memoryStream);
    }
}

我的第二个代码示例背后的想法是摆脱文件句柄并将文件内容复制到内存中。之后,位图将获得 MemoryStream 的所有权,该内存流将通过调用 oldImage.Dispose() 来在我的第一个示例中进行处置。

通过使用这种方法,内存中的图像永远不会超过两个,这样只会因真正的大图片或少量 RAM 导致 OutOfMemoryExceptions。

I don't think there is a real memory leak. The problem is that you don't dispose the old bitmap, it is up to the GC to clean the stuff. But there is no deterministic way to say when this will happen.

So i think if you're going to loop through a lot of pictures, you'll see some memory increase and at some other point it will fall down or resist at one position.

I didn't test it, but maybe this will help a little to make it more deterministic:

public void Draw() {
    Bitmap bmp = new Bitmap(240,320);
    using(var g = Graphics.FromImage(bmp))
    using(var solidBrush = SolidBrush(Color.Black))
    {
        // draw something with Graphics here.
        g.Clear(Color.Black);
        g.DrawImage(Images.CloseIcon, 16, 48);
        g.DrawImage(Images.RefreshIcon, 46, 48);
        g.FillRectangle(solidBrush, 0, 100, 240, 103);

        //Backup old image in pictureBox
        var oldImage = pictureBox.Image;
        pictureBox.Image = bmp; 
        //Release resources from old image
        if(oldImage != null)
            ((IDisposable)oldImage).Dispose();            
    }
}

Update

And another idea inspired by jack30lena:

public static Bitmap LoadBitmap(string path)
{
    //Open file in read only mode
    using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read))
    //Get a binary reader for the file stream
    using (BinaryReader reader = new BinaryReader(stream))
    {
        //copy the content of the file into a memory stream
        var memoryStream = new MemoryStream(reader.ReadBytes((int)stream.Length));
        //make a new Bitmap object the owner of the MemoryStream
        return new Bitmap(memoryStream);
    }
}

The idea behind my second code sample is to get rid of the file handle and copy the file content into memory. Afterwards the Bitmap will taken ownership of the MemoryStream which will be disposed within my first sample by calling the oldImage.Dispose().

By using this approach there should never be more then two images in memory, thous leading only to OutOfMemoryExceptions by really big pictures or small amount of RAM.

°如果伤别离去 2024-09-08 06:23:39

1:
我不知道它是否适用于 Windows Mobile,但请尝试以下操作:

FileStream bitmapFile = new FileStream("mybitmap.bmp", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
Image loaded = new Bitmap(bitmapFile);

2:必须处置 SolidBrush。处置有一般规则。 --> “由您实例化的实现 dispose 的每个对象都必须手动处置,除非对象返回/引用/输出值”

在这种情况下,最好使用 using< /code> 语句

using (new objecttodispose){ ..... } 

using 语句将确保在任何情况下(例如例外)调用 Dispose()

3: Dispose() 将释放位图资源。

1:
I dont know if it works in Windows Mobile but try this:

FileStream bitmapFile = new FileStream("mybitmap.bmp", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
Image loaded = new Bitmap(bitmapFile);

2: The SolidBrush must be disposed. There is a general rule for dispose. --> "every object, instanciated by you, that implements dispose must be disposed manually, exept when the object is a return/ref/out value"

In this case it is better to use a using statement

using (new objecttodispose){ ..... } 

The using statement will ensure the call of Dispose() in any case (exception for example).

3: Dispose() will free the bitmap ressources.

权谋诡计 2024-09-08 06:23:39

您可以从控制器获取 Bitmap 对象,然后将其分配给 PictureBox 的 image 属性。您还应该处理 PictureBox 的当前图像以释放资源。

 var bmp = controller.GetBitmap();
 pictureBox1.Image.Dispose(); // this releases bitmap resources, required
 pictureBox1.Image = bmp;

You can get an Bitmap object from your controller and then assign it to image property of PictureBox. You should also dispose the current image of PictureBox to release the resource.

 var bmp = controller.GetBitmap();
 pictureBox1.Image.Dispose(); // this releases bitmap resources, required
 pictureBox1.Image = bmp;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文