728x90
반응형
pictureBox1에 로드한 이미지에서 마우스 클릭 시 해당 포인트의 컬러를 lblColor의 배경색으로 변경해 주고, RGB 값과 HEX 값을 텍스트박스에 각각 입력해 주는 코드입니다.
bmp.GetPixel(x, y)
해당 Bitmap의 지정된 픽셀의 색을 가져옴
pointColor.R pointColor.G pointColor.B
컬러의 R, G, B 값을 가져옴
pointColor.Name
컬러의 HEX 값을 가져옴
(ex) ff4a4c4f
C# Color 구조체는 ARGB로 구성이 되어있기 때문에 Hex 값이 8자리입니다.
A(Alpha) 값은 투명도를 나타내는데, 투명도를 제외한 RGB Hex 값만 뿌려주도록 아래와 같이 앞의 두 자리를 제외하고 영문자는 대문자로 나타내도록 했습니다.
pointColor.Name.Substring(2, 6).ToUpper() : ff4a4c4f -> 4A4C4F
1 2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
private void pictureBox1_MouseClick(object sender, MouseEventArgs e)
{
if (pictureBox1.BackgroundImage != null)
{
try
{
//Converting loaded image into bitmap
Bitmap bmp = new Bitmap(pictureBox1.BackgroundImage);
//Get the color at click point
//Get Ratio with PictureBox and Image
//(PictureBox Background Layout = Stretch)
int x = bmp.Width * e.X / pictureBox1.Width;
int y = bmp.Height * e.Y / pictureBox1.Height;
Color pointColor = bmp.GetPixel(x, y);
lblColor.BackColor = pointColor;
txtRgb.Text = $"({pointColor.R}, {pointColor.G}, {pointColor.B})";
txtHex.Text = $"#{pointColor.Name.Substring(2, 6).ToUpper()}";
//(ex) pointColor.Name.Substring(2, 6).ToUpper() : ff4a4c4f -> 4A4C4F
}
catch (Exception ex)
{
MessageBox.Show("Get Color Failed. : " + ex.ToString());
}
}
}
|
cs |
728x90
반응형