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