图片格式是PNG格式,如图:背景色是黑色,或者说是近似黑色。
经过处理后要达到消除背景色,并且保留大树阴影的功能。如图:
C#是否能够消除背景色,但是保留这颗大树的阴影呢?当然,可以。
现在我贴一段代码,是一个热心网友提供的,可以做到这一点,大家可以自己试试:
     public Bitmap Test()
        {
            var img = new Bitmap("c:\\1.png");           
            //X轴
            for(var x=0;x<img.Width;x++)
            {
                //Y轴
                for(var y = 0;y<img.Height;y++)
                {
                    var color = img.GetPixel(x, y); //得到X,Y处的像素
                    if(color.R==0 && color.G==0 && color.B==0) //检查是否是黑的
                    {
                        img.SetPixel(x,y,Color.Transparent); //设置为透明                     }
                }     
            }
            return img;
        }
现在又有新的问题出现了,如果处理这样一张图片,就会发现,黑色,或者说类似黑色的区域无法消除,大家可以自己动手试试看,非常有趣。
当然,我很菜,我没想出什么太好的办法,求大师指点迷津
------------
大家可以以上面的图片为例,谈谈思路、互相交流心得体会,让更多的新人受益。

解决方案 »

  1.   

    ...  看来那一贴你还是没看懂.
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    using System.Runtime.InteropServices;
    using System.Drawing.Imaging;namespace TrialTest
    {
        public partial class Frm图片黑色区域透明 : Form
        {        OpenFileDialog opfg = new OpenFileDialog();
            Bitmap bmpeee;
            byte step;        public Frm图片黑色区域透明()
            {
                InitializeComponent();
               
                opfg.Filter = "图像文件|*.jpg;*.gif;*.png;*.bmp|All files(*.*)|*.*";
            }
            /// <summary>
            /// 获取指定透明度的图像
            /// </summary>
            /// <param name="SourceBitmap">源图像</param>
            /// <param name="OpaCityValue">透明度百分比</param>
            /// <returns></returns>
            /// <res></res>
            public Bitmap TheTransparentBitmap(Bitmap SourceBitmap, double OpaCityValue)
            {
                try
                {
                    Bitmap ForOutBitmap = new Bitmap(SourceBitmap);
                    BitmapData bmpDATA = new BitmapData();
                    bmpDATA = ForOutBitmap.LockBits(new Rectangle(0, 0, SourceBitmap.Width - 1, SourceBitmap.Height - 1), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
                    byte[] BTS = new byte[bmpDATA.Stride * bmpDATA.Height + 1];
                    Marshal.Copy(bmpDATA.Scan0, BTS, 0, BTS.Length - 1);
                    int tmpValue = 0;
                    for ( int I = 0; I <= BTS.Length - 4; I += 4)
                    {
                        if (IsBlack(BTS[I], BTS[I + 1], BTS[I + 2]))
                        {
                            tmpValue = (int)(BTS[I + 3] * OpaCityValue);
                            BTS[I + 3] = (byte)tmpValue;
                        }
                    }
                    Marshal.Copy(BTS, 0, bmpDATA.Scan0, BTS.Length - 1);
                    ForOutBitmap.UnlockBits(bmpDATA);
                    return ForOutBitmap;
                }
                catch (Exception ex)
                {
                    return null;
                }
            }
            private bool IsBlack(byte B, byte G, byte R)
            {
                return -step < B && B < step && -step < G && G < step && -step < R && R < step;
            }
            private void button1_Click(object sender, EventArgs e)
            {
                this.opfg.FileName = this.textBox1.Text;
                if (this.opfg.ShowDialog() == DialogResult.OK)
                {
                    if (bmpeee != null)
                        bmpeee.Dispose();
                    try { bmpeee = new Bitmap(opfg.FileName); }
                    catch (Exception) { MessageBox.Show("错误的文件格式!它不是一个受支持的图像!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Stop); }
                    if (bmpeee != null)
                    {
                        this.textBox1.Text = opfg.FileName;
                        if (pictureBox1.Image != null)
                        {
                            pictureBox1.Image.Dispose();
                            pictureBox1.Image = null;
                        }
                        pictureBox1.Image = bmpeee;
                    }
                }
            }
            private void button2_Click(object sender, EventArgs e)
            {
                if (pictureBox1.Image != null)
                    pictureBox1.Image = TheTransparentBitmap((Bitmap)pictureBox1.Image, 0.00f);
            }
            private void trackBar1_Scroll(object sender, EventArgs e)
            {
                if (bmpeee != null)
                {
                    step = (byte)trackBar1.Value;
                    pictureBox1.Image = TheTransparentBitmap(bmpeee, 0.00f);
                }
            }
        }
    }
      

  2.   

    if(color.R==0 && color.G==0 && color.B==0) //检查是否是黑的
    这句话是判断纯黑色的,而不是近是黑色,所以近是黑色,你没法透明了
      

  3.   

    另一个文件
    namespace TrialTest
    {
        partial class Frm图片黑色区域透明
        {
            /// <summary>
            /// 必需的设计器变量。
            /// </summary>
            private System.ComponentModel.IContainer components = null;        /// <summary>
            /// 清理所有正在使用的资源。
            /// </summary>
            /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
            protected override void Dispose(bool disposing)
            {
                if (disposing && (components != null))
                {
                    components.Dispose();
                }
                base.Dispose(disposing);
            }        #region Windows 窗体设计器生成的代码        /// <summary>
            /// 设计器支持所需的方法 - 不要
            /// 使用代码编辑器修改此方法的内容。
            /// </summary>
            private void InitializeComponent()
            {
                this.pictureBox1 = new System.Windows.Forms.PictureBox();
                this.button1 = new System.Windows.Forms.Button();
                this.textBox1 = new System.Windows.Forms.TextBox();
                this.trackBar1 = new System.Windows.Forms.TrackBar();
                this.label1 = new System.Windows.Forms.Label();
                ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
                ((System.ComponentModel.ISupportInitialize)(this.trackBar1)).BeginInit();
                this.SuspendLayout();
                // 
                // pictureBox1
                // 
                this.pictureBox1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
                this.pictureBox1.Dock = System.Windows.Forms.DockStyle.Bottom;
                this.pictureBox1.Location = new System.Drawing.Point(0, 26);
                this.pictureBox1.Name = "pictureBox1";
                this.pictureBox1.Size = new System.Drawing.Size(956, 618);
                this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
                this.pictureBox1.TabIndex = 0;
                this.pictureBox1.TabStop = false;
                // 
                // button1
                // 
                this.button1.Location = new System.Drawing.Point(459, 1);
                this.button1.Name = "button1";
                this.button1.Size = new System.Drawing.Size(75, 23);
                this.button1.TabIndex = 1;
                this.button1.Text = "浏览...";
                this.button1.UseVisualStyleBackColor = true;
                this.button1.Click += new System.EventHandler(this.button1_Click);
                // 
                // textBox1
                // 
                this.textBox1.Location = new System.Drawing.Point(2, 1);
                this.textBox1.Name = "textBox1";
                this.textBox1.ReadOnly = true;
                this.textBox1.Size = new System.Drawing.Size(451, 21);
                this.textBox1.TabIndex = 3;
                // 
                // trackBar1
                // 
                this.trackBar1.AutoSize = false;
                this.trackBar1.Location = new System.Drawing.Point(616, 1);
                this.trackBar1.Maximum = 255;
                this.trackBar1.Name = "trackBar1";
                this.trackBar1.Size = new System.Drawing.Size(328, 23);
                this.trackBar1.TabIndex = 4;
                this.trackBar1.TickStyle = System.Windows.Forms.TickStyle.None;
                this.trackBar1.Scroll += new System.EventHandler(this.trackBar1_Scroll);
                // 
                // label1
                // 
                this.label1.AutoSize = true;
                this.label1.Location = new System.Drawing.Point(562, 7);
                this.label1.Name = "label1";
                this.label1.Size = new System.Drawing.Size(59, 12);
                this.label1.TabIndex = 5;
                this.label1.Text = "黑色调节:";
                // 
                // Frm图片黑色区域透明
                // 
                this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
                this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
                this.AutoScroll = true;
                this.ClientSize = new System.Drawing.Size(956, 644);
                this.Controls.Add(this.label1);
                this.Controls.Add(this.trackBar1);
                this.Controls.Add(this.textBox1);
                this.Controls.Add(this.button1);
                this.Controls.Add(this.pictureBox1);
                this.Name = "Frm图片黑色区域透明";
                this.Text = "Form2";
                ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
                ((System.ComponentModel.ISupportInitialize)(this.trackBar1)).EndInit();
                this.ResumeLayout(false);
                this.PerformLayout();        }        #endregion
            private System.Windows.Forms.PictureBox pictureBox1;
            private System.Windows.Forms.Button button1;
            private System.Windows.Forms.TextBox textBox1;
            private System.Windows.Forms.TrackBar trackBar1;
            private System.Windows.Forms.Label label1;    }
    }
      

  4.   

    你那个帖子给你回复过了。
    新建项目,拖大一点,右下角放个按钮,双击按钮,吧上面代码复制替换生成的按钮事件,运行,点击,选中你的文件。绘制出你目标图案……
    private void button1_Click(object sender, EventArgs e)
    {
        OpenFileDialog dlg = new OpenFileDialog();
        dlg.Filter = "*.png|*.png||";
        if (dlg.ShowDialog() != System.Windows.Forms.DialogResult.OK) return;
        Image img = Image.FromFile(dlg.FileName);
        using (Graphics g = this.CreateGraphics())
        {
            System.Drawing.Imaging.ImageAttributes ia = new ImageAttributes();
            Color c = (img as Bitmap).GetPixel(0, 0);
            ia.SetColorKey(c, c);
            Rectangle rect = new Rectangle(0,0,img.Width,img.Height);
            g.DrawImage(img, rect, 0, 0, img.Width, img.Height, GraphicsUnit.Pixel, ia);    }
    }
      

  5.   

     hiddkiller 的头像很牛!
      

  6.   

    引用 3 楼 gxingmin 的回复:
    if(color.R==0 &amp;&amp; color.G==0 &amp;&amp; color.B==0) //检查是否是黑的
    这句话是判断纯黑色的,而不是近是黑色,所以近是黑色,你没法透明了将其中"==0”换成"<=xx"楼主别说不会啊~~~
      

  7.   

    亮点:ImageAttribute类的SetColorKey用法。
      

  8.   

    类似这种游戏常用的像素图,通常使用左上角(0,0)坐标处的颜色为透明色.只要遍历像素,但凡色彩值与(0,0)处一样的都可以修改为透明.至于所谓的"近似色",那是对于非像素化图像,比如JPEG/PNG等.
      

  9.   

    Sorry,不好意思. 我对我说的话表示歉意. 
      

  10.   

    就在你第一帖中. 在38楼里修改的dylike的代码里面的 8(颜色区间)越大消失的黑色素越多. 
      

  11.   

    啊,我知道了,它有一个Value
      

  12.   


    ImageAttribute.SetColorKey本身就可以设置一个范围是过滤色的。你们自己也实现了。实际上系统已经有这个方法了。你们的调节实际上就是调节SetColorKey的2个参数而已…