错误描述:A Graphics object cannot be created from an image that has an indexed pixel
解决思路:做一个同样尺寸的bitmap,将“indexed pixel format”格式的图片复制过来,变为一个非“indexed pixel format”的图片
实现代码:
protected void Page_Load(object sender, EventArgs e)
{
if(Page.IsPostBack ==false)
{
string file = "mailbanner.gif";
string addText = "上海星移企业邮局";
try
{
addText = Request.QueryString["mark"].ToString();
}
catch(Exception)
{
}
//载入原始图片
Bitmap bmp = new Bitmap(Server.MapPath(file));
Graphics graphics;
try
{
//试图取得Graphics对象,用于添加文字
//对于indexed pixel format,此处会抛出异常
graphics = System.Drawing.Graphics.FromImage(bmp);
}
catch (Exception)
{
//对于indexed pixel format,抛出异常的特殊处理
Bitmap newBmp = new Bitmap(bmp.Width, bmp.Height);
graphics = System.Drawing.Graphics.FromImage(newBmp);
graphics.DrawImage(bmp,
new Rectangle(0, 0, newBmp.Width, newBmp.Height),
new Rectangle(0, 0, bmp.Width, bmp.Height),
GraphicsUnit.Pixel);
bmp = newBmp;
}
graphics.DrawString(addText,
new Font("Verdana", 14, FontStyle.Regular ),
new SolidBrush(Color.Gray), 181, 9);
graphics.DrawString(addText,
new Font("Verdana", 14, FontStyle.Regular),
new SolidBrush(Color.Goldenrod ), 180, 8);
graphics.Dispose();
System.IO.MemoryStream ms = new System.IO.MemoryStream();
//网上的例程,通常是 bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg)
//色彩失真明显
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
bmp.Dispose();
Response.ClearContent();
Response.ContentType = "image/bmp";
Response.BinaryWrite(ms.ToArray());
}
}