using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Web;
namespace Book_Painting.Common
{
/// <summary>
/// 圖片壓縮
/// </summary>
public class ThumbnailImage
{
/// <summary>
/// 按照指定大小縮放圖片,但是為了保證圖片寬高比自動截取
/// </summary>
/// <param name="srcImage"></param>
/// <param name="iWidth"></param>
/// <param name="iHeight"></param>
/// <returns></returns>
public Bitmap SizeImageWithOldPercent(Image srcImage, int iWidth, int iHeight)
{
try
{
// 要截取圖片的寬度(臨時圖片)
int newW = srcImage.Width;
// 要截取圖片的高度(臨時圖片)
int newH = srcImage.Height;
// 截取開始橫坐標(臨時圖片)
int newX = 0;
// 截取開始縱坐標(臨時圖片)
int newY = 0;
// 截取比例(臨時圖片)
double whPercent = 1;
whPercent = ((double)iWidth / (double)iHeight) * ((double)srcImage.Height / (double)srcImage.Width);
if (whPercent > 1)
{
// 當前圖片寬度對於要截取比例過大時
newW = int.Parse(Math.Round(srcImage.Width / whPercent).ToString());
}
else if (whPercent < 1)
{
// 當前圖片高度對於要截取比例過大時
newH = int.Parse(Math.Round(srcImage.Height * whPercent).ToString());
}
if (newW != srcImage.Width)
{
// 寬度有變化時,調整開始截取的橫坐標
newX = Math.Abs(int.Parse(Math.Round(((double)srcImage.Width - newW) / 2).ToString()));
}
else if (newH == srcImage.Height)
{
// 高度有變化時,調整開始截取的縱坐標
newY = Math.Abs(int.Parse(Math.Round(((double)srcImage.Height - (double)newH) / 2).ToString()));
}
// 取得符合比例的臨時文件
Bitmap cutedImage = CutImage(srcImage, newX, newY, newW, newH);
// 保存到的文件
Bitmap b = new Bitmap(iWidth, iHeight);
Graphics g = Graphics.FromImage(b);
// 插值算法的質量
g.InterpolationMode = InterpolationMode.Default;
g.DrawImage(cutedImage, new Rectangle(0, 0, iWidth, iHeight), new Rectangle(0, 0, cutedImage.Width, cutedImage.Height), GraphicsUnit.Pixel);
g.Dispose();
return b;
}
catch (Exception)
{
return null;
}
}
/// <summary>
/// 剪裁 -- 用GDI+
/// </summary>
/// <param name="b">原始Bitmap</param>
/// <param name="StartX">開始坐標X</param>
/// <param name="StartY">開始坐標Y</param>
/// <param name="iWidth">寬度</param>
/// <param name="iHeight">高度</param>
/// <returns>剪裁后的Bitmap</returns>
public Bitmap CutImage(Image b, int StartX, int StartY, int iWidth, int iHeight)
{
if (b == null)
{
return null;
}
int w = b.Width;
int h = b.Height;
if (StartX >= w || StartY >= h)
{
// 開始截取坐標過大時,結束處理
return null;
}
if (StartX + iWidth > w)
{
// 寬度過大時只截取到最大大小
iWidth = w - StartX;
}
if (StartY + iHeight > h)
{
// 高度過大時只截取到最大大小
iHeight = h - StartY;
}
try
{
Bitmap bmpOut = new Bitmap(iWidth, iHeight);
Graphics g = Graphics.FromImage(bmpOut);
g.DrawImage(b, new Rectangle(0, 0, iWidth, iHeight), new Rectangle(StartX, StartY, iWidth, iHeight), GraphicsUnit.Pixel);
g.Dispose();
return bmpOut;
}
catch
{
return null;
}
}
}
}
調用截圖
