开发 WPF 程序时,如何将图像作为缩略图加载?

在开发 WPF 应用程序时,在列表中展示相关图片是一个很常见的需求。比如,在列表中展示用户的虚拟头像:如果每页显示 100 条数据的话,那么就需要加载一百张图片到内存里。很显然这不会出什么问题,一般情况下用户的图像都不会太大。

但如果换个场景,比如订单列表或者产品列表就不太合适了。为了获得更好的销售效果,产品图一般都会很大。加载这样一个列表就会占用大量的内存。

其中一个解决方式是:在加载到界面之前就为图片生成好缩略图。这项工作可以由后端服务器完成或者编写一个自定义的转换器来搞定。

事实上,WPF 中内置了一个很有意思的 DecodePixelWidth 属性可以轻松的将位图作为缩略图加载以达到节省应用程序内存的目的。

<!-- Simple image rendering. However, rendering an image this way may not
     result in the best use of application memory. See markup below which
     creates the same end result but using less memory. -->
<Image Width="200" Source="Sample.jpg"/>

其中,Sample.jpg 是一张分辨率为 7360 x 4912 的图片。启动后的程序内存占用 534 MB。

使用以下代码设置 DecodePixelWidth 属性:​​​​​​​


<Image Width="200">
  <Image.Source>
    <!-- To save significant application memory, set the DecodePixelWidth or  
     DecodePixelHeight of the BitmapImage value of the image source to the desired 
     height and width of the rendered image. If you don't do this, the application will 
     cache the image as though it were rendered as its normal size rather than just 
     the size that is displayed. -->
    <!-- Note: In order to preserve aspect ratio, only set either DecodePixelWidth
         or DecodePixelHeight but not both. -->
    <BitmapImage DecodePixelWidth="200" UriSource="Sample.jpg" />
  </Image.Source>
</Image>

内存占用降低为 65 MB,效果非常明显。

以上代码来自微软官方文档,链接地址:

https://learn.microsoft.com/en-us/dotnet/desktop/wpf/graphics-multimedia/how-to-load-an-image-as-a-thumbnail

原文地址​​​​​​​ 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
WPF中,当一个Button控件不可用,可以通过改变按钮上的图像为灰度图来达到变灰的效果。 一种实现方式是使用Button的样式和触发器来实现。首先,我们需要将按钮的样式定义在XAML中,在其中设置按钮的模板,并在其中添加一个Image元素用于显示图像。在按钮的样式中,为按钮的IsEnabled属性添加一个触发器,当该属性值为False,触发器会将图像转为灰度。 以下是一个简单的实现示例: ```xml <Button Content="按钮" IsEnabled="False"> <Button.Style> <Style TargetType="Button"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="Button"> <Grid> <Image Source="图片路径"/> </Grid> </ControlTemplate> </Setter.Value> </Setter> <Style.Triggers> <Trigger Property="IsEnabled" Value="False"> <Setter Property="Effect"> <Setter.Value> <GrayscaleEffect/> </Setter.Value> </Setter> </Trigger> </Style.Triggers> </Style> </Button.Style> </Button> ``` 在上述示例中,首先定义了一个Button,并设置其Content属性为"按钮",IsEnabled属性为False。然后,定义了一个样式,并将按钮的模板设置为一个包含Image的网格布局。 接下来,在该样式的触发器中,当按钮的IsEnabled属性为False,设置按钮的Effect属性为GrayscaleEffect,即灰度效果。这里GrayscaleEffect是一个自定义的灰度特效。 以上就是一种在WPF中实现按钮不可用图像变灰度图的方法。通过定义控件样式和触发器,我们可以根据按钮的可用性状态来改变按钮上的图像效果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值