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

用.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);
        }
    }
}

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

经过我的大量尝试和搜索,大概只用FCL是不能生成透明的GIF了,不知哪位大大有其他方法或是类库,还望赐教。

posted on 2008-02-15 19:10  Superstone  阅读(811)  评论(0编辑  收藏  举报

导航