为了提高与用户的交互力,很多网站都有图片上传之类的功能,
图片过大在显示时是很占用资源的(为了布局用IMG控制成小图更亏),
下面便用两个简单的方法,为大图片生成需要的小图片
方法1: 使用 System.Drawing.Image
- /// <summary>
- /// 对图片进行处理,返回一个Image类别的对象
- /// </summary>
- /// <param name="oldImgPath">原图片路径</param>
- /// <param name="newWidth">新图片宽度</param>
- /// <param name="newHeight">新图片高度</param>
- /// <returns></returns>
- public static Image GetNewImage(string oldImgPath, int newWidth, int newHeight)
- {
- Image oldImg = Image.FromFile(oldImgPath); // 加载原图片
- Image newImg = oldImg.GetThumbnailImage(newWidth, newHeight, new Image.GetThumbnailImageAbort(IsTrue), IntPtr.Zero); // 对原图片进行缩放
- return newImg;
- }
- private static bool IsTrue() // 在Image类别对图片进行缩放的时候,需要一个返回bool类别的委托
- {
- return true;
- }
方法2: 使用 System.Drawing.Bitmap
- /// <summary>
- /// 对图片进行处理,返回一个Bitmap类别的对象
- /// </summary>
- /// <param name="oldBmpPath">原图片路径</param>
- /// <param name="newWidth">新图片宽度</param>
- /// <param name="newHeight">新图片高度</param>
- /// <returns></returns>
- public static Bitmap GetNewBitMap(string oldBmpPath, int newWidth, int newHeight)
- {
- Bitmap oldBmp = new Bitmap(oldBmpPath); // 加载原图片
- Bitmap bmp = new Bitmap(newWidth, newHeight); // 创建新图片
- Graphics grap = Graphics.FromImage(bmp); // 绑定画板
- // 原图片的开始绘制位置,及宽和高 (控制Rectangle的组成参数,便可实现对图片的剪切)
- Rectangle oldRect = new Rectangle(0, 0, oldBmp.Width, oldBmp.Height);
- // 绘制在新画板中的位置,及宽和高 (在这里是完全填充)
- Rectangle newRect = new Rectangle(0, 0, newWidth, newHeight);
- // 指定新图片的画面质量
- grap.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear;
- // 把原图片指定位置的图像绘制到新画板中
- grap.DrawImage(oldBmp, newRect, oldRect, GraphicsUnit.Pixel);
- /*
- * 画图的步骤到此就已经完成了.
- *
- * 在绘制完成新图片后,还可以使用 Graphics对象的一些方法,为图片添加自定义的内容
- * grap.DrawString(...);添加文字
- * grap.DrawPie(...);添加扇形
- * grap.DrawLine(...);添加直线
- * ...
- * */
- // 添加文字
- Brush bru = Brushes.Red; // 笔刷
- Font font = new Font(new FontFamily("华文行楷"), 30, FontStyle.Regular, GraphicsUnit.World); // 字体
- PointF pf = new PointF(3, 3); // 坐标
- grap.DrawString("羊", font, bru, pf); // 填充文字
- return bmp;
- }
调用方法:
- protected void Button1_Click(object sender, EventArgs e)
- {
- Image img = UpdateImage.GetNewImage(FileUpload1.PostedFile.FileName/*图片路径*/, 200, 200);
- img.Save(Server.MapPath("img_XXX.jpg"));
- Bitmap bmp = UpdateImage.GetNewBitMap(FileUpload1.PostedFile.FileName/*图片路径*/, 200, 200);
- bmp.Save(Server.MapPath("bm_XXX.jpg"));
- }