首页 > 编程 > .NET > 正文

.NET中的动态生成图像组件

2024-07-10 13:03:45
字体:
来源:转载
供稿:网友

y'know, there's this really cool library in .net for dynamically creating images on the fly. however, this article has nothing to do with that, so if that's what you're looking for, stop now. what this article is about is very simple -- how to use a single line of code (via a component call) to output the contents of an image residing on the server's hard drive. why not just use an img tag? well, we want this page to used as the src of an img tag, so it has to actually have a content-type of "image/gif" and use binarywrite to display the image. to do this in classic asp requires a custom component (or a third party component such as persits aspupload, which has a sendbinary method that does this). in fact, let's take a look at how this works with a quick sample before we do it in .net. below is the complete code required to display a static image using aspupload. you can see this file in action by clicking here.

displayimage.asp:
1 <% option explicit %>
2 <object id="objupload" runat="server" progid="persits.upload.1"></object>
3 <%
4 objupload.sendbinary server.mappath("/images/aspalliance_fade_468x60.gif"), true
5 %>

now, let's do this in .net. we can use the system.drawing library to open an image and display it, using the following code:

displayimage.aspx:
1 <%@ page language="c#" autoeventwireup="false" trace="false" debug="false" %>
2 <% @import namespace="system.drawing" %>
3 <% @import namespace="system.io" %>
4 <% @import namespace="system.drawing.imaging" %>
5 <%@ outputcache duration="100" varybyparam="none" %>
6 <%
7 string path;
8 path = server.mappath("///images//aspalliance_fade_468x60.gif");
9 system.drawing.image myimage = system.drawing.image.fromfile(path);
10
11 memorystream tempstream = new memorystream();
12 myimage.save(tempstream,imageformat.gif);
13
14 response.clearcontent();
15 response.contenttype = "image/gif";
16 response.binarywrite(tempstream.toarray());
17 response.end();
18 %>

here is the result of using this code as the src of an img tag:


old:(notice that there is a problem here -- this is an animated gif, but this version doesn't show any more than the first frame of the graphic. not good. so we'll scrap that version, hope that perhaps there is an animated gif type supported in the future, and move on.)

as you can see, the above example renders the animated gif image just fine now, thanks to updates to the .net framework in beta2. the httpimage class, below, is no longer necessary, but is left for posterity. -- steve the httpimage class -- no longer functional (or necessary) under beta 2

you can tell we're getting to the real thing now, because i actually bothered to put the working code into a class file. in this case, i called it httpimage, and it's written in c# and has two simple methods. actually, one overloaded method, outputimageviahttp, which takes either a virtual file path or a static file path. before we get into the class, let's see it in action by looking at a simple aspx page that uses it. click here for the example, and below is the source code. note that the asp.net page is passing its own instances of response and server to the component (line 8). we'll see how the component uses these below.

displayimage2.aspx:
1 <%@ page language="c#" contenttype="image/gif" %>
2 <%@ import namespace="stevenator.components" %>
3 <%@ outputcache duration="100" varybyparam="none" %>
4 <script language="c#" runat="server">
5 protected void page_load(object sender, eventargs e)
6 {
7 httpimage myhttpimage = new httpimage();
8 myhttpimage.outputimageviahttp("//images//aspalliance_fade_468x60.gif", this.response, this.server);
9 }
10 </script>

pretty cool, eh? the image is actually animated, as it's supposed to be. now, the reason this is even remotely useful is so that if you want to show a random image, like for an ad banner, you can use this method to output the image from your file system. for example, this image tag has as its source the same file that we just looked at (it is animated to fade in about once per minute):


ok, now we're finally ready to actually look at the class. first, here is the source code:

httpimage.cs:
1 namespace stevenator.components
2 {
3 using system;
4 using system.io;
5 using system.web;
6
7 /// <summary>
8 /// summary description for httpimage.
9 /// </summary>
10 public class httpimage
11 {
12 public httpimage()
13 {
14 //
15 // todo: add constructor logic here
16 //
17 }
18
19 public void outputimageviahttp(string absolutepath, httpresponse response)
20 {
21 filestream ofilestream;
22 long lfilesize, lstartpos = 0;
23
24 ofilestream = new filestream(absolutepath, filemode.open);
25 lfilesize = ofilestream.length;
26
27 byte[] bbuffer = new byte[(int)lfilesize];
28 ofilestream.read(bbuffer, 0, (int)lfilesize);
29 ofilestream.close();
30
31 response.clearcontent();
32 response.contenttype = "image/gif";
33
34 response.binarywrite(bbuffer);
35 ofilestream.close();
36 response.end();
37 }
38 public void outputimageviahttp(string virtualpath, httpresponse response, httpserverutility server)
39 {
40 string path;
41
42 path = server.mappath(virtualpath);
43
44 outputimageviahttp(path, response);
45 }
46 }
47 }

as you can see, this is a pretty simple class. no frills. let's look at the second overloaded method first, since it's simpler. on line 38 you can see the declaration. we need to pass in the a response and a server object from our asp.net page, which we saw on line 8 of displayimage2.aspx. we only need server for this second overloaded call, because we're going to use server.mappath to determine the absolute path to the image and then simply call the other method. which takes us to line 19, the other method call.

we're going to use the filestream object to access the image, and we will need to know the file's size so that we know when to stop reading and avoid an error. lines 27 to 30 do all 90% of the work for this class, by loading the buffer with the contents of the file. then all that remains is to set the content type to an image type (in this case, i've hardcoded it to be "image/gif", but you could make that a parameter or base it on the file extension) and then use the binarywrite command to output the image. the binarywrite command is nothing new to classic asp developers -- in fact, the basic concepts of this whole article are all old news for class asp developers, but i hadn't done this in .net before, so i thought i'd share it with you. hopefully it'll help a few of you get going with .net a little faster. if you just want to plug the component in and see it work, you can download it here: httpimage.dllx. the download didn't like the fact that it was a dll, so remove the x from the end of the filename after you download it. you can get the c# source here.
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表