Cool!!将图片转换为HTML图片

嘿嘿,就是将图片转换为HTML代码(DIV点阵),也就是将图片的每个象素点都用DIV来实现,这样一张HTML图片就出来了:)
为了避免IE暂停响应,转换的图片不要太大.要不然转换出来也不敢看!比如我们将验证码图片输出为HTML代码,这样要破解的话就让对方去还原这副图片吧:)
大家看看下面这张图(嘿嘿,不是图片来的,注意别用鼠标拖动选择,要不然我怕你的浏览器会暂停响应!)的效果:




代码很少很简单,就只有两个函数,如下:
        public static void CovertImageToHtml(string imageFile, string fileName)
        
{
            
using (Bitmap image = new Bitmap(imageFile))
            
{
                CovertImageToHtml(image, fileName); 
            }

        }

        
public static void CovertImageToHtml(Bitmap image, string fileName)
        
{
            
using (StreamWriter writer = new StreamWriter(fileName, false, Encoding.Default, 1024))
            
{
                
//定义CSS样式
                writer.WriteLine("<style>");
                writer.WriteLine(
"#htmlpic{{width:{0}px;height:{1}px;}}", image.Width, image.Height);
                writer.WriteLine(
"#htmlpic div{float:left;height:1px;overflow:hidden;}");
                writer.WriteLine(
"</style>");

                
//输出图片数据
                writer.WriteLine("<div id=\"htmlpic\">");
                
for (int h = 0; h < image.Height; h++)
                
{
                    Color preColor 
= image.GetPixel(0, h);     //获取第一点的颜色值
                    int count = 1;
                    
for (int w = 1; w < image.Width; w++)
                    
{
                        Color nowColor 
= image.GetPixel(w, h);
                        
if (preColor == nowColor)
                        
{
                            count
++;
                        }

                        
else
                        
{
                            writer.WriteLine(
"<div style=\"background:{0};width:{1}px\"></div>", ColorTranslator.ToHtml(preColor), count);
                            count 
= 1;
                            preColor 
= nowColor;
                        }

                    }

                    
//写入最后的数据
                    writer.WriteLine("<div style=\"background:{0};width:{1}px\"></div>", ColorTranslator.ToHtml(preColor), count);
                    writer.WriteLine();
                }

                writer.WriteLine(
"</div>");
            }

        }
posted @ 2008-05-09 11:26  Kingthy  阅读(4246)  评论(15编辑  收藏  举报