上传前在.Net core Blazor中压缩图像

问题描述 投票:0回答:1

我需要上传图像然后将其存储在数据库上。我想在将图像上传到服务器之前对其进行压缩或调整大小。我正在尝试 magick.Net,但它现在对我不起作用。任何其他方法都会非常有帮助。

我的代码如下。

Index.razor 页面

<FormItem>
    <Template>
        <label for="Remarks" class="k-label k-form-label">@MOM.Alias.Common.DTO.Icon</label>
        <CardImage Src="@ImageSrc" Height="100px" Width="100px" />
        <TelerikButton Id="btnTicketCategoryRemove" ButtonType="@Telerik.Blazor.ButtonType.Button" Visible="@(ImageSrc!= MOM.UI.Client.Constants.Common.NoImageIcon)" Icon="FontIcon.Trash" [email protected] ThemeColor="@ThemeConstants.Button.ThemeColor.Error" OnClick="@RemoveIcon" Size="@size" Rounded="@size"></TelerikButton>

        <TelerikFileSelect AllowedExtensions="@Common.AllowAllowedFileTypes"
                           OnSelect="@OnSelect" OnRemove="@OnRemove" Multiple=false
                           MinFileSize="Common.MinFileSize" MaxFileSize="Common.MaxFileSize" @ref="@telerikFileSelectRef">
        </TelerikFileSelect>
        <div class="k-form-hint">
            @Constants.Label.ExpectedFiles <strong>@Constants.Label.AllowedFileTypes</strong><br />
            @Constants.Label.Between <strong>&nbsp;@Constants.Label.MinSizeText</strong>&nbsp; @Constants.Label.And <strong>@Constants.Label.MaxSizeText</strong>
        </div>
    </Template>
</FormItem>

@代码片段

public async Task OnSelect(FileSelectEventArgs args)
{
    try
    {
        FileSelectFileInfo file = args.Files[0];
        if (!file.InvalidExtension && !file.InvalidMaxFileSize && !file.InvalidMinFileSize)
        {
            var byteArray = new byte[file.Stream.Length];
            var stream = new MemoryStream(byteArray);
            await file.Stream.CopyToAsync(stream);
            dto.Icon = stream.ToArray();

            ImageSrc = CommonHelper.GetImageFromByteArray(dto.Icon);
        }                        
        dialogRef?.Refresh();
    }
    catch (Exception ex)
    {
        throw ex;
    }
}
c# asp.net-core blazor telerik
1个回答
0
投票

试试这个:

     if (model.AttachmentType == (int)MessageType.Media && model.IsFromMobile == false || model.IsFromMobile == null)
     {
         var imageService = new ImageService();
         await imageService.CompressAndSaveImageAsync(formFile, path, 30);
     }

实施:

using Microsoft.AspNetCore.Http;
using SixLabors.ImageSharp.Formats.Jpeg;

namespace Services
{
    public class ImageService
    {
         public async Task CompressAndSaveImageAsync(IFormFile imageFile, 
         string outputPath, int quality = 75)
         {
             using var imageStream = imageFile.OpenReadStream();
             using var image = Image.Load(imageStream);
             var encoder = new JpegEncoder
             {
                 Quality = quality, // Adjust this value for desired compression quality
        };

        await Task.Run(() => image.Save(outputPath, encoder));
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.