Reputation: 43
How can I change an image file size to desired size ? Like an image of 800KB into 100KB ?
I have an image of 3MB Dimensions: (2560 X 1600) with 300 dpi and bit depth of 24. I simply read it in Bitmap change its resolution to 150 dpi and save with new name with thinking that may reduce it to almost half of its original but the new file keeps same size and dpi SetResolution donot create any effect.
Bitmap image = Bitmap.FromFile("myPic.jpeg");
image.SetResolution(96, 96);
image.Save("newPic.jpeg");
Then I used this code
// Reads Image
Bitmap image = Bitmap.FromFile("myPic.jpeg");
// Sets canvas with new dpi but same dimensions and color depth
Bitmap canvas = new Bitmap(image.Width, image.Height, PixelFormat.Format24bppRgb);
canvas.SetResolution(150, 150);
// Draw image on canvas through graphics
Graphics graphics = Graphics.FromImage(canvas);
graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
graphics.DrawImage(image, new Rectangle(0, 0, image.Width, image.Height),
new Rectangle(0, 0, image.Width, image.Height), GraphicsUnit.Pixel);
// Saved Image
bitmap.Save("newPic.jpeg");
Here dpi got changed for new file but file size jumps to 7.84MB
Where is the fault? Does dpi have any effect on file size ?
Thank you for your consideration. Stay Blessed
Upvotes: 1
Views: 4501
Reputation: 700720
The resolution (ppi / dpi) has no effect on the file size. It's only information about how large the image should be in physical dimensions, i.e. how to convert the pixel size into inches.
When you resave the image using a different resolution, the file will be completely identical, except for those two values.
When you create a new bitmap and draw the image onto that, the new bitmap object doesn't have a file type associated with it, so when you save it without specifying a file type, it will be saved as a PNG image instead of JPEG.
What you can do to change the file size without changing the pixel dimensions, is to change the compression level for the JPEG file.
MSDN: How to: Set JPEG Compression Level
Upvotes: 2