using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
public static void ResizeImage(string fileNameIn, string fileNameOut, int maxWidthOrHeight)
{
// Open the image
Bitmap bmpSource = new Bitmap(fileNameIn);
Size originalSize = bmpSource.Size;
Size newSize = new Size(0, 0);
bmpSource.Dispose();
decimal maxHeightDecimal = Convert.ToDecimal(maxWidthOrHeight);
decimal maxWidthDecimal = Convert.ToDecimal(maxWidthOrHeight);
decimal resizeFactor = 0;
if (originalSize.Height > originalSize.Width)
{
// Portrait
resizeFactor = Convert.ToDecimal(Decimal.Divide(originalSize.Height, maxHeightDecimal));
newSize.Height = maxWidthOrHeight;
newSize.Width = Convert.ToInt32(originalSize.Width / resizeFactor);
}
else
{
// Lanscape
resizeFactor = Convert.ToDecimal(Decimal.Divide(originalSize.Width, maxWidthDecimal));
newSize.Height = Convert.ToInt32(originalSize.Height / resizeFactor);
newSize.Width = maxWidthOrHeight;
}
Bitmap mySourceBitmap = null;
Bitmap myTargetBitmap = null;
Graphics myGraphics = null;
try
{
mySourceBitmap = new Bitmap(fileNameIn);
int newWidth = newSize.Width;
int newHeight = newSize.Height;
myTargetBitmap = new Bitmap(mySourceBitmap, newWidth, newHeight);
myGraphics = Graphics.FromImage(myTargetBitmap);
myGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
mySourceBitmap.Dispose();
// Save th new image
myTargetBitmap.Save(fileNameOut, ImageFormat.Jpeg);
}
catch (Exception)
{
throw;
}
finally
{
if (myGraphics != null) myGraphics.Dispose();
if (mySourceBitmap != null) mySourceBitmap.Dispose();
if (myTargetBitmap != null) myTargetBitmap.Dispose();
}
}
ไม่มีความคิดเห็น:
แสดงความคิดเห็น