图片等比例缩放方法....(加两个走过的弯路)

Posted on 2006-06-27 14:31  fgp3  阅读(443)  评论(2)    收藏  举报
public class SmallPic
{
    //************************************************************//
    //图片缩放
    //************************************************************//
    public SmallPic() { }
    public string zoom(string strOldPic, int intSize)
    {
        int intWidth = 100, intHeight = 100;
        string strNewPic, strNewFileName;
        System.Drawing.Bitmap objPic;
        //取时间作为方件名
        DateTime thetime = DateTime.Now;
        strNewPic = thetime.Year.ToString() + thetime.Month.ToString() + thetime.Day.ToString();
        strNewPic += thetime.Hour.ToString() + thetime.Minute.ToString() + thetime.Second.ToString() + thetime.Millisecond.ToString();
        //再加个随机数做文件名
        Random therand = new Random();
        strNewPic += therand.Next(1, 1000).ToString();
        strNewFileName = "images/title/" + strNewPic + ".gif";
        //STRNEWPIC 实际地址
        strNewPic = "~/flyxnews/" + strNewFileName;
        strNewPic = HttpContext.Current.Server.MapPath(strNewPic);
        //出错图片
        string errurl = "images/err.gif";
        //
        char x = strOldPic[0];
        if (x.ToString() == "h")
        {
            try
            {
                WebRequest wr = WebRequest.Create(strOldPic);
                WebResponse res = wr.GetResponse();
                objPic = new System.Drawing.Bitmap(res.GetResponseStream());
            }
            catch
            {
                return errurl;
            }
        }
        else
        {
            return errurl;
        }

        if (intSize == 0) { intSize = 100; }
        Single singleWidth = Convert.ToSingle(objPic.Width);
        Single singleHeight = Convert.ToSingle(objPic.Height);
        Single k = singleWidth / singleHeight;
        if (Convert.ToInt32(k) > 1)
        {
            singleWidth = intSize;
            singleHeight = intSize/k;
        }
        else
        {
            singleWidth = k * intSize;
            singleHeight = intSize;
        }
        intWidth = Convert.ToInt32(singleWidth);
        intHeight = Convert.ToInt32(singleHeight);
        System.Drawing.Bitmap objNewPic = new System.Drawing.Bitmap(objPic, intWidth, intHeight);
        objNewPic.Save(strNewPic, System.Drawing.Imaging.ImageFormat.Png);
        objPic.Dispose();
        objNewPic.Dispose();
        return strNewFileName;
    }
}

博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3