I am working on a .NET application to reduce image file sizes using ImageMagick. My application stores some "settings" in a Hashtable for use in various areas of the application. I am now adding a feature to reduce image size based on desired DPI in the transformed image. Basically, I am looking up the DPI in the unaltered image, calculating the percentage of the desired DPI in relation to the current DPI, and then I will resize the image dimensions by this proportion.
ImageMagick reports image DPI as floating point values. So 200x200 DPI is really 199.975x199.975. Thus I use Math.Ceiling() to get the values into my application. When I try to use the desired DPI from my settings Hashtable to do the percentage calculation I get an invalid cast exception. I don't know why this is happening.
Here is a test case that fails in the same manner as my actual code:
using System;
using System.Collections;
namespace typetest
{
class Program
{
private struct DPI {
public double x;
public double y;
}
public static void Main(string[] args)
{
Hashtable vars = new Hashtable();
DPI dpi;
string dpiString = "199.547:199.547";
string[] ret;
vars["newDpiX"] = 150;
vars["newDpiY"] = 150;
ret = dpiString.Split(':');
dpi.x = ( (double)vars["newDpiX"] / Math.Ceiling(double.Parse(ret[0])) ) * 100;
dpi.y = ( (double)vars["newDpiY"] / Math.Ceiling(double.Parse(ret[1])) ) * 100;
Console.WriteLine("New DPI percentage = " + dpi.x + "%x" + dpi.y +"%");
}
}
}
If I change the division to
double newDpiX = 150.0;
dpi.x = ( newDpiX / Math.Ceiling(double.Parse(ret[0])) ) * 100;
it will work as expected. What is going on here?