(原創) 如何将图片转成Binary Image? (.NET) (ASP.NET) (C#) (GDI+) (Image Processing)

这是我修Computer Vision的作业,此源代码也示范出如何Pixel By Pixel的方式编辑图片以及如何读取indexd的bmp图片格式。

所谓的Binary Image,就是整个图片只用黑色和白色表示,一个灰阶图片,全部的颜色只有256种(0~255),若大于128,则用黑色表示RGB(255,255,255),若小于128,则用白色表示RGB(0,0,0),主要是方便做影像辨识。

 1<%@ Page Language="C#" %>
 2
 3<%@ Import Namespace="System.Drawing" %>
 4<%@ Import Namespace="System.Drawing.Imaging" %>
 5<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 6
 7<script runat="server">
 8
 9  protected void Page_Load(object sender, EventArgs e) {
10    // Bitmap uses System.Drawing namespace.
11    Bitmap bmpOld = new Bitmap(Server.MapPath("lena.bmp"));
12
13    // Size the new bitmap to source bitmap's dimension.
14    Bitmap bmpNew = new Bitmap(bmpOld.Width, bmpOld.Height);
15
16    Graphics canvas = Graphics.FromImage(bmpNew);
17
18    // Draw the old bitmap's content to the new bitmap.
19    // Paint the entire region of old bitmap to the new bitmap.
20    // Use the rectangle type to select area of source image.
21    canvas.DrawImage(bmpOld, new Rectangle(00, bmpNew.Width, bmpNew.Height), 00, bmpOld.Width, bmpOld.Height, GraphicsUnit.Pixel);
22
23    bmpOld = bmpNew;
24    
25    int gray = 0;
26    
27    for(int x=0;x < bmpOld.Width;x++{
28      for (int y = 0; y < bmpOld.Height; y++{
29        gray = bmpOld.GetPixel(x, y).R;
30        gray += bmpOld.GetPixel(x, y).G;
31        gray += bmpOld.GetPixel(x,y).B;
32        
33        gray /= 3;
34        
35        if (gray >= 128{
36          bmpOld.SetPixel(x,y,Color.FromArgb(255,255,255));
37        }

38        else {
39          bmpOld.SetPixel(x,y,Color.FromArgb(0,0,0));
40        }

41      }

42    }

43    
44    Response.ContentType = "image/bmp";
45
46    // ImageFormat uses System.Drawing.Imaging namespace.
47    // Must use ImageFormat.Jpeg. If use ImageFormat.Bmp,
48    // you'll get "System.Runtime.InteropServices.ExternalException: A generic error occurred in GDI+." error.
49    bmpOld.Save(Response.OutputStream, ImageFormat.Jpeg);
50
51    // You should always call the Dispose method to release 
52    // the Graphics and related resources created by the 
53    // FromImage method.
54    bmpNew.Dispose();
55    bmpOld.Dispose();
            canvas.Dispose();
56
57  }

58
</script>
59
60<html xmlns="http://www.w3.org/1999/xhtml">
61<head runat="server">
62  <title>Untitled Page</title>
63</head>
64<body>
65  <form id="form1" runat="server">
66    <div>
67    </div>
68  </form>
69</body>
70</html>
71


See Also
(原創) 如何實現Real Time的Binary Image? (SOC) (Verilog) (Image Processing) (DE2-70) (TRDB-D5M)  

posted on 2006-10-15 19:36  真 OO无双  阅读(3552)  评论(5编辑  收藏  举报

导航