如题:
添加命名空间如下:
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
-----------------------------------------------------------------------------------------------
显示原图:
- //显示原图
- protected void btnImage_Click(object sender, EventArgs e)
- {
- string filePath = Server.MapPath("~/Up/美女.jpg");
- //方式一:
- //Response.ContentType = "image/jpeg";
- //Response.WriteFile(filePath);
- //方式二:
- FileStream imageStr = new FileStream(filePath, FileMode.Open);
- byte[] imageData=new byte[imageStr.Length];
- imageStr.Read(imageData,0,(int)imageStr.Length);
- Response.OutputStream.Write(imageData, 0, (int)imageStr.Length);
- }
想要改变的尺寸:
- private static Size NewSize(int maxWidth, int maxHeight, int Width, int Height)
- {
- double w = 0.0;
- double h = 0.0;
- double sw = Convert.ToDouble(Width);
- double sh = Convert.ToDouble(Height);
- double mw = Convert.ToDouble(maxWidth);
- double mh = Convert.ToDouble(maxHeight);
- if (sw < mw && sh < mh)//如果maxWidth和maxHeight大于源图像,则缩略图的长和高不变
- {
- w = sw;
- h = sh;
- }
- else if ((sw / sh) > (mw / mh))
- {
- w = maxWidth;
- h = (w * sh) / sw;
- }
- else
- {
- h = maxHeight;
- w = (h * sw) / sh;
- }
- return new Size(Convert.ToInt32(w), Convert.ToInt32(h));
- }
转化成缩略图:
- //转化成缩略图
- public void SendSmallImage(string filename, string newfile, int maxHeight, int maxWidth)
- {
- System.Drawing.Image img = System.Drawing.Image.FromFile(filename);//源图像的信息
- System.Drawing.Imaging.ImageFormat thisformat = img.RawFormat; //源图像的格式
- Size newSize = NewSize(maxWidth, maxHeight, img.Width, img.Height); //返回调整后的图像Width与Height
- Bitmap outBmp = new Bitmap(newSize.Width, newSize.Height);
- Graphics g = Graphics.FromImage(outBmp);
- //设置画布的描绘质量(高)
- g.CompositingQuality = CompositingQuality.HighQuality;
- g.SmoothingMode = SmoothingMode.HighQuality;
- g.InterpolationMode = InterpolationMode.HighQualityBicubic;
- g.DrawImage(img, new Rectangle(0, 0, newSize.Width, newSize.Height), 0, 0, img.Width, img.Height, GraphicsUnit.Pixel);
- g.Dispose();
- //以下代码为保存图片时,设置压缩质量
- EncoderParameters encoderParams = new EncoderParameters();
- long[] quality = new long[1];
- quality[0] = 100;
- EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
- encoderParams.Param[0] = encoderParam;
- //获取包含有关内置图像编码解码器的信息的ImageCodecInfo对象。
- ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
- ImageCodecInfo jpegICI = null;
- for (int x = 0; x < arrayICI.Length; x++)
- {
- if (arrayICI[x].FormatDescription.Equals("JPEG"))
- {
- jpegICI = arrayICI[x];//设置jpeg编码
- break;
- }
- }
- if (jpegICI != null)
- {
- outBmp.Save(newfile , jpegICI, encoderParams);
- }
- else
- {
- outBmp.Save(newfile, thisformat);
- }
- img.Dispose();
- outBmp.Dispose();
- }
页面上是一个FileUpload控件,先上传原图,在显示在页面上,添加一个Image控件,宽,高设为:100×100,用以对比缩略图。
将原图输出缩略为100×100;
原文发布时间为:2009-10-27
本文作者:vinoYang
本文来自云栖社区合作伙伴CSDN博客,了解相关信息可以关注CSDN博客。