0

Just wandering, how to reduce the file size of the image but keeping the quality in C# .net?

I have the following code use to save the image taken from ipad:

Bitmap srcBmp = new Bitmap(file.InputStream);

int w = srcBmp.Width;
int h = srcBmp.Height;
if (srcBmp.Width > 2732 && srcBmp.Height > 2048)
{
    w = 2732;
    h = 2048;
}

SizeF newSize = new SizeF(w, h);
Bitmap target = new Bitmap(w, h);
var destRect = new Rectangle(0, 0, w, h);

HttpContext.Response.Clear();
HttpContext.Response.ContentType = "image/jpeg";
using (var graphics = Graphics.FromImage(target))
{
    graphics.CompositingMode = CompositingMode.SourceCopy;
    graphics.CompositingQuality = CompositingQuality.HighQuality;
    graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
    graphics.SmoothingMode = SmoothingMode.HighQuality;
    graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;

    using (var wrapMode = new ImageAttributes())
    {
        wrapMode.SetWrapMode(WrapMode.TileFlipXY);
        graphics.DrawImage(srcBmp, destRect, 0, 0, w, h, GraphicsUnit.Pixel, wrapMode);
        using (FileStream fileStream = new FileStream(fname, FileMode.Create))
        {
            target.Save(fileStream, System.Drawing.Imaging.ImageFormat.Jpeg);
        }
    }
}

The Image been saved is always over 14MB. Anyway I can keep the image quality and reduce the file size below 2MB?

shA.t
  • 16,580
  • 5
  • 54
  • 111
Jin Yong
  • 42,698
  • 72
  • 141
  • 187
  • There are many posts related to the same thing like [this one](https://stackoverflow.com/questions/87753/resizing-an-image-without-losing-any-quality), and also [this](http://www.c-sharpcorner.com/blogs/resizing-image-in-c-sharp-without-losing-quality1), so check them out. – boop_the_snoot Aug 21 '17 at 04:30
  • I think you mean *reduce image size* instead of *reduce file size* as your code ;). – shA.t Aug 21 '17 at 04:33

1 Answers1

0

I don't think that much reduction without decresing the picture quality is possible. However you can remove the metadata from an image using the Exif library without reducing the picture quality

Or if you are good with reduction in picture quality you can use GID

Sumodh S
  • 709
  • 1
  • 14
  • 36