2023年2月12日 星期日

[研究][WinForm][C#]把白底圖去背變成透明圖

[研究][WinForm][C#]把白底圖去背變成透明圖

2023-02-12

環境:Visual Studio 2022 + WinForm + C#

********************************************************************************

Form1.cs

using System.Drawing.Imaging;
using System.Windows.Forms;

namespace BgRemover
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            openFileDialog1.InitialDirectory = "c:\\";
            //openFileDialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
            //openFileDialog1.FilterIndex = 2;
            //openFileDialog1.RestoreDirectory = true;

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                string filePath = openFileDialog1.FileName;
                Image image = System.Drawing.Image.FromFile(filePath);
                Bitmap pbitmap = new Bitmap(image);
                pbitmap.MakeTransparent(Color.White);
                pictureBox1.Image = pbitmap;
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog1 = new SaveFileDialog();
            //saveFileDialog1.Filter = "Png Image|*.png|JPeg Image|*.jpg|Bitmap Image|*.bmp|Gif Image|*.gif";
            saveFileDialog1.Filter = "Png Image|*.png";
            saveFileDialog1.Title = "Save an Image File";
            saveFileDialog1.ShowDialog();

            if (saveFileDialog1.FileName != "")
            {
                pictureBox1.Image.Save(saveFileDialog1.FileName, ImageFormat.Png);
            }
        }
    }
}

(完)

相關

沒有留言:

張貼留言