Home > Article > Backend Development > How to resize image in 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
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; }
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!