当前位置: 代码迷 >> ASP.NET >> .net web中Image控件的有关问题
  详细解决方案

.net web中Image控件的有关问题

热度:9347   发布时间:2013-02-25 00:00:00.0
.net web中Image控件的问题
如题,在winform中,可以直接用 pictureBox1.Image = 类名a.方法名b(); 类名a.方法名b()返回Bitmap类型。
现在在web中,我运用Image控件,那么怎么实现把返回为Bitmap类型,赋给Image,让图片显示出来,谢谢!

------解决方案--------------------------------------------------------
[code=C#][/code]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;

public partial class CheckCode : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
CreateCheckCodeImage(GenerateCheckCode());
}

private string GenerateCheckCode()
{
char code;
int number;
string checkCode = String.Empty;

Random random = new Random();

for (int i = 0; i < 4; i++)
{
number = random.Next();

if (number % 2 == 0)
code = (char)('0' + (char)(number % 10));
else
code = (char)('A' + (char)(number % 26));

checkCode += code;
}

Response.Cookies.Add(new HttpCookie("CheckCode", checkCode));

return checkCode;
}

private void CreateCheckCodeImage(string checkCode)
{
if (checkCode == null || checkCode.Trim() == String.Empty)
return;

Bitmap image = new Bitmap((int)Math.Ceiling((checkCode.Length * 12.5)), 22);
Graphics graphics = Graphics.FromImage(image);

try
{
//生成随机生成器
Random random = new Random();

//清空图片背景色
graphics.Clear(Color.White);

//画图片的背景噪音线
for (int i = 0; i < 25; i++)
{
int x1 = random.Next(image.Width);
int x2 = random.Next(image.Width);
int y1 = random.Next(image.Height);
int y2 = random.Next(image.Height);

graphics.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
}

Font font = new Font("Arial", 12, (FontStyle.Bold | FontStyle.Italic));
LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
graphics.DrawString(checkCode, font, brush, 2, 2);

//画图片的前景噪音点
for (int i = 0; i < 100; i++)
{
int x = random.Next(image.Width);
int y = random.Next(image.Height);

image.SetPixel(x, y, Color.FromArgb(random.Next()));
}

//画图片的边框线
graphics.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);

MemoryStream ms = new MemoryStream();
image.Save(ms, ImageFormat.Gif);

Response.ClearContent();
Response.ContentType = "image/gif";
Response.BinaryWrite(ms.ToArray());

}
finally
{
graphics.Dispose();
image.Dispose();
}
}
}最后,另外一个页面:

<asp:Image ID="Image1" runat="server" ImageUrl="CheckCode.aspx" />

--------------------------------------------------------------------------------
摘抄的自己看下,希望对你有帮助
------解决方案--------------------------------------------------------
Bitmap型不能直接给Image控件,除非先把该Bitmap保存为文件,否则应该没有办法。

还有一种是给ImageUrl属性一个动态页地址,那个动态页输出Bitmap。类似于验证码图片的做法。

------解决方案--------------------------------------------------------
  相关解决方案