Click here to Skip to main content
15,888,610 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
how can i change picture dpi from 96 dpi to 300 dpi i c#

What I have tried:

private void button2_Click(object sender, EventArgs e)
{
var filename = @"--input--image--";
var targetfile = @"--output-image--";

using (var image = Image.FromFile(filename))
{
// changing to 96 DPI
var resolution = new byte[8] { 0, 0, 96, 0, 0, 0, 1, 0 };

if (image.PropertyIdList.Contains(282))
{
var xResolution = image.GetPropertyItem(300);
xResolution.Value = resolution;
image.SetPropertyItem(xResolution);
}
if (image.PropertyIdList.Contains(283))
{
var yResolution = image.GetPropertyItem(300);
yResolution.Value = resolution;
image.SetPropertyItem(yResolution);
}

image.Save(targetfile, image.RawFormat);
}
}
but this is not working
Posted
Updated 6-Sep-16 0:22am
Comments
Philippe Mori 6-Sep-16 13:24pm    
Is it that hard to use a code block to make code readable? I am not interested in answering such questions as it take twice as much time to understand unformatted code...

1 solution

Changing resolution is complicated: it's not just a case of altering a simple variable.
You need to look at how images are stored: they contain a fixed number of pixels (x width by y height) and the DPI value only controls how many of those are initially displayed in a physical inch on a particular device when the image is drawn to it. Changing the DPI values in the file doesn't change the number of pixels, and often won't affect how the image is displayed, given that it's frequently stretched or shrunk to fit into a particular part of a display or page.

It's possible to "upscale" or "downscale" the resolution by re-rendering the image, but that doesn't add detail (despite what you see on TV) - it just makes pixels bigger or extrapolates extra pixel values when you upscale, or discards details when you downscale. Even then, it's not a trivial process.

And reading and saving files is a bad idea unless you really, really need to - most images are compressed, and the most popular format - jpeg - uses a "lossy" compression, so each time you save the image, you lose data which you cannot recover. Often 4 or 5 saves is enough to reduce a file to unusability, but even one extra can "soften" detail out noticeably.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900