本文介紹獲取網絡上的圖片將其大小尺寸改成自己想要的
/// <summary> /// 圖片大小裁剪 /// </summary> /// <param name="filePath"></param> /// <returns></returns> public byte[] ResizeImage(string filePath) { WebRequest request = (WebRequest)HttpWebRequest.Create(filePath); WebResponse response = request.GetResponse(); using (Stream stream = response.GetResponseStream()) { Bitmap bm = (Bitmap)Image.FromStream(stream); bm = GetThumbnail(bm, 50, 40); MemoryStream ms = new MemoryStream(); bm.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp); byte[] bytes = ms.GetBuffer(); //byte[] bytes= ms.ToArray(); 這兩句都可以,至於區別么,下面有解釋 ms.Close(); return bytes; } }
/// <summary> /// 修改圖片的大小 /// </summary> /// <param name="b"></param> /// <param name="destHeight"></param> /// <param name="destWidth"></param> /// <returns></returns> public Bitmap GetThumbnail(Bitmap b, int destHeight, int destWidth) { System.Drawing.Image imgSource = b; System.Drawing.Imaging.ImageFormat thisFormat = imgSource.RawFormat; int sW = 0, sH = 0; // 按比例縮放 int sWidth = imgSource.Width; int sHeight = imgSource.Height; if (sHeight > destHeight || sWidth > destWidth) { if ((sWidth * destHeight) > (sHeight * destWidth)) { sW = destWidth; sH = (destWidth * sHeight) / sWidth; } else { sH = destHeight; sW = (sWidth * destHeight) / sHeight; } } else { sW = sWidth; sH = sHeight; } Bitmap outBmp = new Bitmap(destWidth, destHeight); Graphics g = Graphics.FromImage(outBmp); g.Clear(Color.Transparent); // 設置畫布的描繪質量 g.CompositingQuality = CompositingQuality.HighQuality; g.SmoothingMode = SmoothingMode.HighQuality; g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.DrawImage(imgSource, new Rectangle((destWidth - sW) / 2, (destHeight - sH) / 2, sW, sH), 0, 0, imgSource.Width, imgSource.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; imgSource.Dispose(); return outBmp; }
asp.net mvc 前台調用
/// <summary> /// 得到圖像 /// </summary> /// <param name="path"></param> /// <returns></returns> public FileResult GetAvator(string path) { return File(service.ResizeImage(path), "image/png"); }