NEWS

[C#] Color Thief cách xuất màu sắc thiết kế từ hình ảnh

[C#] Color Thief cách xuất màu sắc thiết kế từ hình ảnh
Đăng bởi: Thảo Meo - Lượt xem: 1222 15:55:29, 06/09/2023DEVEXPRESS   In bài viết

Xin chào các bạn, bài viết hôm nay mình hướng dẫn các bạn cách lấy màu sắc từ hình ảnh sử dụng thư viện color thief trong lập trình C#, winform.

[C#] How to extract color from image use Color Thief

Giao diện demo ứng dụng:

pallet_color

Color Thief là một thư viện phổ biến trong lập trình C#, giúp bạn trích xuất màu chính từ một hình ảnh.

Thư viện này thường được sử dụng trong ứng dụng WinForms để lấy màu chủ đạo từ một hình ảnh, điều này có thể hữu ích trong việc thiết kế giao diện người dùng, tạo biểu đồ dựa trên màu sắc hoặc thậm chí tạo gợi ý màu sắc dựa trên hình ảnh.

Đầu tiên, các bạn cài đặt thư viện từ Nuget:

NuGet\Install-Package ksemenenko.ColorThief -Version 1.1.1.4

Video demo ứng dụng:

Source code C#:

using ColorThiefDotNet;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Net.Mime.MediaTypeNames;
using Image = System.Drawing.Image;

namespace ExtractColorPalletFromImage
{
    public partial class Form1 : Form
    {
        List<System.Drawing.Color> colorList = new List<System.Drawing.Color>();
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
          
            
          
        }

        private void label2_Click(object sender, EventArgs e)
        {

        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog openFileDialog = new OpenFileDialog())
            {
                openFileDialog.Filter = "Image Files|*.jpg;*.jpeg;*.png;*.gif|All Files|*.*";
                openFileDialog.Title = "Select an image file";               

                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    colorList.Clear();
                    string selectedImagePath = openFileDialog.FileName;

                    try
                    {
                       
                        picImage.Image = Image.FromFile(selectedImagePath);

                        var colorThief = new ColorThief();
                        var result = colorThief.GetPalette((Bitmap)picImage.Image, 10);
                        var colorDominant = colorThief.GetColor((Bitmap)picImage.Image);

                        var hexColorDominant = $"#{colorDominant.Color.R:X2}{colorDominant.Color.G:X2}{colorDominant.Color.B:X2}";
                        var _colorDominant = ColorTranslator.FromHtml(hexColorDominant);
                        pic_Do.BackColor = _colorDominant;
                        foreach (var paletteColor in result)
                        {
                            var hexColor = $"#{paletteColor.Color.R:X2}{paletteColor.Color.G:X2}{paletteColor.Color.B:X2}";
                            var color = ColorTranslator.FromHtml(hexColor) ;
                            colorList.Add(color);   
                        }
                        uc_ColorPallet1.Colors = colorList;


                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"Error loading image: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }
    }
}

Các bạn cần tạo một usercontrol để hiển thị bảng pallet màu:

Source code control show color pallets:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ExtractColorPalletFromImage
{
    public partial class uc_ColorPallet : UserControl
    {

        private List<Color> colors;
        private int selectedColorIndex = -1;
        private Timer toastTimer;
        private Label toastLabel;

        public uc_ColorPallet()
        {
            InitializeComponent();
            DoubleBuffered = true; // Enable double buffering for smoother drawing
            colors = new List<Color>();
            InitializeToastComponents();
        }

        private void InitializeToastComponents()
        {
            toastTimer = new Timer();
            toastTimer.Interval = 1500; // 2 seconds
            toastTimer.Tick += ToastTimer_Tick;

            toastLabel = new Label();
            toastLabel.AutoSize = true;
            toastLabel.BackColor = Color.FromArgb(128, Color.Black); // Semi-transparent background
            toastLabel.ForeColor = Color.White;
            toastLabel.Font = new Font("Tahoma", 10);
            toastLabel.Visible = false;
            toastLabel.Padding = new Padding(8, 8, 8, 8);

            Controls.Add(toastLabel);
        }

        public List<Color> Colors
        {
            get { return colors; }
            set { colors = value; Invalidate(); }
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);

            if (Colors.Count == 0)
            {
                return;
            }

            int numRows = (colors.Count + 4) / 5; // 5 columns
            int numCols = 5;

            int cellWidth = Width / numCols;
            int cellHeight = Height / numRows;

            using (var font = new Font("Arial", 10)) // Font for hex codes
            {
                for (int row = 0; row < numRows; row++)
                {
                    for (int col = 0; col < numCols; col++)
                    {
                        int colorIndex = row * numCols + col;
                        if (colorIndex >= colors.Count)
                            break;

                        Color color = colors[colorIndex];

                        int x = col * cellWidth;
                        int y = row * cellHeight;

                        // Fill the entire cell with the color
                        using (var brush = new SolidBrush(color))
                        {
                            e.Graphics.FillRectangle(brush, x, y, cellWidth, cellHeight);
                        }

                        // Draw the hex code inside the cell
                        string hexCode = ColorToHex(color);
                        SizeF textSize = e.Graphics.MeasureString(hexCode, font);
                        float textX = x + (cellWidth - textSize.Width) / 2;
                        float textY = y + (cellHeight - textSize.Height) / 2;
                        e.Graphics.DrawString(hexCode, font, Brushes.Black, textX, textY);

                        // Highlight the selected color
                        //if (colorIndex == selectedColorIndex)
                        //{
                            using (var pen = new Pen(Color.White, 4))
                            {
                                int borderWidth = 4;
                                e.Graphics.DrawRectangle(pen, x + borderWidth / 2, y + borderWidth / 2, cellWidth - borderWidth, cellHeight - borderWidth);
                            }
                       // }
                    }
                }
            }
        }

        private string ColorToHex(Color color)
        {
            return "#" + color.R.ToString("X2") + color.G.ToString("X2") + color.B.ToString("X2");
        }

        
        private void ShowToastMessage(string message, Point location)
        {
            toastLabel.Text = message;
            toastLabel.Location = location;
            toastLabel.Visible = true;
            toastTimer.Start();
        }

        private void ToastTimer_Tick(object sender, EventArgs e)
        {
            toastLabel.Visible = false;
            toastTimer.Stop();
        }

        protected override void OnMouseClick(MouseEventArgs e)
        {
            base.OnMouseClick(e);

            int colIndex = e.X / (Width / 5); // 5 columns
            int rowIndex = e.Y / (Height / ((colors.Count + 4) / 5)); // Determine the number of rows
            int cellIndex = rowIndex * 5 + colIndex;

            if (cellIndex >= 0 && cellIndex < colors.Count)
            {
                selectedColorIndex = cellIndex;

                // Copy the hex code to the clipboard
                string hexCode = ColorToHex(colors[cellIndex]);
                Clipboard.SetText(hexCode);

                // Show the "copied" toast message at the mouse click position
                ShowToastMessage($"Copied: {hexCode}", new Point(e.X, e.Y));

                // Redraw to update the selection
                Invalidate();
            }
        }
    }
}

Khi các bạn click vào từng màu sắc nó sẽ copy mã HexCode màu lại cho các bạn.

Thanks for watching!

 

DOWNLOAD SOURCE

THÔNG TIN TÁC GIẢ

BÀI VIẾT LIÊN QUAN

[C#] Color Thief cách xuất màu sắc thiết kế từ hình ảnh
Đăng bởi: Thảo Meo - Lượt xem: 1222 15:55:29, 06/09/2023DEVEXPRESS   In bài viết

CÁC BÀI CÙNG CHỦ ĐỀ

Đọc tiếp
.