資源簡介
C#使用GDI+處理圖片,包括
1、按比例縮放圖片
2、縮放到指定大小
3、裁剪縮放
4、四面裁剪圖片
5、忽略比例直接縮放
代碼片段和文件信息
enum?AnchorPosition
{
????Top
????Center
????Bottom
????Left
????Right
}
//1、按比例縮放圖片
static?Image?ScaleByPercent(Image?imgPhoto?int?Percent)
{
????float?nPercent?=?((float)Percent/100);
?
????int?sourceWidth?=?imgPhoto.Width;
????int?sourceHeight?=?imgPhoto.Height;
????int?sourceX?=?0;
????int?sourceY?=?0;
?
????int?destX?=?0;
????int?destY?=?0;?
????int?destWidth??=?(int)(sourceWidth?*?nPercent);
????int?destHeight?=?(int)(sourceHeight?*?nPercent);
?
????Bitmap?bmPhoto?=?new?Bitmap(destWidth?destHeight?
?????????????????????????????PixelFormat.Format24bppRgb);
????bmPhoto.SetResolution(imgPhoto.HorizontalResolution?
????????????????????????????imgPhoto.VerticalResolution);
?
????Graphics?grPhoto?=?Graphics.FromImage(bmPhoto);
????grPhoto.InterpolationMode?=?InterpolationMode.HighQualityBicubic;
?
????grPhoto.DrawImage(imgPhoto?
????????new?Rectangle(destXdestYdestWidthdestHeight)
????????new?Rectangle(sourceXsourceYsourceWidthsourceHeight)
????????GraphicsUnit.Pixel);
?
????grPhoto.Dispose();
????return?bmPhoto;
}
//2、縮放到指定大小
static?Image?FixedSize(Image?imgPhoto?int?Width?int?Height)
{
????int?sourceWidth?=?imgPhoto.Width;
????int?sourceHeight?=?imgPhoto.Height;
????int?sourceX?=?0;
????int?sourceY?=?0;
????int?destX?=?0;
????int?destY?=?0;?
?
????float?nPercent?=?0;
????float?nPercentW?=?0;
????float?nPercentH?=?0;
?
????nPercentW?=?((float)Width/(float)sourceWidth);
????nPercentH?=?((float)Height/(float)sourceHeight);
????if(nPercentH?????{
????????nPercent?=?nPercentH;
????????destX?=?System.Convert.ToInt16((Width?-?
??????????????????????(sourceWidth?*?nPercent))/2);
????}
????else
????{
????????nPercent?=?nPercentW;
????????destY?=?System.Convert.ToInt16((Height?-?
??????????????????????(sourceHeight?*?nPercent))/2);
????}
?
????int?destWidth??=?(int)(sourceWidth?*?nPercent);
????int?destHeight?=?(int)(sourceHeight?*?nPercent);
?
????Bitmap?bmPhoto?=?new?Bitmap(Width?Height?
??????????????????????PixelFormat.Format24bppRgb);
????bmPhoto.SetResolution(imgPhoto.HorizontalResolution?
?????????????????????imgPhoto.VerticalResolution);
?
????Graphics?grPhoto?=?Graphics.FromImage(bmPhoto);
????grPhoto.Clear(Color.Red);
????grPhoto.InterpolationMode?=?
????????????InterpolationMode.HighQualityBicubic;
?
????grPhoto.DrawImage(imgPhoto?
????????new?Rectangle(destXdestYdestWidthdestHeight)
????????new?Rectangle(sourceXsourceYsourceWidthsourceHeight)
????????GraphicsUnit.Pixel);
?
????grPhoto.Dispose();
????return?bmPhoto;
}
//3、裁剪縮放
static?Image?Crop(Image?imgPhoto?int?Width?
????????????????????int?Height?AnchorPosition?Anchor)
{
????int?sourceWidth?=?imgPhoto.Width;
????int?sourceHeight?=?imgPhoto.Height;
????int?sourceX?=?0;
????int?sourceY?=?0;
????int?destX?=?0;
????int?destY?=?0;
?
????float?nPercent?=?0;
????float?nPercentW?=?0;
????float?nPercentH?=?0;
?
????nPercentW?=?((float)Width/(
評論
共有 條評論