Too much memory consumption while converting image between wpf and gdi+

。_饼干妹妹 提交于 2020-01-11 13:05:03

问题


I am expecting too much memory consumption while converting an TransformedBitmap to a System.Drawing.Bitmap. The Image ist quite big with 7360x4912 pixel with a BGR32 Pixelformat which adds up to 144609280 bits ~ 138MB.

Initially I load the image from hard drive into a BitmapImage. Then rotate it with RotateTransform to end up with a final TransformedBitmap (WPF).

For Imageprocessing with EmguCV I will need System.Drawing.Bitmap. I convert the TransformedBitmap using the following function:

Private Function convertToBitmap(tb As TransformedBitmap) As System.Drawing.Bitmap

    Dim myBitmap As New System.Drawing.Bitmap(tb.PixelWidth, tb.PixelHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb)
    '140mb increase'

    Dim data As System.Drawing.Imaging.BitmapData =
        myBitmap.LockBits(New System.Drawing.Rectangle(System.Drawing.Point.Empty, myBitmap.Size),
                          System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb)

    tb.CopyPixels(Int32Rect.Empty, data.Scan0, data.Height * data.Stride, data.Stride)
    'another 140MB increase'

    myBitmap.UnlockBits(data)

    Return myBitmap
End Function

The Loading of the TransformedBitmap takes about 140MB as expected. After converting the TransformedBitmap to a Bitmap using the mentioned function I can detect an increase of 276MB, which is exactly doubled the size of the image itself.

Do you have any clue of what I am missing? I want to keep the Transformed Bitmap as well as the converted Bitmap but nothing more.

Thanks in advance

EDIT:

Here is the Calling Code with some Comment on Memory:

Dim tb As New TransformedBitmap()

    ' Create the source to use as the tb source.
    Dim bi As New BitmapImage()
    bi.BeginInit()
    bi.UriSource = New Uri(Image_Path, UriKind.Absolute)
    bi.CacheOption = BitmapCacheOption.OnLoad
    bi.EndInit()
    ' Properties must be set between BeginInit and EndInit calls.

    tb.BeginInit()
    tb.Source = bi

    ' Set image rotation.
    Dim transform As New RotateTransform(angle)
    tb.Transform = transform
    tb.EndInit()
    ' Set the Image source.
    imgChurch.Source = tb
    ' load the Image for OpenCV too
    _cvImage?.Dispose()
    'memory around 177MB
    Dim bmp As System.Drawing.Bitmap = convertToBitmap(tb) 'Memory is after 
    'Call about 454MB
    _cvImage = New CVImage(bmp)
    bmp.Dispose()
    GC.Collect()

CVImage Class is a wrapper for EmguCV lib.

public CVImage(Bitmap bmp)
    {
        var img = new Image<Bgr, byte>(bmp);
        currentImg = img.Mat;
    }

来源:https://stackoverflow.com/questions/49109248/too-much-memory-consumption-while-converting-image-between-wpf-and-gdi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!