您的位置:首页 > 其它

System.Drawing.Graphics读取带有索引的图片及思考

2008-02-15 19:10 274 查看
用.NET的System.Drawing.Graphics来加载带有索引的图片,比如带有透明色的GIF图片,会出现“A Graphics object cannot be created from an image that has an indexed pixel format”的错误。上网搜索了一番,找到了变通解决的方法

本文代码下载
代码如下:

using (Bitmap image = new Bitmap(Server.MapPath("1.gif")))
{
// Size the new bitmap to source image's dimension.
using (Bitmap frame = new Bitmap(image.Width, image.Height))
{
// Uses temp frame to write on g.
using (Graphics g = Graphics.FromImage(frame))
{
g.Clear(Color.Red);
//g.Clear(Color.Transparent);

// Draw the original indexed image's content to the temp frame.
// Paint the entire region of original image to the temp frame.
// Use the rectangle type to select area of source image.
g.DrawImage(image, new Rectangle(0, 0, frame.Width, frame.Height), 0, 0, image.Width, image.Height, GraphicsUnit.Pixel);

Font f = new Font("Verdana", 30);
Brush b = new SolidBrush(Color.Black);
string addText = "ˮӡ";
g.DrawString(addText, f, b, 400, 100);

Response.Clear();
Response.ContentType = "image/bmp";

frame.Save(Response.OutputStream, ImageFormat.Jpeg);
}
}
}


.csharpcode{ background-color: #eee; border:1px solid #ccc; padding:5px;}
.csharpcode, .csharpcode pre
{
font-size: 1em;
color: black;
font-family: "Courier New", courier, monospace;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

就是不直接读取这个GIF,新建一个和它同样大小的Bitmap,用Graphics把图像画上去。但在输出图像的发现透明的地方变成了黑色,当我把Graphics清成红色时,输出的图像在透明处变成了红色,说明GIF的透明起作用了。由此引出了我的考虑:难道空的Graphics是黑色的,为什么不是透明色呢?

.csharpcode{ background-color: #eee; border:1px solid #ccc; padding:5px;}
.csharpcode, .csharpcode pre
{
font-size: 1em;
color: black;
font-family: "Courier New", courier, monospace;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

经过我的大量尝试和搜索,大概只用FCL是不能生成透明的GIF了,不知哪位大大有其他方法或是类库,还望赐教。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