主题: ASP.NET 上传图片自动压缩指定大小
作者: hmh, 发布日期: 2012-11-02 09:48:54, 浏览数: 7524

upload_json.ashx

 

一、加入以下代码:

 

   找到: imgFile.SaveAs(filePath);代码后加入
  
  //我加入的把图片缩小
  SmallPic(filePath, 650);  //650图片宽度

*******************************************************

 二、 并加入:(public class Upload : IHttpHandler 内部加入

     /**/
    /// <summary> 
    /// 按比例缩小图片,自动计算高度 
    /// </summary> 
    /// <param name="strOldPic">源图文件名(包括路径)</param> 
    /// <param name="strNewPic">缩小后保存为文件名(包括路径)</param> 
    /// <param name="intWidth">缩小至宽度</param> 
    public void SmallPic(string PicPath, int intWidth)
    {

        System.Drawing.Bitmap objPic, objNewPic;
        try
        {
            objPic = new System.Drawing.Bitmap(PicPath);
            if (objPic.Width > intWidth)
            {
                double tempbl = (double)objPic.Width / objPic.Height;
                int intHeight = Convert.ToInt32(Convert.ToDouble(intWidth) / tempbl);
                objNewPic = new System.Drawing.Bitmap(objPic, intWidth, intHeight);
                objPic.Dispose();
                //objNewPic.Save(PicPath);
                SaveAsJPEG(objNewPic, PicPath, 90);  //90图片压缩品质
                objNewPic.Dispose();
            }
            else {
                objPic.Dispose();
            }
        }
        catch (Exception exp) { throw exp; }
        finally
        {
            objPic = null;
            objNewPic = null;
        }
    }

 

    /// <summary>
    /// 保存为JPEG格式,支持压缩质量选项
    /// </summary>
    /// <param name="bmp"></param>
    /// <param name="FileName"></param>
    /// <param name="Qty"></param>
    /// <returns></returns>
    public static bool SaveAsJPEG(System.Drawing.Bitmap bmp, string FileName, int Qty)
    {
        try
        {
            System.Drawing.Imaging.EncoderParameter p;
            System.Drawing.Imaging.EncoderParameters ps;

            ps = new System.Drawing.Imaging.EncoderParameters(1);

            p = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, Qty);
            ps.Param[0] = p;

            bmp.Save(FileName, GetCodecInfo("image/jpeg"), ps);

            return true;
        }
        catch
        {
            return false;
        }

    }
    /// <summary>
    /// 保存JPG时用
    /// </summary>
    /// <param name="mimeType"></param>
    /// <returns>得到指定mimeType的ImageCodecInfo</returns>
    private static System.Drawing.Imaging.ImageCodecInfo GetCodecInfo(string mimeType)
    {
        System.Drawing.Imaging.ImageCodecInfo[] CodecInfo = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders();
        foreach (System.Drawing.Imaging.ImageCodecInfo ici in CodecInfo)
        {
            if (ici.MimeType == mimeType) return ici;
        }
        return null;
    }

 

发表新帖 发表回复