Home  >  Article  >  Backend Development  >  How to resize image in C#?

How to resize image in C#?

WBOY
WBOYforward
2023-09-18 18:41:021409browse

C# 如何调整图像大小?

A bitmap consists of the pixel data of a graphic image and its attributes. There are many standard formats for saving bitmaps to files. GDI supports the following file formats: BMP, GIF, EXIF, JPG, PNG, and TIFF. You can use one of the Bitmap constructors to create images from files, streams, and other sources, and use the Save method to save them to a stream or file system.

In the code below CompressAndSaveImageAsync method compresses the image and saves it in the mentioned path.

The new image name will be the combination of desktop userId and dateTime

Example

private async Task<string> CompressAndSaveImageAsync(Bitmap inputImage, int quality=50){
   string imageSavedPath = string.Empty;
   try{
      var jpgEncoder = await GetEncoderAsync(ImageFormat.Jpeg);
      var imageEncoder = Encoder.Quality;
      var imageEncoderParameters = new EncoderParameters(1);
      var imageEncoderParameter = new EncoderParameter(imageEncoder, quality);
      imageEncoderParameters.Param[0] = imageEncoderParameter;
      var userId = Regex.Replace(WindowsIdentity.GetCurrent().Name, @"[^0&minus;9a&minus;zA&minus;Z]+", "_");
      var currentDateTime = Regex.Replace(DateTimeOffset.Now.ToString().Split(&#39;+&#39;)[0].Trim(), @"   [^0&minus;9a&minus;zA&minus;Z]+", "_");
      var imageName = $"{userId}_{currentDateTime}.jpg";
      imageSavedPath = "C:\Users\K\Desktop\Questions\Images";
      inputImage.Save(imageSavedPath, jpgEncoder, imageEncoderParameters);
      inputImage.Dispose();
   }
   catch (Exception ex){
      throw
   }
   return imageSavedPath;
}
private async Task<ImageCodecInfo> GetEncoderAsync(ImageFormat format){
   ImageCodecInfo imageCodecInfo = null;
   try{
      var codecs = ImageCodecInfo.GetImageDecoders();
      foreach (var codec in codecs){
         if (codec.FormatID == format.Guid){
            imageCodecInfo = codec;
         }
      }
   }
   catch (Exception ex){
      throw
   }
   return imageCodecInfo;
}

The above is the detailed content of How to resize image in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete
Previous article:C# interface typeNext article:C# interface type