gpt4 book ai didi

c# - 防止在渲染之前复制 C# WPF BitmapSource 字节

转载 作者:太空宇宙 更新时间:2023-11-03 15:23:50 24 4
gpt4 key购买 nike

我一直在使用 32 位 C# WPF 应用程序,该应用程序在 ListBox 中显示大量大图像(在许多情况下为 1080p)。问题是在我的 C# 对象(我绑定(bind)到)中保留一个 BitmapSource 对象会显着增加内存,因为我创建的 BitmapSource 的字节在渲染之前被复制/复制。如果我保留 BitmapSource 对象以便重用它或在其他地方重新显示它,由于渲染前复制,我最终会得到原始图像字节的多个副本。更具体地说,在渲染之前调用 CopyPixels(Int32Rect sourceRect, Array pixels, int stride, int offset)。带有堆栈跟踪的内存/堆分析证实了字节在渲染之前被复制的想法。

我创建的唯一“变通方法”如下:

ImageData data = _backendImage.getData();
SWIGTYPE_p_unsigned_char rawData = _backendImage.getRawData();
IntPtr dataPointer = SWIGTYPE_p_unsigned_char.getCPtr(rawData).Handle;
GC.Collect(); // forces garbage collection on not-displayed images
return Utilities.GenerateBitmapSource((int)_backendImage.getWidth(), (int)_backendImage.getHeight(), _backendImage.getByteOrder(), dataPointer, data.Count);

最后一行是我自己的函数来实际生成一个 BitmapSource 对象,这超出了这个问题的范围。

解决方法在性能上非常差,因为在每次渲染到 ListBox 之前,我不仅要复制一份数据,还要复制两份数据(一份放入 BitmapSource,一份用于渲染)。保留 BitmapSource 会删除所有重复的复制操作,但会占用大量内存。

这是我的 ListBox XAML:

<ListBox Name="SlideShowListBox" ItemsSource="{Binding SlideData.PreviewData}" 
SelectedIndex="{Binding SelectedIndex}"
ScrollViewer.VerticalScrollBarVisibility="Visible"
SelectionMode="Extended"
VirtualizingStackPanel.VirtualizationMode="Recycling">
<ListBox.ItemTemplate>
<DataTemplate>
<VirtualizingStackPanel Orientation="Horizontal" Margin="0, 2.5, 0, 2.5">
<Label Content="{Binding data.ImageNumber}" VerticalAlignment="Top" Width="30" HorizontalContentAlignment="Right" Margin="0,-6.5,0,0"/>
<Grid>
<Image Source="{Binding data.ImageThumbnail}" RenderOptions.BitmapScalingMode="HighQuality" VerticalAlignment="Top" HorizontalAlignment="Left"
Name="ListImage"
MaxWidth="{Binding ElementName=ListBoxItemSizer,
Path=ActualWidth, Converter={ikriv:MathConverter}, ConverterParameter=(x - 20)}">
<Image.Style>
<Style TargetType="{x:Type Image}">
<Style.Triggers>
<DataTrigger Binding="{Binding data.IsHidden}" Value="True">
<Setter Property="Opacity" Value="0.5"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Image.Style>
</Image>
</Grid>
</VirtualizingStackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>

问题:当我已经将所有字节存储在 RAM 中并在图像上调用了 .Freeze() 时,是否有任何方法可以防止 WPF 在渲染之前复制字节? 我希望我的图像字节的一个副本在 RAM 中:不多也不少。

可能相关:.NET Memory issues loading ~40 images, memory not reclaimed -- 似乎无关,因为我是从原始字节而不是(文字)流对象构建 BitmapSource 对象。

编辑:有趣的说明——我在两个不同的屏幕上的 2 个不同的 ListBox 项目中显示这些 BitmapSource 项目。如果我保留这些对象,RAM 使用只会在 BitmapSource 的第一次 渲染时增加,而不会在后续渲染时增加,无论 BitmapSource 出现在哪个屏幕或 ListBox 上。

最佳答案

