1public bool MakeThumbnail(string thumb, string img, int width, int height, bool keepOriginalRatio)
2 {
3 System.Drawing.Image fullSizeImg;
4 try
5 {
6 fullSizeImg = new System.Drawing.Bitmap(img);
7 }
8 catch (Exception ex)
9 {
10 return false;
11 }
12
13 if ((fullSizeImg.Width <= width) && (fullSizeImg.Height <= height))
14 {
15 //Smaller or same size as thumbnail so no need to do anything special
16 try
17 {
18 fullSizeImg.Save(thumb);
19 return true;
20 }
21 catch (Exception ex)
22 {
23 return false;
24 }
25 }
26 else
27 {
28 if (keepOriginalRatio)
29 {
30 if (width <= 0)
31 {
32 width = height * fullSizeImg.Width / fullSizeImg.Height;
33 }
34 else if (height <= 0)
35 {
36 height = width * fullSizeImg.Height / fullSizeImg.Width;
37 }
38 else
39 {
40 float TargetRatio = width / height;
41 float CurrentRatio = fullSizeImg.Width / fullSizeImg.Height;
42
43 if (CurrentRatio > TargetRatio) //We'll scale height
44 { height = width / Convert.ToInt16(CurrentRatio); }
45 else // We'll scale width
46 { width = height * Convert.ToInt16(CurrentRatio); }
47 }
48 }
49
50 System.Drawing.Image thumbNailImg = new System.Drawing.Bitmap(fullSizeImg, width, height);
51 System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(thumbNailImg);
52
53 g.FillRectangle(System.Drawing.Brushes.White, 0, 0, width, height);
54 g.DrawImage(fullSizeImg, 0, 0, width, height);
55
56 try
57 {
58 thumbNailImg.Save(thumb, fullSizeImg.RawFormat);
59 }
60 catch (Exception ex)
61 {
62 return false;
63 }
64 }
65 return false;
66 }