Hallo,
ich habe mir eine Funktion baut, die mir das automatische beschneiden von Bildern übernimmt.
Dabei werden die Bilder von dem überflüssigem Rand (Hintergrund) getrennt.
Ich habe jetzt das Problem, dass ich bei der Umwandlung großer Mengen Bilder immer ein speicherproblem bekomme System.OutOfMemoryException
Das Problem scheint zu sein, dass ich den Speicher irgenwie nicht richtig freigebe. Wenn ich die Anwendung starte erhöht sich der Speicherbedarf immer ein bischen mehr - solange bis der Fehler kommt.
Ich habe jetzt versuche mit .dispose() die Objekte alle zu zerstören - aber irgend was funktioniert noch nicht.
Hier mal der Code:
''' <summary>
''' Bild Beschneiden entfernt den unnötigen Rand eines Bildes
''' </summary>
''' <param name="bmp">Das zu beschneidene Bild</param>
''' <returns>Neues beschnittenes Bild</returns>
Public Function Beschneiden(ByVal Bmp As Bitmap) As Bitmap
Dim CropRight As Integer, CropLeft As Integer, CropTop As Integer, _
CropBottom As Integer
'von Links
For CropLeft = 0 To Bmp.Width - 1
If beschneiden_check_row(Bmp, CropLeft) = False Then CropLeft -= 1 _
: Exit For
Next
If CropLeft = -1 Then CropLeft = 0
'von Rechts
For CropRight = Bmp.Width - 1 To 0 Step -1
If beschneiden_check_row(Bmp, CropRight) = False Then CropRight += _
1 : Exit For
Next
'von Oben
For CropTop = 0 To Bmp.Height - 1
If beschneiden_check_col(Bmp, CropTop) = False Then CropTop -= 1 : _
Exit For
Next
If CropTop = -1 Then CropTop = 0
'von Unten
For CropBottom = Bmp.Height - 1 To 1 Step -1
If beschneiden_check_col(Bmp, CropBottom) = False Then CropBottom _
+= 1 : Exit For
Next
If CropBottom = Bmp.Height And CropTop = 0 And CropLeft = 0 And _
CropRight = Bmp.Width Then Return Bmp
Dim NewWidth As Integer = CropRight - CropLeft
Dim NewHeight As Integer = CropBottom - CropTop
Dim fixBmp As Bitmap = New Bitmap(NewWidth, NewHeight, _
PixelFormat.Format32bppArgb)
Dim g As Drawing.Graphics = Graphics.FromImage(fixBmp)
g.Clear(Color.White)
g.SmoothingMode = SmoothingMode.HighQuality
g.CompositingQuality = CompositingQuality.HighQuality
g.InterpolationMode = InterpolationMode.High
g.DrawImage(Bmp, New RectangleF(0, 0, NewWidth, NewHeight), New _
RectangleF(CropLeft, CropTop, NewWidth, NewHeight), _
GraphicsUnit.Pixel)
Return (fixBmp)
g.Dispose()
fixBmp.Dispose()
End Function
Function beschneiden_check_row(ByVal bmp As Bitmap, ByVal Row As Integer) _
As Boolean
Dim FirstColor As Integer = bmp.GetPixel(Row, 0).R
For Col As Integer = 0 To bmp.Height - 1
If bmp.GetPixel(Row, Col).R <> FirstColor Then Return False
Next
Return True
End Function
Function beschneiden_check_col(ByVal bmp As Bitmap, ByVal Col As Integer) _
As Boolean
Dim FirstColor As Integer = bmp.GetPixel(0, Col).R
For Row As Integer = 0 To bmp.Width - 1
If bmp.GetPixel(Row, Col).R <> FirstColor Then Return False
Next
Return True
End Function Wer kann mir sagen was ich falsch mache?
Danke
Joachim |