BitmapSource.CopyPixels有两个副本吗?

时间:2018-03-07 11:50:49

标签: c# .net wpf memory bitmap

我预计在使用BitmapSource.CopyPixels复制图像时内存会出现异常增加。

我的图像文件pic.jpg有2913 * 4744像素,所以大约50MB,内存为32bpp。它被加载到TransformedBitmap。 然后我尝试将其转换为System.Drawing.Bitmap进行图像处理。

当我打电话给“tb.CopyPixels”时,会发生奇怪的事情。我希望内存增加50MB。因为具有50MB的图像被复制到bytearray。但实际上我的体验增加了大约100MB,所以内存的两倍。是否有某种额外的(内心)复制?我错过了什么?如何将Bitmapsource转换为增加50MB的位图?

由于

调用代码和转换:

    System.Drawing.Bitmap bmp;    
    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        TransformedBitmap tb = new TransformedBitmap();

        // Create the source to use as the tb source.
        BitmapImage bi = new BitmapImage();
        bi.BeginInit();
        bi.UriSource = new Uri("pic.jpg", UriKind.Relative);
        bi.CacheOption = BitmapCacheOption.OnLoad;
        bi.EndInit();
        //' Properties must be set between BeginInit and EndInit calls.

        tb.BeginInit();
        tb.Source = bi;

        //' Set image rotation.
        RotateTransform transform = new RotateTransform(90);
        tb.Transform = transform;
        tb.EndInit();
        //' Set the Image source.
        image.Source = tb;

        bmp = convertToBitmap(tb);
        Console.WriteLine();
    }


    private System.Drawing.Bitmap convertToBitmap(TransformedBitmap tb)
    {
        int stride = (tb.PixelWidth * (tb.Format.BitsPerPixel / 8));
        byte[] pixels = new byte[(tb.PixelHeight * stride)];

        tb.CopyPixels(pixels, stride, 0);  //<-- strange Memory increase of 
        //about 100MB. I expected 50MB (the image itself)

        System.Drawing.Bitmap myBitmap;

        using (MemoryStream ms = new MemoryStream(pixels))
        {
            myBitmap = new System.Drawing.Bitmap(ms);
        }
        return myBitmap;
    }

0 个答案:

没有答案