Home > Backend Development > C#.Net Tutorial > How to resize image in C#?

How to resize image in C#?

WBOY
Release: 2023-09-18 18:41:02
forward
1478 people have browsed it

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;
}
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template