以前寫過這個內容,但是找不到了再寫一次 由於cs和bs 顯示圖片原理不一樣,所以不一樣
(bs顯示原理圖片為產生圖片輸出到用戶端,當然不包括用戶端的繪圖程式VML,SVG等,而cs程式介面本身就可以看作是一個畫板)
(bs顯示圖片除了image控制項,直接輸出http流也行,但是如果要用image控制項,就必須依賴image.url也就是bs的image控制項必須依賴一個存在的物理地址顯示而不像cs的控制項可以依賴一個記憶體流,不管是圖片,.aspx,.ashx等等,也就是想要動態顯示圖片需要在連結地址或者流輸出上做文章)
/// <summary>
/// 縮放圖片(cs控制項用,因為cs控制項需要返回System.Drawing.Image)原理需要產生新圖片寬度
/// </summary>
/// <param name="img">原圖片</param>
/// <param name="xWith">縮放寬比例,如果想縮小圖片,小於100</param>
/// <param name="yHeight">縮放高比例</param>
/// <returns>返回處理後圖片</returns>
public System.Drawing.Image scaleImg(System.Drawing.Image img, int xWith, int yHeight)
{
//計算處理後圖片寬
int i = Convert.ToInt32(img.Width * xWith / 100);
//計算處理後圖片高
int j = Convert.ToInt32(img.Height * yHeight / 100);
//格式化圖片
System.Drawing.Image imgScale = new System.Drawing.Bitmap(i, j, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(imgScale);
System.Drawing.Rectangle srcRect = new System.Drawing.Rectangle(0, 0, img.Width, img.Height);
System.Drawing.Rectangle desRect = new System.Drawing.Rectangle(0, 0, imgScale.Width, imgScale.Height);
g.Clear(System.Drawing.Color.White);
g.DrawImage(img, desRect, srcRect, System.Drawing.GraphicsUnit.Pixel);
//處理後的圖片另存
imgScale.Save("E:\\1111.jpg", System.Drawing.Imaging.ImageFormat.Gif);
g.Dispose();
return imgScale;
}
/// <summary>
/// bs用,按比例縮小圖片(高度按縮小按寬度的縮小比例縮小)原理直接控制控制項寬度
/// </summary>
/// <param name="ImageMap">介面顯示的Image</param>
/// <param name="ImagePath">圖片虛擬路徑</param>
/// <param name="WidthSize">圖片縮小後定下的寬度</param>
/// <param name="Server">本頁的Server</param>
public void ImageSize(System.Web.UI.WebControls.Image ImageMap, string ImagePath, int WidthSize, System.Web.HttpServerUtility Server)
{
System.Drawing.Image Img = System.Drawing.Image.FromFile(Server.MapPath(ImagePath));
int ImgWidth = Img.Width;
int ImgHeight = Img.Height;
ImageMap.ImageUrl = ImagePath;
if (ImgWidth > WidthSize)
{
ImageMap.Width = WidthSize;
ImageMap.Height = WidthSize * ImgHeight / ImgWidth;
}
}