我无法在渲染前阻止复制。在尝试了从使用 CacheOption = BitmapCacheOption.NoneBitmapImage 到从内存中的文件而不是图像加载的所有方法之后,在 RAM 中保留 1 个字节副本的修复相对简单。

要修复它,请创建您自己的继承自 BitmapSource 的自定义类。按照接受的答案中的代码 here ,根据您自己的图像格式进行必要的调整。例如,我需要使用自己的步幅值而不是提供的步幅值,因为我要将 24bpp 数组转换为 Pbgra32 格式。我使用不安全的复制代码来进行更快的复制(同样,针对我的用例进行了修改)。我已将我的代码复制到这篇文章的底部,但它与链接的 SO 文章非常相似。

但是,您的自定义 BitmapSource 仍然有 2 个字节副本。 (CopyPixels 函数名称泄露了这一点。)要删除现在无关的副本,只需设置 _data = null 并让 GC 在可能的时候清理它。多田! RAM 中的一个字节副本,性能很快,ListBox 滚动有效,您可以在其他屏幕和其他地方重用您的 BitmapSource,并且内存使用是可以接受的。

我很担心如果在渲染之后调用这会破坏 CreateInstanceCore(),并且这可能会破坏我自己以外的其他用例。

class RGB24BitmapSource : BitmapSource
{
private byte[] _data;
private int _stride;
private int _pixelWidth;
private int _pixelHeight;

public RGB24BitmapSource(int pixelWidth, int pixelHeight, IntPtr data, int dataLength, int stride)
{
if (dataLength != 0 && data != null && data.ToInt64() != 0)
{
_data = new byte[dataLength];
Marshal.Copy(data, _data, 0, dataLength);
}
_stride = stride;
_pixelWidth = pixelWidth;
_pixelHeight = pixelHeight;
}

private RGB24BitmapSource(int pixelWidth, int pixelHeight, byte[] data, int stride)
{
_data = data;
_stride = stride;
_pixelWidth = pixelWidth;
_pixelHeight = pixelHeight;
}

unsafe public override void CopyPixels(Int32Rect sourceRect, Array pixels, int stride, int offset)
{
if (_data != null)
{
fixed (byte* source = _data, destination = (byte[])pixels)
{
byte* dstPtr = destination + offset;
for (int y = sourceRect.Y; y < sourceRect.Y + sourceRect.Height; y++)
{
for (int x = sourceRect.X; x < sourceRect.X + sourceRect.Width; x++)
{
byte* srcPtr = source + _stride * y + 3 * x;
byte a = 255;
*(dstPtr++) = (byte)((*(srcPtr + 2)) * a / 256);
*(dstPtr++) = (byte)((*(srcPtr + 1)) * a / 256);
*(dstPtr++) = (byte)((*(srcPtr + 0)) * a / 256);
*(dstPtr++) = a;
}
}
}
}
_data = null; // it was copied for render, so next GC cycle could theoretically reclaim this memory. This is the magic fix.
}

protected override Freezable CreateInstanceCore()
{
return new RGB24BitmapSource(_pixelWidth, _pixelHeight, _data, _stride);
}

// DO. NOT. COMMENT. THESE. OUT. IF YOU DO, CRASHES HAPPEN!
#pragma warning disable 0067 // disable unused warnings
public override event EventHandler<DownloadProgressEventArgs> DownloadProgress;
public override event EventHandler DownloadCompleted;
public override event EventHandler<ExceptionEventArgs> DownloadFailed;
public override event EventHandler<ExceptionEventArgs> DecodeFailed;
#pragma warning restore 0067

public override double DpiX
{
get { return 96; }
}

public override double DpiY
{
get { return 96; }
}

public override System.Windows.Media.PixelFormat Format
{
get { return PixelFormats.Pbgra32; }
}

public override BitmapPalette Palette
{
get { return BitmapPalettes.WebPalette; }
}

public override int PixelWidth
{
get { return _pixelWidth; }
}

public override int PixelHeight
{
get { return _pixelHeight; }
}

public override double Width
{
get { return _pixelWidth; }
}

public override double Height
{
get { return _pixelHeight; }
}
}

关于c# - 防止在渲染之前复制 C# WPF BitmapSource 字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36135454/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com