欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

ASP.NET中图片显示方法实例

程序员文章站 2023-12-21 20:56:04
本文实例讲述了asp.net中图片的显示方法。分享给大家供大家参考。具体如下: genimage.ashx: 复制代码 代码如下:<%@ webhandler l...

本文实例讲述了asp.net中图片的显示方法。分享给大家供大家参考。具体如下:

genimage.ashx:

复制代码 代码如下:
<%@ webhandler language="c#" class="netpix.imagegenerator" %>

genimage.ashx.cs:

// copyright (c) 2003 by greg ennis
// (mailto:greg@ennis.net)
//
// the contents of this file are subject to the artistic license (the "license").
// you may not use this file except in compliance with the license. 
// you may obtain a copy of the license at:
// http://www.opensource.org/licenses/artistic-license.html
using system;
using system.collections;
using system.componentmodel;
using system.data;
using system.data.sqlclient;
using system.drawing;
using system.web;
using system.io;
using system.configuration;
using system.web.sessionstate;
using system.web.ui;
using system.web.ui.webcontrols;
using system.web.ui.htmlcontrols;
namespace netpix
{
  public class imagegenerator : ihttphandler 
  { 
    public bool isreusable 
    { get { return true; } } 
    public void processrequest(httpcontext context) 
    { 
      // get the image filename and album root path from the database
      //图片浏览次数
      int numviews;
      //图片数据库中的id
      int picid = convert.toint32(context.request["id"]);
      //图片路径 
      string imgpath = npdata.getpathtopicture(picid, out numviews);
      // writing an image to output stream
      context.response.contenttype = "image/jpg";
      // 'thumbnail' means we are requesting a thumbnail
      //显示缩略图
      if (context.request["thumbnail"] != null)
      {
        // need to load the image, resize it, and stream to the client.
        // calculate the scale so as not to stretch or distort the image.
        bitmap bmp = new bitmap(imgpath);
        float scale = 150.0f / system.math.max(bmp.height, bmp.width);
        system.drawing.image thumb = bmp.getthumbnailimage((int)(bmp.width * scale), (int)(bmp.height * scale), null, system.intptr.zero);
        thumb.save(context.response.outputstream, system.drawing.imaging.imageformat.jpeg);
        bmp.dispose();
        thumb.dispose();
      }
      else
      {
        // stream directly from the file
        // get the stream and send it out the response
        system.io.filestream fs = file.open(imgpath, filemode.open, fileaccess.read, fileshare.read);
        const int bytelength = 8192;
        byte[] bytes = new byte[bytelength];
        while( fs.read(bytes, 0, bytelength ) != 0 )
        {
          context.response.binarywrite(bytes); 
        }
        fs.close();
        //更新数据库浏览次数
        npdata.setnumviews(picid, numviews+1);
      }
    }
  }
}

使用方法:

复制代码 代码如下:
imgctrl.imageurl = "genimage.ashx?id=" + request["id"];

希望本文所述对大家的asp.net程序设计有所帮助。

上一篇:

下一篇: