Skip to content

Instantly share code, notes, and snippets.

@arman-hpp
Created October 6, 2024 07:22
Show Gist options
  • Save arman-hpp/31f493df7f2fdd596dba5e0bd0571a01 to your computer and use it in GitHub Desktop.
Save arman-hpp/31f493df7f2fdd596dba5e0bd0571a01 to your computer and use it in GitHub Desktop.
PicReducer
private static byte[] ReducePicture(string inputPath, int percentage, int quality = 75)
{
using (var originalImage = Image.FromFile(inputPath))
{
var newWidth = originalImage.Width * percentage / 100;
var newHeight = originalImage.Height * percentage / 100;
using (var resizedImage = new Bitmap(newWidth, newHeight))
{
using (var graphics = Graphics.FromImage(resizedImage))
{
graphics.DrawImage(originalImage, 0, 0, newWidth, newHeight);
}
using (var memoryStream = new MemoryStream())
{
var codecs = ImageCodecInfo.GetImageDecoders();
var jpgEncoder = codecs.FirstOrDefault(codec => codec.FormatID == ImageFormat.Jpeg.Guid);
if (jpgEncoder == null)
throw new InvalidCastException("Jpg encoder doesn't exists.");
var encoderParameters = new EncoderParameters(1);
encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, quality);
resizedImage.Save(memoryStream, jpgEncoder, encoderParameters);
return memoryStream.ToArray();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment