我现在只有点思想...也不知道是不是对的....具体的实施也不知道怎么打  io和gdi+用的不好
我现在想是否可以用 FileStream 读取本地图片 转换成image存储  再用gdi+ 里面的方法缩小
这个image  成120*120 然后再上传 saveAS服务器?   好像有个GetThumbnailImage也可以做缩略图   但是不怎么会用 MSDN上的参数也不知道要怎么写。
好像要用到委托....恳请高手指点下小弟。 具体应该怎么做。 

解决方案 »

  1.   

    如下代码有待验证
    private static string strConnect = System.Configuration.ConfigurationManager.AppSettings["connStr"];
        //上传图像
        protected void btnUpload_Click(object sender, EventArgs e)
        {
            ……
            string imgType;
            string fullFileName = this.txtPath.PostedFile.FileName;
            imgType = fullFileName.Substring(fullFileName.LastIndexOf(".") + 1).ToLower();
            string UserDirectory = Session["UserID"].ToString();//用户ID为所创建文件夹的名字
            string UserPath = Server.MapPath("UpLoad").ToString() + "\\" + UserDirectory;
            //如果文件夹不存在则创建
            if (!Directory.Exists(UserPath))
            {
                Directory.CreateDirectory(UserPath);
            }
            string originalImagePath = UserPath + "\\" + "Original";
            if(!Directory.Exists(originalImagePath))
            {
                Directory.CreateDirectory(originalImagePath);
            }
            string thumbnailPath = UserPath + "\\" + "Thumbnail";
            if (!Directory.Exists(thumbnailPath))
            {
                Directory.CreateDirectory(thumbnailPath);
            }        
            // 获取上传图像的文件名
            string fileName = txtName.Text;
            ……
                if (imgType=="jpg"||imgType=="jpeg"||imgType=="bmp"||imgType=="png"||imgType=="icon")
                {
                    try
                    { 
                        //生成原图
                        byte[] oFileByte = new byte[this.txtPath.PostedFile.ContentLength];
                        Stream oStream = this.txtPath.PostedFile.InputStream;
                        System.Drawing.Image oImage = System.Drawing.Image.FromStream(oStream);
                        int oWidth = oImage.Width;//原图宽度
                        int oHeight = oImage.Height;//原图高度
                        int tWidth = 100;//设置缩略图初始宽度
                        int tHeight = 100;//设置缩略图初始宽度                    //按比例计算出缩略图的宽度和高度
                        if (oWidth >= oHeight)
                        {
                            tHeight = (int)Math.Floor(Convert.ToDouble(oHeight) * (Convert.ToDouble(tWidth) / Convert.ToDouble(oHeight)));
                        }
                        else
                        {
                            tWidth = (int)Math.Floor(Convert.ToDouble(oWidth) * (Convert.ToDouble(tHeight) / Convert.ToDouble(oHeight)));
                        }
                        
                        //生成缩略图
                        Bitmap tImage = new Bitmap(tWidth,tHeight);
                        Graphics g = Graphics.FromImage(tImage);
                        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;//设置高质量插值法
                        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;//设置高质量,低速度呈现平滑程度
                        g.Clear(Color.Transparent);//清空画布并以透明背景色填充
                        g.DrawImage(oImage, new Rectangle(0, 0, tWidth, tHeight), new Rectangle(0, 0, oWidth, oHeight), GraphicsUnit.Pixel);
                                            
                        //this.txtPath.PostedFile.SaveAs(originalImagePath + "\\" + fileName + "." + imgType);
                        //string originalImageUrl = "UpLoad/" + UserDirectory + "/" + "Orginal/"+fileName + ".jpg" ;//得到服务端原图片的虚拟路径
                        // string thumbnailImageUrl = "UpLoad/" + UserDirectory + "/" + "Thumbnail/" + fileName + ".jpg";//得到服务端原图片的虚拟路径
                        //以JPG格式保存图像
                        //oImage.Save(originalImageUrl, System.Drawing.Imaging.ImageFormat.Jpeg);/*看看这里这两个保存方式有没有问题*/
                      //   tImage.Save(thumbnailImageUrl, System.Drawing.Imaging.ImageFormat.Jpeg);
                        string oPath = originalImagePath + "\\" + fileName + ".jpg";
                        string tPath = thumbnailPath + "\\" + fileName + ".jpg";
                        //以JPG格式保存图像
                        oImage.Save(oPath, System.Drawing.Imaging.ImageFormat.Jpeg);
                        tImage.Save(tPath, System.Drawing.Imaging.ImageFormat.Jpeg);
                        lblMessage.Visible = true;
                        lblMessage.Text = "图像上传成功!";
                        txtName.Text = "";
                        txtDescription.Text = "";
                        //释放资源                    
                        oImage.Dispose();
                        g.Dispose();
                        tImage.Dispose();
                    }
                    catch (Exception ex)
                    {
                        lblMessage.Visible = true;
                        lblMessage.Text = "由于网络原因,上载文件错误 " + ex.Message;
                    }
                }
                else
                {
                    Response.Write("<script language='javascript'>alert('你选择的图像格式错误!');</script>");
                    lblMessage.Visible = false;
                }
    }
      

  2.   

    搜下吧。有很多相关的资料。http://hi.baidu.com/jonesvale/blog/item/47ab801197909e08213f2e92.html
      

  3.   

    如下代码有待验证ToThumbnailImage.aspx<%@ Page language="c#" Codebehind="ToThumbnailImage.aspx.cs" Src="ToThumbnailImage.aspx.cs" AutoEventWireup="false" Inherits="Exam_C.ToThumbnailImage" %><html>  <head>    <title>Lion互动网络 =>生成缩略图</title>  </head>  <body>     <form id="Form1" method="post" runat="server">     </form>   </body></html> ToThumbnailImage.aspx.csusing System;using System.Collections;using System.ComponentModel;using System.Data;using System.Drawing;using System.Web;using System.Web.SessionState;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.HtmlControls;using System.Drawing.Imaging;namespace Exam_C{ /// <summary> /// ToThumbnailImage 的摘要说明。 /// </summary> public class ToThumbnailImage : System.Web.UI.Page {  /*    Create By lion    2003-05-20 19:00    Copyright (C) 2004 www.LionSky.Net. All rights reserved.   Web: http://www.Lionsky.net ;  Email: [email protected]   */    static Hashtable htmimes=new Hashtable();  internal readonly string AllowExt = ".jpe|.jpeg|.jpg|.png|.tif|.tiff|.bmp";    #region Web 窗体设计器生成的代码  override protected void OnInit(EventArgs e)  {   #region htmimes[".jpe"]="image/jpeg";   htmimes[".jpeg"]="image/jpeg";   htmimes[".jpg"]="image/jpeg";      htmimes[".png"]="image/png";      htmimes[".tif"]="image/tiff";   htmimes[".tiff"]="image/tiff";   htmimes[".bmp"]="image/bmp";   #endregion   //调用生成缩略图方法   ToThumbnailImages("lionsky.jpg","b.gif",300);  }    #endregion   #region Helper   /// <summary>  /// 获取图像编码解码器的所有相关信息  /// </summary>  /// <param name="mimeType">包含编码解码器的多用途网际邮件扩充协议 (MIME) 类型的字符串</param>  /// <returns>返回图像编码解码器的所有相关信息</returns>  static ImageCodecInfo GetCodecInfo(string mimeType)  {   ImageCodecInfo[] CodecInfo = ImageCodecInfo.GetImageEncoders();   foreach(ImageCodecInfo ici in CodecInfo)   {    if(ici.MimeType == mimeType)return ici;   }   return null;  }  /// <summary>  /// 检测扩展名的有效性  /// </summary>  /// <param name="sExt">文件名扩展名</param>  /// <returns>如果扩展名有效,返回true,否则返回false.</returns>  bool CheckValidExt(string sExt)  {      bool flag=false;   string[] aExt = AllowExt.Split('|');   foreach(string filetype in aExt)   {    if(filetype.ToLower()==sExt)    {     flag = true;     break;    }   }      return flag;  }  /// <summary>  /// 保存图片  /// </summary>  /// <param name="image">Image 对象</param>  /// <param name="savePath">保存路径</param>  /// <param name="ici">指定格式的编解码参数</param>  void SaveImage(System.Drawing.Image image,string savePath,ImageCodecInfo ici)  {   //设置 原图片 对象的 EncoderParameters 对象   EncoderParameters parameters = new EncoderParameters(1);   parameters.Param[0] = new EncoderParameter(Encoder.Quality, ((long) 90));   image.Save(savePath, ici, parameters);   parameters.Dispose();  }  #endregion  #region Methods  /// <summary>  /// 生成缩略图  /// </summary>  /// <param name="sourceImagePath">原图片路径(相对路径)</param>  /// <param name="thumbnailImagePath">生成的缩略图路径,如果为空则保存为原图片路径(相对路径)</param>  /// <param name="thumbnailImageWidth">缩略图的宽度(高度与按源图片比例自动生成)</param>  public void ToThumbnailImages(string sourceImagePath,string thumbnailImagePath,int thumbnailImageWidth)  {   string SourceImagePath = sourceImagePath;   string ThumbnailImagePath = thumbnailImagePath;   int ThumbnailImageWidth = thumbnailImageWidth;   string sExt = SourceImagePath.Substring(SourceImagePath.LastIndexOf(".")).ToLower();   if(SourceImagePath.ToString()==System.String.Empty) throw new NullReferenceException("SourceImagePath is null!");   if(!CheckValidExt(sExt))   {    throw new ArgumentException("原图片文件格式不正确,支持的格式有[ "+ AllowExt +" ]","SourceImagePath");   }   //从 原图片 创建 Image 对象   System.Drawing.Image image = System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath(SourceImagePath));     int num = ((ThumbnailImageWidth / 4) * 3);   int width = image.Width;   int height = image.Height;   //计算图片的比例   if ((((double) width) / ((double) height)) >= 1.3333333333333333f)   {    num = ((height * ThumbnailImageWidth) / width);   }   else   {    ThumbnailImageWidth = ((width * num) / height);   }   if ((ThumbnailImageWidth < 1) || (num < 1))   {    return;   }   //用指定的大小和格式初始化 Bitmap 类的新实例   Bitmap bitmap = new Bitmap(ThumbnailImageWidth, num, PixelFormat.Format32bppArgb);   //从指定的 Image 对象创建新 Graphics 对象   Graphics graphics = Graphics.FromImage(bitmap);   //清除整个绘图面并以透明背景色填充   graphics.Clear(Color.Transparent);   //在指定位置并且按指定大小绘制 原图片 对象   graphics.DrawImage(image, new Rectangle(0, 0, ThumbnailImageWidth, num));   image.Dispose();       try   {       //将此 原图片 以指定格式并用指定的编解码参数保存到指定文件     string savepath = (ThumbnailImagePath==null?SourceImagePath:ThumbnailImagePath);      SaveImage(bitmap,HttpContext.Current.Server.MapPath(savepath),GetCodecInfo((string)htmimes[sExt]));   }   catch(System.Exception e)   {    throw e;   }   finally   {    bitmap.Dispose();          graphics.Dispose();   }  }  #endregion }}
      

  4.   


       Bitmap myimage = new Bitmap("D:\\123.jpg");
            myimage.GetThumbnailImage(120, 120, null, IntPtr.Zero);
            //Graphics g = Graphics.FromImage(myimage);
            myimage.Save("E:\\123.gif", System.Drawing.Imaging.ImageFormat.Gif);
    为什么图片没缩小呢?   GetThumbnailImage(120, 120, null, IntPtr.Zero);
    不是已经制定120了么  为什么存入E盘的文件还是原来那么大呢?
      

  5.   

    新建一个bitmap是想要的大小。再循环取相应的象素。using System;
    using System.Drawing;
    using System.Collections;
    using System.ComponentModel;
    using System.Windows.Forms;
    using System.Data;namespace Image
    {
    /// <summary>
    /// Form1 的摘要说明。
    /// </summary>
    public class Form1 : System.Windows.Forms.Form
    {
    private System.Windows.Forms.Button button1;
    private System.Windows.Forms.OpenFileDialog openFileDialog1;
    /// <summary>
    /// 必需的设计器变量。
    /// </summary>
    private System.ComponentModel.Container components = null;
    private System.Windows.Forms.Button button2;
    private System.Windows.Forms.NumericUpDown numericUpDown1;
    private System.Windows.Forms.Label label1;
    private System.Windows.Forms.Label label2;
    private System.Windows.Forms.NumericUpDown numericUpDown2;
    private System.String StrFileName="";
    public Form1()
    {
    //
    // Windows 窗体设计器支持所必需的
    //
    InitializeComponent(); //
    // TODO: 在 InitializeComponent 调用后添加任何构造函数代码
    //
    } /// <summary>
    /// 清理所有正在使用的资源。
    /// </summary>
    protected override void Dispose( bool disposing )
    {
    if( disposing )
    {
    if (components != null) 
    {
    components.Dispose();
    }
    }
    base.Dispose( disposing );
    } #region Windows 窗体设计器生成的代码
    /// <summary>
    /// 设计器支持所需的方法 - 不要使用代码编辑器修改
    /// 此方法的内容。
    /// </summary>
    private void InitializeComponent()
    {
    this.button1 = new System.Windows.Forms.Button();
    this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
    this.button2 = new System.Windows.Forms.Button();
    this.numericUpDown1 = new System.Windows.Forms.NumericUpDown();
    this.label1 = new System.Windows.Forms.Label();
    this.label2 = new System.Windows.Forms.Label();
    this.numericUpDown2 = new System.Windows.Forms.NumericUpDown();
    ((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).BeginInit();
    ((System.ComponentModel.ISupportInitialize)(this.numericUpDown2)).BeginInit();
    this.SuspendLayout();
    // 
    // button1
    // 
    this.button1.Location = new System.Drawing.Point(24, 208);
    this.button1.Name = "button1";
    this.button1.Size = new System.Drawing.Size(80, 23);
    this.button1.TabIndex = 0;
    this.button1.Text = "浏览图像";
    this.button1.Click += new System.EventHandler(this.button1_Click);
    // 
    // openFileDialog1
    // 
    this.openFileDialog1.Filter = "Image files (JPeg, Gif, Bmp, etc.)|*.jpg;*.jpeg;*.gif;*.bmp;*.tif; *.tiff; *.png|" +
    " JPeg files (*.jpg;*.jpeg)|*.jpg;*.jpeg |GIF files (*.gif)|*.gif |BMP files (*.b" +
    "mp)|*.bmp|Tiff files (*.tif;*.tiff)|*.tif;*.tiff|Png files (*.png)| *.png |All f" +
    "iles (*.*)|*.*";
    // 
    // button2
    // 
    this.button2.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
    this.button2.Location = new System.Drawing.Point(8, 8);
    this.button2.Name = "button2";
    this.button2.Size = new System.Drawing.Size(360, 192);
    this.button2.TabIndex = 1;
    this.button2.Paint += new System.Windows.Forms.PaintEventHandler(this.button2_Paint);
    // 
    // numericUpDown1
    // 
    this.numericUpDown1.Location = new System.Drawing.Point(184, 208);
    this.numericUpDown1.Minimum = new System.Decimal(new int[] {
       1,
       0,
       0,
       0});
    this.numericUpDown1.Name = "numericUpDown1";
    this.numericUpDown1.Size = new System.Drawing.Size(40, 21);
    this.numericUpDown1.TabIndex = 2;
    this.numericUpDown1.Value = new System.Decimal(new int[] {
     5,
     0,
     0,
     0});
    this.numericUpDown1.ValueChanged += new System.EventHandler(this.numericUpDown1_ValueChanged);
    // 
    // label1
    // 
    this.label1.Location = new System.Drawing.Point(112, 212);
    this.label1.Name = "label1";
    this.label1.Size = new System.Drawing.Size(72, 16);
    this.label1.TabIndex = 3;
    this.label1.Text = "X方向缩放:";
    // 
    // label2
    // 
    this.label2.Location = new System.Drawing.Point(232, 212);
    this.label2.Name = "label2";
    this.label2.Size = new System.Drawing.Size(72, 16);
    this.label2.TabIndex = 5;
    this.label2.Text = "Y方向缩放:";
    // 
    // numericUpDown2
    // 
    this.numericUpDown2.Location = new System.Drawing.Point(304, 208);
    this.numericUpDown2.Minimum = new System.Decimal(new int[] {
       1,
       0,
       0,
       0});
    this.numericUpDown2.Name = "numericUpDown2";
    this.numericUpDown2.Size = new System.Drawing.Size(48, 21);
    this.numericUpDown2.TabIndex = 4;
    this.numericUpDown2.Value = new System.Decimal(new int[] {
     5,
     0,
     0,
     0});
    this.numericUpDown2.ValueChanged += new System.EventHandler(this.numericUpDown2_ValueChanged);
    // 
    // Form1
    // 
    this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
    this.ClientSize = new System.Drawing.Size(376, 238);
    this.Controls.Add(this.label2);
    this.Controls.Add(this.numericUpDown2);
    this.Controls.Add(this.label1);
    this.Controls.Add(this.numericUpDown1);
    this.Controls.Add(this.button2);
    this.Controls.Add(this.button1);
    this.MaximizeBox = false;
    this.Name = "Form1";
    this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
    this.Text = "演示以任意比例缩放显示图像";
    ((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).EndInit();
    ((System.ComponentModel.ISupportInitialize)(this.numericUpDown2)).EndInit();
    this.ResumeLayout(false); }
    #endregion /// <summary>
    /// 应用程序的主入口点。
    /// </summary>
    [STAThread]
    static void Main() 
    {
    Application.Run(new Form1());
    }
    private void button1_Click(object sender, System.EventArgs e)
    {//浏览图像
               this.openFileDialog1.ShowDialog();
       this.StrFileName=this.openFileDialog1.FileName;
       this.button2.Refresh();
    }
    private void button2_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
    {//以任意比例缩放显示图像
    if(this.StrFileName.Trim()=="")
    return;
    System.Drawing.Bitmap MyBitmap=new Bitmap(this.StrFileName);
    Graphics g = e.Graphics;
    TextureBrush MyBrush = new TextureBrush(MyBitmap);
    float fx=(float)(this.numericUpDown1.Value/10);
    float fy=(float)(this.numericUpDown2.Value/10);
    g.ScaleTransform(fx,fy);
    //MyBrush.ScaleTransform(fx,fy);
    g.FillRectangle(MyBrush,0,0,this.ClientRectangle.Width,this.ClientRectangle.Height);
    } private void numericUpDown1_ValueChanged(object sender, System.EventArgs e)
    {//更新图像显示
    this.button2.Refresh();
    } private void numericUpDown2_ValueChanged(object sender, System.EventArgs e)
    {//更新图像显示
       this.button2.Refresh();
    }

    }
    }
      

  6.   

    public bool ResizeImg(string ImgFile, string sImgPath, int ResizeWidth, int ResizeHeight, string BgColor)
        {
            try
            {
                FileStream fs = new FileStream(ImgFile, FileMode.Open);
                BinaryReader br = new BinaryReader(fs);
                byte[] bytes = br.ReadBytes((int)fs.Length);
                br.Close();
                fs.Close();
                MemoryStream ms = new MemoryStream(bytes);            System.Drawing.Image imgPhoto = System.Drawing.Image.FromStream(ms);
                int imgPhotoWidth = imgPhoto.Width;
                int imgPhotoHeight = imgPhoto.Height;
                int StartX = 0;
                int StartY = 0;
                int NewWidth = imgPhotoWidth;
                int NewHeight = imgPhotoHeight;
                if (NewWidth > ResizeWidth)
                {
                    NewWidth = ResizeWidth;
                    NewHeight = Convert.ToInt32(imgPhotoHeight * Math.Round(Convert.ToDecimal(NewWidth) / Convert.ToDecimal(imgPhotoWidth), 10));
                }            if (NewHeight > ResizeHeight)
                {
                    NewHeight = ResizeHeight;
                    NewWidth = Convert.ToInt32(imgPhotoWidth * Math.Round(Convert.ToDecimal(NewHeight) / Convert.ToDecimal(imgPhotoHeight), 10));
                }            StartX = ResizeWidth - NewWidth;
                StartY = ResizeHeight - NewHeight;            StartX = StartX > 0 ? StartX / 2 : 0;
                StartY = StartY > 0 ? StartY / 2 : 0;            Bitmap bmPhoto = new Bitmap(ResizeWidth, ResizeHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                bmPhoto.SetResolution(72, 72);
                Graphics gbmPhoto = Graphics.FromImage(bmPhoto);
                gbmPhoto.Clear(Color.FromName(BgColor));
                gbmPhoto.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                gbmPhoto.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;            gbmPhoto.DrawImage(imgPhoto, new Rectangle(StartX, StartY, NewWidth, NewHeight), new Rectangle(0, 0, imgPhotoWidth, imgPhotoHeight), GraphicsUnit.Pixel);
                bmPhoto.Save(sImgPath, System.Drawing.Imaging.ImageFormat.Jpeg);            imgPhoto.Dispose();
                gbmPhoto.Dispose();
                bmPhoto.Dispose();            return true;
            }
            catch (Exception err)
            {
                return false;
            }
        }
    public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode)
            {
                System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath);
                int towidth = width;
                int toheight = height;
                int x = 0;
                int y = 0;
                int ow = originalImage.Width;
                int oh = originalImage.Height;
                switch (mode)
                {
                    case "HW":               
                        break;
                    case "W":                  
                        toheight = originalImage.Height * width / originalImage.Width;
                        break;
                    case "H":
                        towidth = originalImage.Width * height / originalImage.Height;
                        break;
                    case "Cut":              
                     if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                        {
                            oh = originalImage.Height;
                           ow = originalImage.Height * towidth / toheight;
                            y = 0;
                            x = (originalImage.Width - ow) / 2;
                        }
                        else
                        {
                            ow = originalImage.Width;
                            oh = originalImage.Width * height / towidth;
                            x = 0;
                            y = (originalImage.Height - oh) / 2;
                        }
                       break;
                    default:
                        break;
                }
               System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);
                System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                g.Clear(System.Drawing.Color.Transparent);
         g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight),
                    new System.Drawing.Rectangle(x, y, ow, oh),
                    System.Drawing.GraphicsUnit.Pixel);
                try
                {
                    bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
                }
                catch (System.Exception e)
                {
                    throw e;
                }
                finally
                {
                    originalImage.Dispose();
                    bitmap.Dispose();
                    g.Dispose();
                }        }
      

  7.   

    System.Drawing.Image image;
    image = CommonCreateThumbnailImage.CreateThumbnailImage(图片宽, 高, 路径, null, true, CommonCreateThumbnailImage.ImageMode.HW);
    image.Save(路径, System.Drawing.Imaging.ImageFormat.Jpeg);