主题: net版上传图片自动缩放
作者: 勿闻轩外香, 发布日期: 2013-11-27 15:13:30, 浏览数: 2405

今天试着改了一下上传图片后自动缩放的问题,自动缩放搞定了,但是还有一个图片在编辑器里面拖放的功能没法解决。图片在编辑器里面,一拖可以拖好大。这个问题留给老大及后来人吧。当然,如果目前有人能解决这个图片拖放问题,希望能告诉我一下。


自动缩放很简单,估计很多人也都会,下面例子仅供新手参考,学习吧

我今天研究了两种模式,一个是给upload_json.ashx传参,取要缩放的宽高;一个是无参数,直接缩放。我使用了第二个。


传参方法,只要使用upload_json.ashx?w=?&h=?这种URL方式即可,在upload_json.ashx页面用context.Request.QueryString["width"]接收参数;


缩放相对简单

System.IO.Stream oStream = imgFile.InputStream;
System.Drawing.Image oImage = System.Drawing.Image.FromStream(oStream);
 if (oImage.Width > 680)
{//取图片宽度,判断是否执行缩放
     CreatImage.TouXiangSuoFang(imgFile, newFileName, dirPath, 680, 680);//自己写的一个缩放类
}else

{

     imgFile.SaveAs(filePath);

}


------------------------------------------缩放类,也不知道这个缩放方法及公式好不好。-------------------------------


public static string TouXiangSuoFang(HttpPostedFile UploadFile, string imageName, string imagemath, int width, int height)
    {
        //生成原图 
        Byte[] oFileByte = new byte[UploadFile.ContentLength];
        System.IO.Stream oStream = UploadFile.InputStream;
        System.Drawing.Image oImage = System.Drawing.Image.FromStream(oStream);

        int oWidth = oImage.Width; //原图宽度 
        int oHeight = oImage.Height; //原图高度 
        int tWidth = width; //设置缩略图初始宽度 
        int tHeight = height; //设置缩略图初始高度 

        //按比例计算出缩略图的宽度和高度 
        if (oWidth >= oHeight)
        {
            tHeight = (int)Math.Floor(Convert.ToDouble(oHeight) * (Convert.ToDouble(tWidth) / Convert.ToDouble(oWidth)));
        }
        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);

        try
        {
            //以JPG格式保存图片 
            tImage.Save(imagemath + imageName, System.Drawing.Imaging.ImageFormat.Jpeg);
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            //释放资源 
            oImage.Dispose();
            g.Dispose();
            tImage.Dispose();
        }
        return imageName;
    }
发表新帖 发表回复