Harshad Raval
Harshad Raval

Reputation: 79

Is there any way to limit resized image file size?

I am looking for a way to limit resized image file size. Resized image size should not exceed given size i.e. 100KB.

This is my code to resize image:

using (var ms = new MemoryStream(Image_data))
{
    var image = Image.FromStream(ms);
    var ratioX = (double)1800 / image.Width;
    var ratioY = (double)1500 / image.Height;

    var ratio = Math.Min(ratioX, ratioY);
    var width = (int)(image.Width * ratio);
    var height = (int)(image.Height * ratio);

    var newImage = new Bitmap(width, height);
    Graphics.FromImage(newImage).DrawImage(image, 0, 0, width, height);
    Graphics.FromImage(newImage).CompositingQuality = CompositingQuality.HighQuality;
    Graphics.FromImage(newImage).SmoothingMode = SmoothingMode.HighQuality;
    Graphics.FromImage(newImage).InterpolationMode = InterpolationMode.HighQualityBicubic;
    Bitmap bmp = new Bitmap(newImage);

    ImageConverter converter = new ImageConverter();
    Image_data = (byte[])converter.ConvertTo(bmp, typeof(byte[]));
    string SmallImageData = string.Format(Convert.ToBase64String(Image_data));
    string subpath = ConfigurationManager.AppSettings["ResizedImagePath"];
    bool pathexists = System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(subpath));
    if (!pathexists)
    {
        System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(subpath));
    }
    string path = HttpContext.Current.Server.MapPath(subpath) + "/" + ImageName + ".jpeg";
    bmp.Save(path, ImageFormat.Jpeg);
}

But above code generate image file of any size.

Upvotes: 1

Views: 418

Answers (1)

Noah Stahl
Noah Stahl

Reputation: 7553

Magick.NET provides an Extent parameter to specify a maximum file size output, which informs the compression. Description:

Gets or sets the compression quality that does not exceed the specified extent in kilobytes (jpeg:extent).

An example as a test case from the source repo:

var defines = new JpegWriteDefines
{
    Extent = 10, // 10 KB target size
};

using (var image = new MagickImage(/* File */))
{
    using (MemoryStream memStream = new MemoryStream())
    {
        image.Settings.SetDefines(defines);

        image.Format = MagickFormat.Jpeg;
        image.Write(memStream);
    }
}

Upvotes: 1

Related Questions