• WPF图片的缩放节省内存


    一、前言

      正好项目用到要加载大量图片,虽然说可以使用WPF提供的自带的UI虚拟化功能,但是直接加载大量的图片到内存还是会

    消耗很多的内存,而且WPF支持UI虚拟化的ListBox等容器的布局是VirtualizingStackPanel,这个对图片多样化的展示支持就

    够呛了,这个布局的话可以自己重新写个虚拟布局管理器,这不是本节的内容,本节要讨论的在WPF下的图片缩略图的问题。

    在网上一搜一大把都是Winform下的图片缩放,其实在WPF下实现图片的缩放也是非常简单的。

    二、WPF实现缩略图

      WPF下图片的处理也是非常到位的,有很多的图片相关的处理类,如图片的编码解码包括裁剪图片啥的,都有。

      WPF图片的显示主要靠BitmapSource,这是个抽象类,有好几个实现类的。本文说的就是BitmapImage,从本地加载图片:

     BitmapImage bit = new BitmapImage();
                using (FileStream fs = new FileStream(@"D:\Pictures\back.jpg", FileMode.Open))
                {
                    fs.Seek(0, SeekOrigin.Begin);
                    bit.BeginInit();
                    bit.CreateOptions = BitmapCreateOptions.IgnoreColorProfile;
                    bit.CacheOption = BitmapCacheOption.OnLoad;
                    bit.DecodePixelWidth = 300;//需要缩略图的解码宽度
                    bit.DecodePixelHeight = (int)(bit.DecodePixelWidth * 0.625);//缩略图的解码高度
                    bit.StreamSource = fs;
                    bit.EndInit();
                }
    
                img1.Source = bit;
    

      如上,便是生成缩略图的关键。可以自行对比缩略图和原始图占用内存的情况,甚至可以保存下来对比。

      当然如果想要等比例的缩放图片,可以尝试BitmapDecoder提前获取原图片的宽高,然后进行等比例缩放:

    {
                        var decoder = BitmapDecoder.Create(fs, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
                        var thumnail = decoder.Thumbnail;
                        var frame = decoder.Frames[0];
                        var raww = frame.Width;//原图的宽
                        var rawh = frame.Height;//原图的高
                    }
  • 相关阅读:
    P2730 魔板 Magic Squares
    P2124 奶牛美容
    4. Median of Two Sorted Arrays(Array; Divide-and-Conquer)
    3.Longest Substring Without Repeating Characters(string; HashTable)
    2.Add Two Numbers (List)
    1.Two Sum (Array; HashTable)
    C++中的浅拷贝、深拷贝、智能指针
    C++ 静态数据成员和静态成员函数
    C & C++ 宏与const
    C++指针与引用
  • 原文地址:https://www.cnblogs.com/yeshuimaowei/p/15688064.html
Copyright © 2020-2023  润新知