将图片转换为HTML图片

时间:2024-03-07 20:10:34
http://hi.baidu.com/luchaoshuai/blog/item/01b5fb35563fcf8ea71e1232.html

将图片转换为HTML代码(DIV点阵),也就是将图片的每个象素点都用DIV来实现

 

   protected void Button1_Click(object sender, System.EventArgs e)
    {
        Response.Write( CovertImageToHtml("d:\\2.jpg"));
    }


    /// <summary>
    /// 把图片转换为div显示的html
    /// 由于图片过大会直接占用CPU和内存,因此只适合验证码等小图片显示
    /// </summary>
    /// <param name="imageFile"></param>
    /// <returns></returns>
    public static string CovertImageToHtml(string imageFile)
    {
        using (System.Drawing.Bitmap image = new System.Drawing.Bitmap(imageFile))
        {
            return CovertImageToHtml(image);
        }
    }

    /// <summary>
    /// 把图片转换为div显示的html
    /// </summary>
    /// <param name="sb"></param>
    /// <param name="image"></param>
    private static string CovertImageToHtml(System.Drawing.Bitmap image)
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();

        //定义CSS样式
        sb.AppendLine("<style>");
        sb.AppendLine(string.Format("#htmlpic{{width:{0}px;height:{1}px;}}", image.Width, image.Height));
        sb.AppendLine("#htmlpic div{float:left;height:1px;overflow:hidden;}");
        sb.AppendLine("</style>");

        //输出图片数据
        sb.AppendLine("<div id=\"htmlpic\">");
        for (int h = 0; h < image.Height; h++)
        {
            System.Drawing.Color preColor = image.GetPixel(0, h);     //获取第一点的颜色值
            int count = 1;
            for (int w = 1; w < image.Width; w++)
            {
                System.Drawing.Color nowColor = image.GetPixel(w, h);
                if (preColor == nowColor)
                {
                    count++;
                }
                else
                {
                    sb.AppendLine(string.Format("<div style=\"background:{0};width:{1}px\"></div>", System.Drawing.ColorTranslator.ToHtml(preColor), count));
                    count = 1;
                    preColor = nowColor;
                }
            }
            //写入最后的数据
            sb.AppendLine(string.Format("<div style=\"background:{0};width:{1}px\"></div>", System.Drawing.ColorTranslator.ToHtml(preColor), count));
            sb.AppendLine();
        }
        sb.AppendLine("</div>");
        return sb.ToString();
    }