我在读取和关闭多个JPG图像时遇到内存问题。
我正在将JPG文件加载到图像对象中,读取文件信息(大小,尺寸,日期等),并读取其EXIF数据以获取Lat / Long的地理编码。然后我将信息推送到ListView对象。这对于最多60个JPG的文件夹来说都很有效。一旦我超过一定数量(不确定阈值实际是多少),我得到了我最喜欢的错误......
**************例外文字************** 为System.OutOfMemoryException: 内存不足。在System.Drawing.Image.FromFile(String filename,Boolean useEmbeddedColorManagement) 在System.Drawing.Image.FromFile(String filename)
...等
我正在某处泄露内存,但我对.NET应用程序有点新手。我从循环中调用此例程,该循环读取目录中的JPG文件集合。
Public Function JPGDat(ByRef jpg As FileInfo) As ListViewItem
Dim filEntry(6) As String
Dim lstEntry As ListViewItem = Nothing
Dim pic As Image = Image.FromFile(jpg.FullName) 'HERE IS WHERE WE CRASH
filEntry(0) = jpg.Name
filEntry(1) = (Math.Round(jpg.Length / 1024)).ToString() 'File Size
filEntry(2) = Format(pic.PhysicalDimension.Width, "0") 'Pixel width dimension
filEntry(3) = Format(pic.PhysicalDimension.Height, "0") 'Pixel height dimension
Try
Dim CLatt As Double = GetCoord(pic.GetPropertyItem(2)) 'Get Latitude from EXIF
Dim CLong As Double = GetCoord(pic.GetPropertyItem(4)) 'Get Longitude from EXIF
filEntry(4) = Format(CLatt, "0.000000000000000")
filEntry(5) = Format(CLong, "0.000000000000000")
Catch ex As Exception
filEntry(4) = ""
filEntry(5) = ""
End Try
filEntry(6) = "Date: " + Format(jpg.CreationTime, "yyyy-MM-dd")
lstEntry = New ListViewItem(filEntry)
If filEntry(4) <> "" Then
lstEntry.Checked = True
End If
pic.Dispose()
Return lstEntry
End Function
答案 0 :(得分:0)
确保将打开的JPG命令放在Try结构...
中 Try
pic = Image.FromFile(jpg.FullName)
filEntry(2) = Format(pic.PhysicalDimension.Width, "0") 'Pixel width dimension
filEntry(3) = Format(pic.PhysicalDimension.Height, "0") 'Pixel height dimension
Catch ex As Exception
MsgBox("Error in file " + jpg.FullName + vbCrLf + ex.Message)
JPGDat = New ListViewItem(filEntry)
Exit Function
End Try
这样,如果你得到一个损坏的JPG,你就不会认为你有内存泄漏!