Example of the Image Display Method in ASP. NET,
This document describes how to display images in ASP. NET. Share it with you for your reference. The details are as follows:
Genimage. ashx:
Copy codeThe Code is as follows: <% @ 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 T in compliance with the License. // You may obtain a copy of the License :// http://www.opensource.org/licenses/artistic-license.htmlusing 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 {retur N true ;}} public void ProcessRequest (HttpContext Context) {// Get the image filename and album root path from the database // int numviews of image views; // ID int picid = Convert. toInt32 (Context. request ["id"]); // image path string imgpath = npdata. getPathToPicture (picid, out numviews); // Writing an image to output stream Context. response. contentType = "image/jpg"; // 'thumbnail 'means we are requesti Ng a thumbnail // display the 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 = 150366f/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. outpu TStream, 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 (); // update the number of database views. setNumViews (picid, numviews + 1 );}}}}
Usage:
Copy codeThe Code is as follows: imgCtrl. ImageUrl = "genimage. ashx? Id = "+ Request [" id "];
I hope this article will help you design ASP. NET programs.