当前位置:网站首页>win10 uwp modify picture quality compress picture
win10 uwp modify picture quality compress picture
2022-08-04 20:02:00 【Lin Dexi】
本文告诉大家如何在 UWP Reduce image size by modifying the quality of the image,This method only supports output jpg 文件
通过创建 BitmapEncoder 的时候指定 BitmapPropertySet You can set the quality of the picture,只有对 JPG format to set the picture quality
The value of picture quality is from 0 到 1 其中 1 Indicates the best quality
var propertySet = new BitmapPropertySet();
// 图片质量,值范围是 0到1 其中 1 的质量最好
var qualityValue = new BitmapTypedValue(imageQuality,
Windows.Foundation.PropertyType.Single);
propertySet.Add("ImageQuality", qualityValue);
var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, imageWriteAbleStream,
propertySet);这里的 imageQuality It's the picture quality,This needs to be passed in
The method of compressing the image size from an image file can be written like this,Create a method to pass in the original image file,and the file that needs to be output,and picture quality
private async Task<StorageFile> ConvertImageToJpegAsync(StorageFile sourceFile, StorageFile outputFile,
double imageQuality)Get the image size first,This will give you an idea of how much compressed,Compare the file size of the original image and the compressed image size
var sourceFileProperties = await sourceFile.GetBasicPropertiesAsync();
var fileSize = sourceFileProperties.Size;An easier way to get the file size is via WinRTXamlToolkit 的 StorageItemExtensions.GetSizeAsync 拿到文件大小
Read the original image file,The original image needs to be decoded first,Then modify the picture quality by encoding
var imageStream = await sourceFile.OpenReadAsync();The decoding method does not need to know the format of the picture
var decoder = await BitmapDecoder.CreateAsync(imageStream);
var pixelData = await decoder.GetPixelDataAsync();
var detachedPixelData = pixelData.DetachPixelData();打开输出文件,进行编码
var imageWriteAbleStream = await outputFile.OpenAsync(FileAccessMode.ReadWrite);Set the image quality when creating the codec
var propertySet = new BitmapPropertySet();
// 图片质量,值范围是 0到1 其中 1 的质量最好
var qualityValue = new BitmapTypedValue(imageQuality,
Windows.Foundation.PropertyType.Single);
propertySet.Add("ImageQuality", qualityValue);
var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, imageWriteAbleStream,
propertySet);Write the encoding to a file
encoder.SetPixelData(decoder.BitmapPixelFormat, decoder.BitmapAlphaMode, decoder.OrientedPixelWidth,
decoder.OrientedPixelHeight, decoder.DpiX, decoder.DpiY, detachedPixelData);
await encoder.FlushAsync();
await imageWriteAbleStream.FlushAsync();Get the size of the compressed file only,对比一下
var jpegImageSize = imageWriteAbleStream.Size;
// 欢迎访问我博客 https://blog.lindexi.com/ 里面有大量 UWP WPF 博客
Debug.WriteLine($"The compressed file is smaller than the uncompressed file{fileSize - jpegImageSize}");The code for this method of compressing images looks a lot though,But it still seems very simple to open the original image file to decrypt the original image and then output to a new file
/// <summary>
/// Convert the original picture to picture quality and compression quality
/// </summary>
/// <param name="sourceFile">原来的图片</param>
/// <param name="outputFile">输出的文件</param>
/// <param name="imageQuality">图片质量,取值范围是 0 到 1 其中 1 的质量最好,This value is only set correctly jpg 图片有效</param>
/// <returns></returns>
private async Task<StorageFile> ConvertImageToJpegAsync(StorageFile sourceFile, StorageFile outputFile,
double imageQuality)
{
var sourceFileProperties = await sourceFile.GetBasicPropertiesAsync();
var fileSize = sourceFileProperties.Size;
var imageStream = await sourceFile.OpenReadAsync();
using (imageStream)
{
var decoder = await BitmapDecoder.CreateAsync(imageStream);
var pixelData = await decoder.GetPixelDataAsync();
var detachedPixelData = pixelData.DetachPixelData();
var imageWriteAbleStream = await outputFile.OpenAsync(FileAccessMode.ReadWrite);
using (imageWriteAbleStream)
{
var propertySet = new BitmapPropertySet();
// 图片质量,值范围是 0到1 其中 1 的质量最好
var qualityValue = new BitmapTypedValue(imageQuality,
Windows.Foundation.PropertyType.Single);
propertySet.Add("ImageQuality", qualityValue);
var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, imageWriteAbleStream,
propertySet);
//key thing here is to use decoder.OrientedPixelWidth and decoder.OrientedPixelHeight otherwise you will get garbled image on devices on some photos with orientation in metadata
encoder.SetPixelData(decoder.BitmapPixelFormat, decoder.BitmapAlphaMode, decoder.OrientedPixelWidth,
decoder.OrientedPixelHeight, decoder.DpiX, decoder.DpiY, detachedPixelData);
await encoder.FlushAsync();
await imageWriteAbleStream.FlushAsync();
var jpegImageSize = imageWriteAbleStream.Size;
// 欢迎访问我博客 https://blog.lindexi.com/ 里面有大量 UWP WPF 博客
Debug.WriteLine($"The compressed file is smaller than the uncompressed file{fileSize - jpegImageSize}");
}
}
return outputFile;
}So write a test program below
Create a button in the interface
<Button Content="压缩图片" HorizontalAlignment="Center" VerticalAlignment="Center" Click="Button_OnClick" />Get a file at the button,Then create the output file in your own temporary folder,If you really need to use this program to compress pictures then please let the user choose another file
private async void Button_OnClick(object sender, RoutedEventArgs e)
{
var pick = new FileOpenPicker();
pick.FileTypeFilter.Add(".jpg");
var file = await pick.PickSingleFileAsync();
if (file != null)
{
await ConvertImageToJpegAsync(file,
await ApplicationData.Current.TemporaryFolder.CreateFileAsync("lindexi"),
0.75);
}
}现在尝试运行代码,Click the interface button,You can see the selection by clicking the button
代码放在 github
This code is referencedAlex Sorokoletov的代码
How to convert image to JPEG and specify quality parameter in UWP C# XAML
BitmapEncoder options reference - Windows UWP applications
Create, edit, and save bitmap images - Windows UWP applications
边栏推荐
- Aura clock chip generation configuration file script
- How to manually download and install SAP Fiori tools - Extension Pack for Visual Studio Code
- 程序员如何在职场上少走弯路?
- 使用 Chrome 开发者工具的 lighthouse 功能分析 web 应用的性能问题
- 【Web漏洞探索】跨站脚本漏洞
- vs Code 运行一个本地WEB服务器
- 【Attention演变史】翻译模型seq2seq (第二弹)
- C#的Dictionary字典集合按照key键进行升序和降序排列
- How to promote the implementation of rural revitalization
- 阿里的arthas使用,入门报错:Unable to attach to 32-bit process running under WOW64
猜你喜欢
随机推荐
SAP UI5 确保控件 id 全局唯一的实现方法
win10终端中如何切换磁盘
MYSQL获取数据库的表名和表注释
QT 小知识随记
【Attention 演变史】RNN的产生、架构、推广、问题(第一弹)
【Attention演变史】翻译模型seq2seq (第二弹)
QCustomPlot 坐标轴间隔显示刻度标签
mysql的存储过程介绍、创建、案例、删除、查看「建议收藏」
linkboy 5.0 正式发布,新增语音识别、图像识别
备忘录模式
awk statistical average max min
MySQL字段类型
Zip4j使用
SQL Server 遇到报错解决办法--更新中
web 应用开发最佳实践之一:避免大型、复杂的布局和布局抖动
华为企业组网实例:VRRP+MSTP典型组网配置
Force KouTi (5), the longest text string back
Qt Designer生成的图形可以自适应窗口的大小变化
Unreal 本地化 国家化 多语言
Chrome 开发者工具 performance 标签页的用法








