智者樂山山如畫, 仁者樂水水無涯。 從從容容一盃酒, 平平淡淡一盞茶。 細雨朦朧小石橋, 春風盪漾小竹筏。 夜無明月花獨舞, 腹有詩書气自華。 吾生有崖,也知無崖,以有崖逐無崖,殆也

图片转成透明底

string sp = Server.MapPath("/");//"/PDF/tz/tempword/"
            if (!System.IO.Directory.Exists(sp))
            {
                System.IO.Directory.CreateDirectory(sp);
            }
            //Request.Files[0].SaveAs(path);

            ImageAttributes vAttr = new ImageAttributes(); //vAttr是关键

            //图像中与0,0那点相同的颜色要变成透明

            Bitmap bitmap = new Bitmap(Request.Files[0].InputStream);
            Bitmap bitmappng = new Bitmap(165, 165);//新生成的图片宽与高
            vAttr.SetColorKey(bitmap.GetPixel(0, 0), bitmap.GetPixel(0, 0));
            Graphics g = Graphics.FromImage(bitmappng);
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.DrawImage(bitmap, new Rectangle(10, 10, 165, 165), 0, 0, bitmap.Width, bitmap.Height, GraphicsUnit.Pixel, vAttr);
            g.Save();
            g.Dispose();
            bitmappng.Save(sp + "png.png", ImageFormat.Png);

 

 

ImageAttributes vAttr = new ImageAttributes(); //vAttr是关键

        //图像中与0,0那点相同的颜色要变成透明

        Bitmap bitmap = new Bitmap(Request.Files[0].InputStream);
        Bitmap bitmappng = new Bitmap(165, 165);
        bitmap.SetPixel(0, 0, Color.FromArgb(0, 0, 0));//设置为统一颜色

        /*将图片的背景只留下红色*/
        for (int i = 0; i < bitmap.Width; i++)
        {
            for (int j = 0; j < bitmap.Height; j++)
            {
                System.Drawing.Color c = bitmap.GetPixel(i, j);
                /*找到红色的RGB范围,然后再进行替换*/
                if (c.R > 128 && (c.R > c.G + 20 && c.R > c.B + 20))  /*非红色要替换成透明 每种颜色要存在一定的差距*/
                {
                    //bitmappng.SetPixel(i, j, System.Drawing.Color.Transparent);
                    //bitmap.SetPixel(i, j, Color.FromArgb(0,c.R, c.G, c.B));//设置为统一颜色
                }
                else
                {
                    bitmap.SetPixel(i, j, Color.FromArgb(0, 0, 0, 0));//设置为统一颜色
                }
            }
        }
        vAttr.SetColorKey(bitmap.GetPixel(0, 0), bitmap.GetPixel(0, 0));
        Graphics g = Graphics.FromImage(bitmappng);
        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
        g.DrawImage(bitmap, new Rectangle(0, 0, 165, 165), 0, 0, bitmap.Width, bitmap.Height, GraphicsUnit.Pixel, vAttr);
        g.Save();
        g.Dispose();



        bitmappng.Save(path, ImageFormat.Png);

 

posted @ 2020-06-23 09:05  後生哥哥  阅读(271)  评论(0编辑  收藏  举报
智者樂山山如畫, 仁者樂水水無涯。 從從容容一盃酒, 平平淡淡一盞茶。 細雨朦朧小石橋, 春風盪漾小竹筏。 夜無明月花獨舞, 腹有詩書气自華。 吾生有崖,也知無崖,以有崖逐無崖,殆也