在wpf和gdi +之间转换图像时,内存消耗太多

时间:2018-03-05 11:17:21

标签: c# .net wpf vb.net bitmap

我希望在将TransformedBitmap转换为System.Drawing.Bitmap时消耗太多内存。 图像非常大,7360x4912像素,BGR32像素格式,最多可达144609280位~138MB。

最初我将图像从硬盘加载到BitmapImage中。然后使用RotateTransform旋转它,最后得到最终的TransformedBitmap(WPF)。

对于使用EmguCV进行图像处理,我需要System.Drawing.Bitmap。我使用以下函数转换TransformedBitmap:

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

TransformedBitmap的加载大约需要140MB。使用上述函数将TransformedBitmap转换为Bitmap后,我可以检测到276MB的增加,这正是图像本身大小的两倍。

你有什么我不知道的线索吗?我想保留转换后的位图以及转换后的位图,但仅此而已。

提前致谢

编辑:

以下是对内存的一些评论的呼叫代码:

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是EmguCV lib的包装器。

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

0 个答案:

没有答案