Front-end image compression before image component upload

[删除(380066935@qq.com或微信通知)]

更好的阅读体验请查看原文:https://github.com/ant-design-blazor/ant-design-blazor/issues/3344

Install SkiaSharp.Views.Blazor

下面是我采用 input file 原生上传实现的方式,上传之后会检测图片的高和宽,将 高或宽的最大值裁剪为1920px,成功运行。

The following is the way I upload the input file natively. After uploading, the height and width of the image will be detected, and the maximum height or width will be cropped to 1920px. It runs successfully.

<FormItem Label="上传">
            <InputFile OnChange="@LoadFiles" multiple />
</FormItem>
private async void LoadFiles(InputFileChangeEventArgs e)
  {
      foreach (var file in e.GetMultipleFiles())
      {
          string url = "https://xxxx.com/api/File/UploadFile";

          using HttpClientHandler handler = new();

          using HttpClient client = new(handler);
          client.DefaultVersionPolicy = HttpVersionPolicy.RequestVersionOrHigher;

          foreach (var header in headers)
          {
              client.DefaultRequestHeaders.Add(header.Key, header.Value);
          }

          string boundary = "----" + DateTime.UtcNow.Ticks.ToString("x");

          using MultipartFormDataContent formDataContent = new(boundary);

          byte[] imageByteArray;

          using (var memoryStream = new MemoryStream())
          {
              await file.OpenReadStream(1024*10000).CopyToAsync(memoryStream);
              imageByteArray = memoryStream.ToArray();
          }

          using var original = SKBitmap.Decode(imageByteArray);

          int maxSideLength = 1920;

          int width = 0;
          int height = 0;

          if (original.Width > original.Height)
          {
              if (original.Width > maxSideLength)
              {
                  var percent = maxSideLength / (float)original.Width;
                  width = (int)(original.Width * percent);
                  height = (int)(original.Height * percent);
              }
          }
          else
          {
              if (original.Height > maxSideLength)
              {
                  var percent = maxSideLength / (float)original.Height;
                  width = (int)(original.Width * percent);
                  height = (int)(original.Height * percent);
              }
          }

          using var resizeBitmap = original.Resize(new SKImageInfo(width, height), SKFilterQuality.High);
          using var image = SKImage.FromBitmap(resizeBitmap);
          using var imageData = image.Encode(SKEncodedImageFormat.Jpeg, 100);

          var fileContent = new StreamContent(imageData.AsStream());

          fileContent.Headers.ContentType = new MediaTypeHeaderValue(file.ContentType);
          formDataContent.Add(fileContent, "file", file.Name);

          var httpResponse = await client.PostAsync(url, formDataContent);

          string responseStr = httpResponse.Content.ReadAsStringAsync().Result;

          Console.WriteLine("Success");
      }
  }