Search code examples
c#bitmapdpi

Trying to change image DPI without changing file size


I have the following code for changing the DPI of an image:

public void changeDPI(string imagePathSource,string imagePathDestination,float DPIx,float DPIy)
        {
            Bitmap bitmap = new Bitmap(imagePathSource);
            Bitmap newBitmap = new Bitmap(bitmap);
            newBitmap.SetResolution(DPIx,DPIy);
            newBitmap.Save(imagePathDestination);
        }

However, this ends up changing the memory size of the file. An example test image started at 267 KB, and the newBitmap version of the file ended up as 1.51 MB. How can I change the DPI without changing the file size?


Solution

  • I think you must indicate the format of the output file, to save as a compressed image format like JPEG.

    newBitmap.Save(imagePathDestination, System.Drawing.Imaging.ImageFormat.Jpeg);