zoukankan      html  css  js  c++  java
  • 通过一般处理程序生成缩略图

    创建一个一般处理程序smallImg.ashx
    要显示图片的时候直接把img标签的src指向smallImg.ashx就行了,后面可以加上要传的参数。

    smallImg.ashx代码如下:

     1 <%@ WebHandler Language="C#" Class="SmallImg" %>
    2
    3 using System;
    4 using System.Web;
    5 using System.Drawing;
    6 public class ImgSmall : IHttpHandler {
    7
    8 //生成图片缩略图
    9 public void ProcessRequest (HttpContext context) {
    10 context.Response.ContentType = "image/jpeg";
    11 //url传来的图片名称
    12 string img = context.Request.QueryString["img"];
    13
    14 if (!string.IsNullOrEmpty(img))
    15 {
    16 //获取图片的物理路径
    17 string path = context.Request.MapPath("images/" + img);
    18 //加载大图
    19 Image big = Image.FromFile(path);
    20
    21 float oldWidth = big.Width;
    22 float oldHeight = big.Height;
    23 float newWidth = 150;
    24 float newHeight = 100;
    25 //保持横纵比例
    26 if (oldWidth / oldHeight > newWidth / newHeight) //宽了,就要以宽为准
    27 {
    28 newHeight = newWidth * oldHeight / oldWidth;
    29 }
    30 else
    31 {
    32 newWidth = newHeight * oldWidth / oldHeight;//高了,就要以高为准
    33 }
    34
    35
    36 //生成小图
    37 Bitmap bitmap = new Bitmap((int)newWidth,(int)newHeight);
    38
    39 Graphics g = Graphics.FromImage(bitmap);
    40 //把大图 画到小图上
    41 g.DrawImage(big, 0, 0, bitmap.Width, bitmap.Height);
    42 //释放资源
    43 g.Dispose();
    44
    45 //把bitmap输出到浏览器
    46 bitmap.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
    47 }
    48
    49 }
    50
    51 public bool IsReusable {
    52 get {
    53 return false;
    54 }
    55 }
    56
    57 }

    最后可以对图片地址进行url重写,让页面代码美观一点,这个可有可无。

  • 相关阅读:
    hdu-6166(最短路+二进制分组)
    hdu-1238(kmp+枚举)
    hdu-3294(最长回文子串)
    hdu-3068(最长回文子串-manacher)
    二维凸包 Graham扫描算法 +hdu 1392
    经典技术书籍
    hdu 5365 计算几何 给几个点判断是否为正方形
    线性素数筛
    关于大数的题
    树状数组的简介和线段树基础操作
  • 原文地址:https://www.cnblogs.com/jesselzj/p/2332415.html
Copyright © 2011-2022 走看看