当前位置:网站首页>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
边栏推荐
猜你喜欢
Use "green computing" technology to promote sustainable development of computing power
JS手写JSON.stringify() (面试)
Desthiobiotin-PEG4-Azide_脱硫生物素-叠氮化物 100mg
电脑一键重装系统内存完整性无法打开怎么办
Jmeter - Heap配置原因报错Invalid initial heap size: -Xms1024m -Xmx2048mError
Force KouTi (5), the longest text string back
腾讯云胡启明:Kubernetes云上资源的分析与优化
搭建MyCat2一主一从的MySQL读写分离
二叉树是否对称
【CAS:2306109-91-9 |胺-PEG4-脱硫生物素】价格
随机推荐
力扣题(5)—— 最长回文子串
Red5搭建直播平台
getBoundingClientRect
【ASP.NET Core】 中间件
如何手动下载并安装 Visual Studio Code 的 SAP Fiori tools - Extension Pack
really time ntp service start command
搭建MyCat2一主一从的MySQL读写分离
【Attention演变史】翻译模型seq2seq (第二弹)
取证程序分类
C语言——青蛙跳台阶(递归)
二叉树的前序遍历
【AGC】构建服务1-云函数示例
C#弹出询问对话框
小软件大作用 | 如何省时省力进行Gerber图层快速对比?
Apache服务器的配置[通俗易懂]
SAP UI5 的初始化过程
Chrome安装zotero connector 插件
CAS :80750-24-9(脱硫生物素 NHS 酯)
web 应用开发最佳实践之一:避免大型、复杂的布局和布局抖动
前3名突然变了,揭秘 7 月编程语言最新排行榜