VB .NET 2010:将大位图另存为文件




我有一个应用程序,它创建了一个由所有 1600 万种颜色组成的Bitmap对象。最终的位图将测量 4096 × 4096 像素。
当我尝试调用位图的Save()方法时,它会导致错误。
这是出现的错误消息:

GDI+ 中发生一般错误。

请试着在这件事上帮助我。提前感谢!


注意:看看下面源代码的最后几行注释。我已经在那里解释了疑问。
源代码:
Public Sub CreateAllColorImage()
    Dim BMP As New Bitmap(4096, 4096) 'This BMP variable is where the image will be created.'
    Dim CurrX = 0
    Dim CurrY = 0
    Dim ExitFors As Boolean = False
    For R = 0 To 255
        For G = 0 To 255
            For B = 0 To 255
                BMP.SetPixel(CurrX, CurrY, Color.FromArgb(R, G, B))
                CurrY += 1 'Increment the Y axis to move to next pixel.'
                If CurrY > 4095 Then CurrX += 1 : CurrY = 0 'Move to next row, or increment X axis, if the last pixel on the Y axis is reached'
                If CurrX > 4095 Then ExitFors = True 'Set the variable to exit the FOR loops if the very last pixel on the whole image is reached.'
                If ExitFors Then Exit For 'Exit the FOR loop if the variable is true.'
            Next
            If ExitFors Then Exit For 'Exit the FOR loop if the variable is true.'
        Next
        If ExitFors Then Exit For 'Exit the FOR loop if the variable is true.'
    Next
    'So therefore, the final image is the BMP variable.'
    'Here, I try to save the Bitmap as a file by calling this:'
    BMP.Save("C:TEST.BMP")
    'This is when the error occurs. I think so because of the image is too large. If so, is there any way to do anything?'
    'And by the way, I already have the rights to access the C: drive because I am working from an Administrator account...'
    BMP.Dispose()
    BMP = Nothing
End Sub

作为普通用户,通常无法访问根C:驱动器。即使您是管理员,除非另有指定,否则您的应用程序也将在正常权限下运行。

不幸的是,GDI+隐藏了大多数异常,因此很难知道所发生事件的确切原因,但我的猜测是,您的问题是由于不允许应用程序直接保存在C:驱动器中。

尝试将图像保存在保证您有权访问的路径中,例如 C:UsersYourUserNameDesktop

这可能是权限问题。若要对其进行测试,请找到已编译的.exe并以管理员身份运行它。如果它有效,您就知道这是一个权限问题。

如果您因为不知道用户名而尝试将其保存到 C: 驱动器,则可以改用 SpecialDirectory

例如

My.Computer.FileSystem.SpecialDirectories.MyDocuments

将允许您将其保存在用户的"文档"文件夹中。通常,保存到 C: 驱动器并不是最好的做法。

我还建议使用另一个可以指定图像格式的构造函数。

例如

bitmapToSave.Save(saveLocation, Imaging.ImageFormat.Bmp)

最新更新