当前位置:网站首页>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
边栏推荐
猜你喜欢
Seata source code analysis: various message processing processes of seata server
ASP.NET商贸进销存管理系统源码(带数据库文档)源码免费分享
《支付宝体验设计精髓》一书,跟测试相关性知识记录
【AGC】构建服务1-云函数示例
实现菜单拖拽排序
使用 Allatori 进行 Jar 包混淆
Desthiobiotin-PEG4-Azide_脱硫生物素-叠氮化物 100mg
【CAS:2306109-91-9 |胺-PEG4-脱硫生物素】价格
华为企业组网实例:VRRP+MSTP典型组网配置
Jmeter - Heap配置原因报错Invalid initial heap size: -Xms1024m -Xmx2048mError
随机推荐
刷题-洛谷-P1307 数字反转
成品升级程序
C#弹出询问对话框
二叉树是否对称
多商户商城系统功能拆解22讲-平台端分销商品
02 ts 变量定义,类型
泰山OFFICE技术讲座:底纹、高亮、边框的关系
WIN10系统如何开启终端
KubeSphere简介,功能介绍,优势,架构说明及应用场景
getBoundingClientRect
刷题-洛谷-P1317 低洼地
C#将对象转换为Dictionary字典集合
vehemently condemn
使用 Chrome 开发者工具 coverage 功能分析 web 应用的渲染阻止资源的执行分布情况
Notepad++更改显示背景
《支付宝体验设计精髓》一书,跟测试相关性知识记录
【AGC】构建服务1-云函数示例
Nuxt.js的优缺点和注意事项
小软件大作用 | 如何省时省力进行Gerber图层快速对比?
密码学系列之:PEM和PKCS7,PKCS8,PKCS12