(原創) 如何用程序的方式载入indexd过的图形文件? (.NET) (ASP.NET) (C#) (GDI+) (Image Processing)

做过indexd的图形文件,如使用正常的方式读取(参阅:如何用程序的方式载入jpg图形文件?),会出现A Graphics object cannot be created from an image that has an indexed pixel format.的错误讯息,以下的程序将示范如何读取indexed图形文件。

 1<!-- (C) OOMusou 2006.09.30 oomusou@hotmail.com-->
 2<%@ Page Language="C#" %>
 3
 4<%@ Import Namespace="System.Drawing" %>
 5<%@ Import Namespace="System.Drawing.Imaging" %>
 6<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 7
 8<script runat="server">
 9  /// <summary>
10  /// .NET Framework 2.0 can't draw indexd pixel format directly.
11  /// and will get  
12  /// "A Graphics object cannot be created from an image that " 
13  /// has an indexed pixel format." exception.
14  /// So we have to make a temporary bitmap, and manually draw 
15  /// indexed pixel format to general bitmap. 
16  /// exception. This example demos how to read indexd pixel format.
17  /// </summary>
18  protected void Page_Load(object sender, EventArgs e) {
19    // Bitmap uses System.Drawing namespace.
20    Bitmap bmp = new Bitmap(Server.MapPath("lena.bmp"));
21    
22    // Size the new bitmap to source bitmap's dimension.
23    Bitmap _bmp = new Bitmap(bmp.Width, bmp.Height);
24
25    // Uses temp _bmp to write on canvas.
26    Graphics canvas = Graphics.FromImage(_bmp);
27
28    // Draw the original indexed bitmap's content to the temp _bmp.
29    // Paint the entire region of original bitmap to the temp _bmp.
30    // Use the rectangle type to select area of source image.
31    canvas.DrawImage(bmp, new Rectangle(00, _bmp.Width, _bmp.Height), 00, bmp.Width, bmp.Height, GraphicsUnit.Pixel);
32
33    // Make temp _bmp to general bmp.
34    bmp = _bmp;
35
36    // Specify HTML's content type.
37    Response.Clear();
38    Response.ContentType = "image/bmp";
39
40    // ImageFormat uses System.Drawing.Imaging namespace.
41    // Must use ImageFormat.Jpeg. If use ImageFormat.Bmp,
42    // you'll get "System.Runtime.InteropServices.ExternalException: A generic error occurred in GDI+." error.
43    bmp.Save(Response.OutputStream,ImageFormat.Jpeg);
44
45    // You should always call the Dispose method to release 
46    // the Graphics and related resources created by the 
47    // FromImage method.
48    _bmp.Dispose();
49    bmp.Dispose();
50    canvas.Dispose();
51  }

52
</script>
53
54<html xmlns="http://www.w3.org/1999/xhtml">
55<head runat="server">
56  <title></title>
57</head>
58<body>
59  <form id="form1" runat="server">
60    <div>
61    </div>
62  </form>
63</body>
64</html>
65    


Reference
Steven A. Smith, Rob Howard, The ASP Alliance, ASP.NET 开发手札, 上奇科技出版事业处
KingLeon, Watermark Website Images At Runtime , The Code Project

posted on 2006-09-30 16:37  真 OO无双  阅读(1628)  评论(0编辑  收藏  举报

导航