You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VB.Net 6.0保存PNG绘图触发GDI+外部异常问题求助

解决GDI+保存PNG时的ExternalException错误

常见原因及修复步骤

1. 避开系统保护目录写入

C盘根目录受Windows UAC权限保护,普通程序默认无写入权限,建议改为写入用户可访问目录,比如桌面、文档或AppData文件夹。

2. 及时释放GDI+资源

绘图用的Graphics、SolidBrush等对象属于非托管资源,需手动释放,否则会导致Bitmap被锁定,GDI+无法完成保存操作。推荐用Using语句自动管理资源生命周期。

3. 修正Bitmap初始化时机

类级别直接初始化Bitmap时,窗体的Width和Height可能还未加载为实际运行尺寸,且长期持有Bitmap会造成资源泄漏,建议在需要绘图的事件(如按钮点击)内创建Bitmap。

4. 移除过时的权限检查

.NET 6中FileIOPermission已被标记为过时,且无法处理UAC这类系统级权限限制,直接通过Try-Catch捕获IO相关异常更实用。

修复后的完整代码

Imports System.Drawing
Imports System.Drawing.Imaging
Imports System.IO

Public Class Form1
    Dim m, i As Integer
    Dim h, Pi, Pi2, u, v, x, y As Single

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        ' 使用窗体当前尺寸创建Bitmap,用Using自动释放
        Using bmp As New Bitmap(Me.Width, Me.Height)
            ' 自动释放Graphics资源
            Using g As Graphics = Graphics.FromImage(bmp)
                m = 1000
                h = 1 / 100
                Pi = Math.PI ' 用系统内置高精度PI值替代手动定义
                Pi2 = Pi * 2
                x = 150
                y = 150

                For i = 1 To m
                    u = x * Math.Cos(h * Pi2) + y * Math.Sin(h * Pi2)
                    v = y * Math.Cos(h * Pi2) - x * Math.Sin(h * Pi2)
                    x = u
                    y = v
                    ' 自动释放SolidBrush资源
                    Using brush As New SolidBrush(Color.FromArgb(255, 0, 0))
                        g.FillRectangle(brush, x, y, 1, 1)
                    End Using
                Next i
            End Using

            ' 保存到桌面目录,避免权限问题
            Dim savePath As String = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "graph.png")
            Try
                bmp.Save(savePath, ImageFormat.Png)
                MessageBox.Show($"图片已保存到:{savePath}")
            Catch ex As Exception
                MessageBox.Show($"保存失败:{ex.Message}")
            End Try
        End Using
    End Sub
End Class

额外优化说明

  • 替换手动定义的3.14为Math.PI,提升计算精度
  • 对所有GDI+对象使用Using语句,彻底避免资源泄漏
  • 保存路径改为桌面,既无权限问题又方便查找结果

内容的提问来源于stack exchange,提问作者user20402884

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 08:20:49