无法使用Dispose关闭内存中的图片

时间:2015-09-03 17:14:26

标签: asp.net vb.net

我使用此代码进行图片水印,当我尝试移动或删除图片时,visual studio显示此错误:

其他信息:该进程无法访问该文件' E:\ lian \ Guest_Upload \ upload \ 179caeff-3ebe-472a-9eda-aeda8ebbbd40.jpg'因为它正被另一个进程使用。

我尝试发布 处置

GC.Collect的()

GC.WaitForPendingFinalizers()

但没有任何事情发生。

请帮我解决此问题

这是我的代码:

  Dim watermarkText As String = "Name"
    Dim watermarkText1 As String = "Nameeeee1111"

    'Get the file name.
    Dim fileName As String = imagepath
    'Dim fs As FileStream = File.OpenRead(filepath)
    'Read the File into a Bitmap.
    Using bmp As New Bitmap(File.OpenRead(filepath))
        Using grp As Graphics = Graphics.FromImage(bmp)

            'Set the Color of the Watermark text.
            Dim brush As Brush = New SolidBrush(Color.FromArgb(100, Color.Gray))
            'New SolidBrush(Color.Gray)

            'Set the Font and its size.
            Dim font As Font = New System.Drawing.Font("Times New Roman", 200, FontStyle.Bold, GraphicsUnit.Pixel)

            Dim font1 As Font = New System.Drawing.Font("Times New Roman", 40, FontStyle.Bold, GraphicsUnit.Pixel)

            'Determine the size of the Watermark text.
            Dim textSize As New SizeF()
            textSize = grp.MeasureString(watermarkText, font)


            Dim textSize1 As New SizeF()
            textSize1 = grp.MeasureString(watermarkText1, font1)

            'Position the text and draw it on the image.
            ' Dim position As New Point((bmp.Width  / 2), (bmp.Height / 2))
            Dim position As New Point((bmp.Width / 2 - (CInt(textSize.Width) / 2)), (bmp.Height / 2 - (textSize.Height / 2)))
            grp.DrawString(watermarkText, font, brush, position)

            Dim position1 As New Point((bmp.Width / 2 - (CInt(textSize.Width) / 2 - 200)), (bmp.Height / 2 - (textSize.Height / 2 - 200)))
            grp.DrawString(watermarkText1, font1, brush, position1)

            Dim p As String
            p = Server.MapPath("reza" & newpath)

            bmp.Save(p, System.Drawing.Imaging.ImageFormat.Jpeg)
            bmp.Dispose()

            brush.Dispose()
            font.Dispose()

            font1.Dispose()
            grp.Dispose()

            GC.Collect()
            GC.WaitForPendingFinalizers()






        End Using
    End Using

1 个答案:

答案 0 :(得分:0)

当您使用Using Bitmap(File.OpenRead(filepath))打开位图时,它会使文件保持打开状态。如果你退出使用块,它应该关闭文件,以便你可以删除它等。这很奇怪,但这是Windows的工作方式。如果您使用Bitmap.FromStream加载文件,该文件不会保持打开状态,它可能会解决问题。

Dispose不起作用的原因是因为您无法在Using块中部署位图。退出块时会自动处理。