图片上传|图片按比例缩放

今天做的一个小模块中,跟图片有关:

首先:生成缩略图,再上传到服务器.

以前做了一个图片上传的,但是他不是按比例缩放的.只需要在中间加一段判断长和宽.就可以了.还是看看代码吧.

 

// 定义image类的对象
    System.Drawing.Image image;
    System.Drawing.Image newimage;
    
// 图片路径
     protected   string  imagePath;
    
// 图片类型
     protected   string  imageType;
    
// 图片名称
     protected   string  imageName;
    
// 提供一个回调方法,用于确定Image对象在执行生成缩略图操作时提前取消执行
    
// 如果此方法确定GetThumbnailImage方法应提前停止执行,则返回true;否则返回false
    System.Drawing.Image.GetThumbnailImageAbort callb  =   null ;
    
protected   void  Button1_Click( object  sender, EventArgs e)
    
{
        
string mPath;
        
//如果文件名称不为空
        if (FileUpload1.PostedFile.FileName != "")
        
{
            imagePath 
= FileUpload1.PostedFile.FileName;
            
//取得图片类型
            imageType = imagePath.Substring(imagePath.LastIndexOf("."+ 1).ToLower().ToString();
            
//取得图片名称
            imageName = imagePath.Substring(imagePath.LastIndexOf("/"+ 1);
            
//判断是否是jpg/gif/jpeg/jpe类型图片
            if (imageType != "jpg" && imageType != "gif" && imageType != "jpeg" && imageType != "jpe")
            
{
                ConfirmMessageBox(
"对不起,请选择:jpg|jpeg|jpe|gif中的任意一种格式!");
            }

            
else
            
{
                
//判断图片是否大于120K[120 * 1024]
                if (FileUpload1.PostedFile.ContentLength > 122880)
                
{
                    Label2.Text 
= "对不起,文件不得大于120K(122880个字节)!";
                }

                
else
                
{
                    
try
                    
{
                        
//建立虚拟路径
                        mPath = Server.MapPath("productImages");
                        
//保存图片到虚拟路径
                        imageName = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + "." + imageType;
                        HiddenField1.Value 
= imageName;
                        FileUpload1.PostedFile.SaveAs(mPath 
+ "/" + imageName);

                        
//显示原图
                        
//Image1.ImageUrl = "productImages/" + imageName;

                        
//为上传图片建立引用
                        image = System.Drawing.Image.FromFile(mPath + "/" + imageName);
                        
//==============================================================
                        
//加入判断长宽的比例代码 >> Begin
                        
//==============================================================
                        
//生成原图
                        Byte[] oFileByte = new Byte[FileUpload1.PostedFile.ContentLength];
                        Stream oStream 
= FileUpload1.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)
                        
{
                            tWidth 
= (int)Math.Floor(Convert.ToDouble(oHeight) * (Convert.ToDouble(tWidth) / Convert.ToDouble(oWidth)));
                        }

                        
else
                        
{
                            tHeight 
= (int)Math.Floor(Convert.ToDouble(oWidth) * (Convert.ToDouble(tHeight) / Convert.ToDouble(oHeight)));
                        }


                        
//==============================================================
                        
//判断长宽的比例代码 >> Over
                        
//==============================================================

                        
///生成缩略图
                        newimage = image.GetThumbnailImage(tHeight, tWidth, callb, System.IntPtr.Zero);
                        
//把缩略图保存到指定的虚拟路径
                        newimage.Save(Server.MapPath("productImages"+ "/small" + imageName);
                        
//释放image对象占用的资源
                        image.Dispose();
                        
//释放newimage占用的资源
                        newimage.Dispose();
                        
//显示缩略图
                        Image1.ImageUrl = "productImages/small" + imageName;
                        Label2.Text 
= "上传成功!";
                    }

                    
catch
                    
{
                        Label2.Text 
= "上传失败!";
                    }

                }

            }

        }

        
else
        
{
            Label2.Text 
= "不能为空,请选择图片!";
        }

    }

 那么显示的时候长宽最大为100.

如果在一个页面需要显示长宽最大为150,怎么办呢?刚刚开始我想从服务器端得到图片的大小.但是他需要的是绝对中路径.

用那种方法只能得到客户端的图片大小.代码如下:

 

private   void  btnGet_Click( object  sender, System.EventArgs e)
        
{
            
if(upImage.PostedFile.FileName != "")
            
{
                imgPath 
=upImage.PostedFile.FileName;
                fileExtName 
= imgPath.Substring(imgPath.LastIndexOf(".")+1,3);

                
if(fileExtName !="gif" && fileExtName != "jpg")
                
{
                    Response.Write(
"请选择GIF和JPG格式的图片");
                }

                
else
                
{
//获取图片大小
                    System.Drawing.Image image =  System.Drawing.Image.FromFile(imgPath);
                    txtHeight.Text 
= image.Height.ToString();
                    txtWidth.Text 
= image.Width.ToString();
                }

            }

            
else
            
{
                Response.Write(
"请选择图片!");
            }

        }

没有办法,只好在显示到客户端时用onLoad事件来完成对图片大小的改造了.

此方法参考Winner.Net@2007图片超过规定的大小就按原图片大小缩小

1,不按照比例的缩放 

 

< script language = " javascript " >   
function  changeImg(mypic) {  
    alert(
"OK");
    
var xw=130;  
    
var xl=160;  

    
var width = mypic.width;  
    
var height = mypic.height;  
                      
    
if (width > xw ) mypic.width = xw;  
    
if (height > xl ) mypic.height = xl;  
}
  
</ script >   
< img src = " sh180.jpg "  onload = " changeImg(this) " >      

2,按照比例的缩放 

 

< script language = " javascript " >   
function  changeImg1(mypic) {  

alert(
"OK");
    
var xw=160;  
    
var xl=180;  
          
    
var width = mypic.width;  
    
var height = mypic.height;  
    
var bili = width/height;          
          
    
var A=xw/width;  
    
var B=xl/height;  
          
    
if(A>1||B>1)  
    
{  
        
if(A<B)  
        
{  
            mypic.width
=xw;  
            mypic.height
=xw/bili;  
        }
  
        
if(A>B)  
        
{  
            mypic.width
=xl*bili;  
            mypic.height
=xl;  
        }
  
    }
  
}
  
</ script >   

哪位高手如果知道怎么得到服务器端图片的大小,请不吝赐教.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在ASP.NET中上传图片并生成缩略图的C#源码 <FONT size=4><FONT size=4><FONT size=4>using 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.IO; using System.Drawing.Imaging; namespace eMeng.Exam { /// <summary> /// Thumbnail 的摘要说明。 /// </summary> public class Thumbnail : System.Web.UI.Page { protected System.Web.UI.WebControls.Label Label1; protected System.Web.UI.WebControls.Button Button1; private void Page_Load(object sender, System.EventArgs e) { // 在此处放置用户代码以初始化页面 Label1.Text = "<h3>在ASP.NET里轻松实炙趼酝?lt;/h3>"; Button1.Text = "上载并显示缩略图"; } #region Web 窗体设计器生成的代码 override protected void OnInit(EventArgs e) { // // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。 // InitializeComponent(); base.OnInit(e); } /// <summary> /// 设计器支持所需的方法 - 不要使用代码编辑器修改 /// 此方法的内容。 /// </summary> private void InitializeComponent() { this.Button1.Click += new System.EventHandler(this.Button1_Click); this.Load += new System.EventHandler(this.Page_Load); } #endregion private void Button1_Click(object sender, System.EventArgs e) { HttpFileCollection MyFileColl = HttpContext.Current.Request.Files; HttpPostedFile MyPostedFile = MyFileColl[0]; if (MyPostedFile.ContentType.ToString().ToLower().IndexOf("image") < 0) { Response.Write("无效的图形格式。"); return; } GetThumbNail(MyPostedFile.FileName, 100, 100, MyPostedFile.ContentType.ToString(), false, MyPostedFile.InputStream); } private System.Drawing.Imaging.ImageFormat GetImageType(object strContentType) { if ((strContentType.ToString().ToLower()) == "image/pjpeg") { return System.Drawing.Imaging.ImageFormat.Jpeg; } else if ((strContentType.ToString().ToLower()) == "image/gif") { return System.Drawing.Imaging.ImageFormat.Gif; } else if ((strContentType.ToString().ToLower()) == "image/bmp") { return System.Drawing.Imaging.ImageFormat.Bmp; } else if ((strContentType.ToString().ToLower()) == "image/tiff") { return System.Drawing.Imaging.ImageFormat.Tiff; } else if ((strContentType.ToString().ToLower()) == "image/x-icon") { return System.Drawing.Imaging.ImageFormat.Icon; } else if ((strContentType.ToString().ToLower()) == "image/x-png") { return System.Drawing.Imaging.ImageFormat.Png; } else if ((strContentType.ToString().ToLower()) == "image/x-emf") { return System.Drawing.Imaging.ImageFormat.Emf; } else if ((strContentType.ToString().ToLower()) == "image/x-exif") { return System.Drawing.Imaging.ImageFormat.Exif; } else if ((strContentType.ToString().ToLower()) == "image/x-wmf") { return System.Drawing.Imaging.ImageFormat.Wmf; } else { return System.Drawing.Imaging.ImageFormat.MemoryBmp; } } private void GetThumbNail(string strFileName, int iWidth, int iheight, string strContentType, bool blnGetFromFile, System.IO.Stream ImgStream) { System.Drawing.Image oImg; if (blnGetFromFile) { oImg = System.Drawing.Image.FromFile(strFileName); } else { oImg = System.Drawing.Image.FromStream(ImgStream); } oImg = oImg.GetThumbnailImage(iWidth, iheight, null, IntPtr.Zero); string strGuid = System.Guid.NewGuid().ToString().ToUpper(); string strFileExt = strFileName.Substring(strFileName.LastIndexOf(".")); Response.ContentType = strContentType; MemoryStream MemStream = new MemoryStream(); oImg.Save(MemStream, GetImageType(strContentType)); MemStream.WriteTo(Response.OutputStream); } } } </FONT></FONT></FONT><FONT color=#ff0000 size=4></FONT><FONT size=4>功能: 1。把图片文件(JPG GIF PNG)上传, 2。保存到指定的路径(在web.config中设置路径,以文件的原有格式保存), 3。并自动生成指定宽度的(在web.config中设置宽度) 4。和指定格式的(在web.config中指定缩略图的格式) 5。和原图比例相同的缩略图(根据宽度和原图的宽和高计算所略图的高度) 6。可以判断是否已经存在文件 7。如果不覆盖,则给出错误 8。如果选中"覆盖原图"checkbox,则覆盖原图。 9。可以根据要求,在webform上设置1个以上的file input和相应的checkbox 10。并在文件上传完毕后,显示原图的文件名,尺寸,字节,和 11。缩略图的文件名尺寸。 12。缩略图的文件名格式:原图+"_thumb."+指定格式,如:test.jpg_thumb.gif,以便于管理。 -------------------- public void UploadFile(object sender, System.EventArgs e) { string imgNameOnly, imgNameNoExt, imgExt; string imgThumbnail; int erroNumber = 0; System.Drawing.Image oriImg, newImg; string strFePicSavePath = ConfigurationSettings.AppSettings["FePicSavePath"].ToString(); string strFePicThumbFormat = ConfigurationSettings.AppSettings["FePicThumbFormat"].ToString().ToLower(); int intFeThumbWidth = Int32.Parse(ConfigurationSettings.AppSettings["FePicThumbWidth"]); string fileExt; StringBuilder picInfo = new StringBuilder(); if(Page.IsValid) { for(int i = 0;i < Request.Files.Count; i++) { HttpPostedFile PostedFile = Request.Files[i]; fileExt = (System.IO.Path.GetExtension(PostedFile.FileName)).ToString().ToLower(); imgNameOnly = System.IO.Path.GetFileName(PostedFile.FileName); if(fileExt == ".jpg" || fileExt == ".gif" || fileExt == ".png") { if(System.IO.File.Exists(strFePicSavePath + imgNameOnly) && (checkboxlistRewrite.Items[i].Selected == false)) { erroNumber = erroNumber + 1; picInfo.Append("<b>错误:</b>文件("+ (i+1) +") " + imgNameOnly + " 已经存在,请修改文件名<br/>" ); } } else { erroNumber = erroNumber + 1; picInfo.Append("<b>错误:</b>文件("+ (i+1) +") " + imgNameOnly + " 扩展名 " + fileExt + " 不被许可<br/>" ); } } if(erroNumber > 0) { picInfo.Append("<font color=red>全部操作均未完成,请修改错误,再进行操作</font><br/>"); } else { for(int i = 0;i < Request.Files.Count; i++) { HttpPostedFile PostedFile = Request.Files[i]; imgNameOnly = System.IO.Path.GetFileName(PostedFile.FileName); imgNameNoExt = System.IO.Path.GetFileNameWithoutExtension(PostedFile.FileName); imgExt = System.IO.Path.GetExtension(PostedFile.FileName).ToString().ToLower(); oriImg = System.Drawing.Image.FromStream(PostedFile.InputStream); newImg = oriImg.GetThumbnailImage(intFeThumbWidth, intFeThumbWidth * oriImg.Height/oriImg.Width,null,new System.IntPtr(0)); switch(imgExt) { //case ".jpeg": case ".jpg": oriImg.Save(strFePicSavePath + imgNameOnly , System.Drawing.Imaging.ImageFormat.Jpeg); break; case ".gif": oriImg.Save(strFePicSavePath + imgNameOnly , System.Drawing.Imaging.ImageFormat.Gif); break; case ".png": oriImg.Save(strFePicSavePath + imgNameOnly , System.Drawing.Imaging.ImageFormat.Png); break; } //oriImg.Save(ConfigurationSettings.AppSettings["FePicSavePath"] + imgNameNoExt + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg); switch(strFePicThumbFormat) { //jpeg format can get the smallest file size, and the png is the largest size //case "jpeg": case "jpg": newImg.Save(strFePicSavePath + imgNameOnly + "_thumb.jpg",System.Drawing.Imaging.ImageFormat.Jpeg); imgThumbnail = imgNameOnly + "_thumb.jpg"; break; case "gif": newImg.Save(strFePicSavePath + imgNameOnly + "_thumb.gif",System.Drawing.Imaging.ImageFormat.Gif); imgThumbnail = imgNameOnly + "_thumb.gif"; break; case "png": newImg.Save(strFePicSavePath + imgNameOnly + "_thumb.png",System.Drawing.Imaging.ImageFormat.Png); imgThumbnail = imgNameOnly + "_thumb.png"; break; default: newImg.Save(strFePicSavePath + imgNameOnly + "_thumb.jpg",System.Drawing.Imaging.ImageFormat.Jpeg); imgThumbnail = imgNameOnly + "_thumb.jpg"; break; }//switch picInfo.Append("<b>文件 名:</b>" + imgNameOnly + " ( " + oriImg.Width + " x " + oriImg.Height + " ) " + PostedFile.ContentLength/1024 + "KB<br/>"); picInfo.Append("<b>缩略图名:</b>" + imgThumbnail + " ( " + newImg.Width + " x " + newImg.Height + " )<br/><br/>"); oriImg.Dispose(); newImg.Dispose(); }//for picInfo.Append("<font color=red>所有操作成功</font><br/>"); }// if erronumber = 0 } else { picInfo.Append("<font color=red>有错误,请检查。操作未成功</font><br/>"); } lblPicInfo.Text = picInfo.ToString(); } </FONT> 资料引用:http://www.knowsky.com/5723.html

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值