首页 > 编程 > .NET > 正文

ASP.NET 生成高质量缩略图代码

2024-07-10 12:55:06
字体:
来源:转载
供稿:网友
  • 网站运营seo文章大全
  • 提供全面的站长运营经验及seo技术!
  •  private static size newsize(int maxwidth, int maxheight, int width, int height)
      {
       double w = 0.0;
       double h = 0.0;
       double sw = convert.todouble(width);
       double sh = convert.todouble(height);
       double mw = convert.todouble(maxwidth);
       double mh = convert.todouble(maxheight);

       if ( sw < mw && sh < mh )
       {
        w = sw;
        h = sh;
       }
       else if ( (sw/sh) > (mw/mh) )
       {
        w = maxwidth;
        h = (w * sh)/sw;
       }
       else
       {
        h = maxheight;
        w = (h * sw)/sh;
       }

       return new size(convert.toint32(w), convert.toint32(h));
      }

      public static void sendsmallimage(string filename, string newfile, int maxheight, int maxwidth)
      {
       system.drawing.image img = system.drawing.image.fromfile(filename);
       system.drawing.imaging.imageformat thisformat = img.rawformat;

       size newsize = newsize(maxwidth, maxheight, img.width, img.height);
       bitmap outbmp = new bitmap(newsize.width, newsize.height);
       graphics g = graphics.fromimage(outbmp);

       // 设置画布的描绘质量
       g.compositingquality = compositingquality.highquality;
       g.smoothingmode = smoothingmode.highquality;
       g.interpolationmode = interpolationmode.highqualitybicubic;

       g.drawimage(img, new rectangle(0, 0, newsize.width, newsize.height),
        0, 0, img.width, img.height, graphicsunit.pixel);
       g.dispose();

       // 以下代码为保存图片时,设置压缩质量
       encoderparameters encoderparams = new encoderparameters();
       long[] quality = new long[1];
       quality[0] = 100;

       encoderparameter encoderparam = new encoderparameter(system.drawing.imaging.encoder.quality, quality);
       encoderparams.param[0] = encoderparam;

       //获得包含有关内置图像编码解码器的信息的imagecodecinfo 对象。
       imagecodecinfo[] arrayici = imagecodecinfo.getimageencoders();
       imagecodecinfo jpegici = null;
       for (int x = 0; x < arrayici.length; x++)
       {
        if (arrayici[x].formatdescription.equals("jpeg"))
        {
         jpegici = arrayici[x];//设置jpeg编码
         break;
        }
       }

       if (jpegici != null)
       {
        outbmp.save(newfile, jpegici, encoderparams);
       }
       else
       {
        outbmp.save(newfile, thisformat);
       }
               
       img.dispose();
       outbmp.dispose();
      }

    发表评论 共有条评论
    用户名: 密码:
    验证码: 匿名发表