How to resize an Image C#?


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

In the below code CompressAndSaveImageAsync Method Compresses the images and saves in the path Mentioned.

The new image name will be a 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−9a−zA−Z]+", "_");
      var currentDateTime = Regex.Replace(DateTimeOffset.Now.ToString().Split('+')[0].Trim(), @"   [^0−9a−zA−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;
}

Updated on: 07-Nov-2020

458 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements