如題:
添加命名空間如下:
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);
outBmp.Save(newfile, thisformat);
img.Dispose();
outBmp.Dispose();
頁面上是一個FileUpload控件,先上傳原圖,在顯示在頁面上,添加一個Image控件,寬,高設為:100×100,用以對比縮略圖。
将原圖輸出縮略為100×100;