c# - 在上传到云之前压缩选取的图像大小 Xamarin
问题描述
我正在开发一个 Xamarin 应用程序,用户可以使用 Xamarin Essentials 插件选择图像。我现在的问题是在加载到云之前使用图像完整路径缩小图像大小。
编码
// Pick Image
private async Task PickImages()
{
if (ImageCollection.Count >= 10)
{
ToastMessageLong("Cannot Select More then 10 Images.");
return;
}
ImageLink image = new();
try
{
FileResult result = await MediaPicker.PickPhotoAsync(new MediaPickerOptions
{
Title = "Pick an Image"
});
if (result == null) return;
image.PostImages = result.FullPath;
ImageCollection.Add(image);
}
catch (Exception x)
{
await DisplayAlert("", x.Message);
}
}
private async Task UploadImagesToCloud()
{
if (ImageCollection.Count > 0)
{
List<ImageLink> imageLinks = new();
foreach (ImageLink img in ImageCollection)
{
// Need to Compress Image before adding to cloud..
ImageLink link = await CloudService.CS.UploadPostImage(img.PostImages);
imageLinks.Add(link);
}
P.Images = imageLinks;
}
}
解决方案
使用 SkiaSharp 给我的解决方案。
public static string CreateThumbnail(string Path, string fileName)
{
var bitmap = SKBitmap.Decode(Path);
int h = bitmap.Height;
int w = bitmap.Width;
int newWidth = w;
int newHeight = h;
//resize algorythm
if (h > 1080 || w > 1080)
{
int rectHeight = 1080;
int rectWidth = 1080;
//aspect ratio calculation
float W = w;
float H = h;
float aspect = W / H;
//new dimensions by aspect ratio
newWidth = (int)(rectWidth * aspect);
newHeight = (int)(newWidth / aspect);
//if one of the two dimensions exceed the box dimensions
if (newWidth > rectWidth || newHeight > rectHeight)
{
//depending on which of the two exceeds the box dimensions set it as the box dimension and calculate the other one based on the aspect ratio
if (newWidth > newHeight)
{
newWidth = rectWidth;
newHeight = (int)(newWidth / aspect);
}
else
{
newHeight = rectHeight;
newWidth = (int)(newHeight * aspect);
}
}
}
var resizedImage = bitmap.Resize(new SKImageInfo(newWidth, newHeight), SKBitmapResizeMethod.Lanczos3);
var image = resizedImage.Encode(SKEncodedImageFormat.Jpeg, 80);
var path = System.Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
var filepath = System.IO.Path.Combine(path, fileName);
string finalPath = filepath;
using (var stream = File.OpenWrite(filepath))
image.SaveTo(stream);
return finalPath;
}
推荐阅读
- c# - 无法访问 ABP 中 Hangfire 循环作业的已处置对象(在 DbContext 上)错误
- excel - 使用 Excel 公式根据单独的填充单元格选择日期
- outlook - 在 Outlook 的已发送文件夹中找不到使用 javamail 发送的邮件
- mysql - MySQL中Select ALL列时如何实现细粒度访问控制?
- django - 如何安全地访问 Django 模型中的请求对象
- winapi - 调用 ITaskScheduler::Activate 失败
- mysql - 访问 Heroku 数据库并连接本地 MySQL 数据库
- scala - Spark Cassandra 将数据集附加到具有空值的表
- html - 音频不会在部署的 Angular 应用程序上播放?
- android - Moshi 没有在 Map 中映射空值