Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/300.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在RichTextBox中更有效地加载图像?_C#_Wpf_Image_Xaml - Fatal编程技术网

C# 如何在RichTextBox中更有效地加载图像?

C# 如何在RichTextBox中更有效地加载图像?,c#,wpf,image,xaml,C#,Wpf,Image,Xaml,我正在我的RichTextBox中拖放一个沉重的图像(95729KB)。但内存使用率是如此令人费解:为什么它存储超过700MB 我的拖放代码: private void RtbEditor_PreviewDrop(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop)) { string[] files = (string[])e.Data.GetData(

我正在我的RichTextBox中拖放一个沉重的图像(95729KB)。但内存使用率是如此令人费解:为什么它存储超过700MB

我的拖放代码:

private void RtbEditor_PreviewDrop(object sender, DragEventArgs e)
{
    if (e.Data.GetDataPresent(DataFormats.FileDrop))
    {
        string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
        if (files != null && files.Length > 0)
        {
            foreach (var file in files)
            {
                // Filter out non-image files.
                if (IsValidImageFile(file))
                {
                    BitmapImage bitmap = new BitmapImage();
                    bitmap.BeginInit();            
                    bitmap.UriSource = new Uri(file, UriKind.Absolute);            
                    bitmap.EndInit();
                    Image image = new Image();            
                    image.Source = bitmap;            
                    var container = new InlineUIContainer(image, rtbEditor.CaretPosition);
                    rtbEditor.CaretPosition = container.ElementEnd;
                }
            }
        }
    }
}

对于图像检查,我只取了图像标题:我做错了什么?

这张厚重的图像可能具有极高的分辨率,并使用PNG或JPEG等格式。这些格式压缩像素数据以减小最终文件大小。但是,为了渲染图像,渲染器需要将图像解压缩为具有(A)RGB值的实际像素

每像素32位的未压缩3000x3000图像的重量约为36 MB。所以你的形象一定更大


为什么要在文本框中渲染如此大的图像?

您肯定不需要那么多像素。只需将
BitmapImage.DecodePixelHeight
BitmapImage.DecodePixelHeight
设置为
BitmapImage.BeginInit()
BitmapImage.BeginInit()之间的适当值。除非不关心原始纵横比,否则不要同时设置这两个值。

老实说,在大多数情况下,这是不必要的。但我不明白为什么我只加载了100 mb的jpeg图像,却占用了这么多内存。我想让RichTextBox像Microsoft Word一样工作。也许我是白痴:)对不起,我的英语是100 MB JPEG是巨大的。如果您希望用户能够将图像拖动到文本编辑器中,则必须将图像的大小调整为更易于处理的大小。我知道我不需要太多像素。但我想实现图像大小调整功能。在BitmapImage.DecorePixeHeight之后,图像质量会下降,不是吗?你知道它为什么占用这么多内存吗?@Roman,正如你所说,你加载一个100MB的jpeg,它将在内存中解码为RGBA图像。那么,你还能指望什么呢?那意味着我不明白发生了什么。所以,当我加载100MB的jpeg时,它会被解码成RGBA,而RGBA又比jpeg大?对不起,我不擅长形象formatting@Roman好啊实际上,在
EndInit()
之后,您可以使用
Height
*
Width
*
Format.BitsPerPixel
/8来计算解码图像需要多少字节。或者您也可以通过
BitmapImage.\u finalSource.DUCECompatiblePtr.\u gcPressure.\u gcPressure
检查它从
GC
保留了多少内存。