Private Shared Values(4) As Integer
Private Shared myImage As Bitmap
Private Shared myArea As Rectangle
Private Shared ocrImg As Bitmap
Private Shared ImgCpy As Bitmap
Public Shared Function PrepImage(ByVal filename As String, ByVal savename As String, ByVal filetype As String) As Boolean
'// Grab region of image for processing
Try
Select Case filetype
Case "A"
Values(0) = 2240
Values(1) = 255
Values(2) = 40
Values(3) = 150
Values(4) = 3
Case "B"
Values(0) = 184
Values(1) = 255
Values(2) = 85
Values(3) = 20
Values(4) = 0
Case "C"
Values(0) = 933
Values(1) = 755
Values(2) = 270
Values(3) = 62
Values(4) = 0
Case Else
Return False
End Select
myImage = Bitmap.FromFile(filename)
ImgCpy = New Bitmap(myImage)
myImage.Dispose()
myArea = New Rectangle(Values(0), Values(1), Values(2), Values(3))
ocrImg = GetPicturePart(ImgCpy, myArea)
ocrImg.RotateFlip(Values(4))
ocrImg.Save(savename, Drawing.Imaging.ImageFormat.Bmp)
ocrImg.Dispose()
ImgCpy.Dispose()
这个函数在我第一次调用它时工作,但随后它失败了,有时我似乎得到一个参数未指定的异常,但大多数情况下我得到一个内存不足的错误。我是否也必须在最后将图像设置为 Nothing,我认为 Dispose 会释放他们正在使用的所有资源?
我将代码重构如下,但仍然有问题,这不使用 get picturepart 函数,但这里也是如此......
Private Shared Function GetPicturePart(ByVal SourceImage As Image, ByVal Region As Rectangle) As Bitmap
Dim ImagePart As Bitmap = New Bitmap(Region.Width, Region.Height)
Using G As Graphics = Graphics.FromImage(ImagePart)
Dim TargetRect As Rectangle = New Rectangle(0, 0, Region.Width, Region.Height)
Dim SourceRect As Rectangle = Region
G.DrawImage(SourceImage, TargetRect, SourceRect, GraphicsUnit.Pixel)
End Using
Return ImagePart
End Function
Dim myImg As New Bitmap(filename)
Dim MyArea As New Rectangle(Values(0), Values(1), Values(2), Values(3))
Dim myFormat As PixelFormat = myImg.PixelFormat
Dim myOCR As Bitmap = myImg.Clone(MyArea, myFormat)
myImg.Dispose()
myImg = Nothing
myOCR.RotateFlip(Values(4))
myOCR.Save(savename, Drawing.Imaging.ImageFormat.Bmp)
myOCR.Dispose()
myOCR = Nothing