清除VB.NET中的IntPtr目标

时间:2018-05-18 13:20:34

标签: asp.net vb.net memory intptr webp

我收到错误There is insufficient system memory in resource pool 'internal' to run this query.我已阅读此帖子:There is insufficient system memory in resource pool 'default' to run this query. on sql

但是,当我添加以下代码时也会发生错误(另请参阅ASP.NET libwebp.dll how to save WebP image to disk):

如下所示,WebPFree不会清除IntPtr类型变量保留的内存。我不确定WebPFree中应添加哪些代码以及如何清除已用内存。 我还检查了this post,但也找不到解决方案。

Dim imgRequest As WebRequest = WebRequest.Create(imageURL)
Dim imgResponse As WebResponse
Dim memStream As New MemoryStream

imgResponse = imgRequest.GetResponse()
Dim streamPhoto As Stream = imgResponse.GetResponseStream()
streamPhoto.CopyTo(memStream)
memStream.Position = 0

Dim bfPhoto As BitmapFrame = ReadBitmapFrame(memStream)
Dim baResize As Byte() = ToByteArray(bfPhoto)
Dim bmp As System.Drawing.Bitmap = imageFunctions.ConvertByteArrayToBitmap(baResize)
File.WriteAllBytes(test.webp, imageFunctions.EncodeImageToWebP(bmp))



Public Class imageFunctions

    <DllImport("libwebp.dll", CallingConvention:=CallingConvention.Cdecl)>
    Public Shared Function WebPEncodeBGRA(ByVal rgba As IntPtr, ByVal width As Integer, ByVal height As Integer, ByVal stride As Integer, ByVal quality_factor As Single, <Out> ByRef output As IntPtr) As Integer
    End Function

    <DllImport("libwebp.dll", CallingConvention:=CallingConvention.Cdecl)>
    Public Shared Function WebPFree(ByVal p As IntPtr) As Integer
    End Function

    Public Shared Function EncodeImageToWebP(ByVal img As System.Drawing.Bitmap) As Byte()
        Dim bmpData As BitmapData = img.LockBits(New Drawing.Rectangle(0, 0, img.Width, img.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb)

        'Create a pointer for webp data
        Dim webpDataSrc As IntPtr

        'Store resulting webp data length after conversion
        Dim webpDataLen As Integer = WebPEncodeBGRA(bmpData.Scan0, img.Width, img.Height, bmpData.Stride, 80, webpDataSrc)

        'Create a managed byte array with the size you just have
        Dim webpDataBin As Byte() = New Byte(webpDataLen - 1) {}

        'Copy from unmanaged memory to managed byte array you created
        System.Runtime.InteropServices.Marshal.Copy(webpDataSrc, webpDataBin, 0, webpDataLen)

        'Free
        WebPFree(webpDataSrc)
        img.Dispose()
        img.UnlockBits(bmpData)

        Return webpDataBin

    End Function

    Public Shared Function ConvertByteArrayToBitmap(ByVal imageData As Byte()) As System.Drawing.Bitmap       
        Dim ms As New IO.MemoryStream(imageData)
        Return New Drawing.Bitmap(ms)
    End Function

End Class

0 个答案:

没有答案