views:

365

answers:

5

Hi,

Is it possible to determine the hexadecimal colour value for an image in C#, if the image is a single block colour?

I have a load of colour chart images, and need to put them into a table with the requisite hex value attached. Unfortunately, the file name is useless to determine this.

Regards

Moo

A: 

Here's the code to get the color of a pixel on the screen at X,Y coordinates. Since you say your images are one block colors, this should work.

using System;
  using System.Drawing;
  using System.Runtime.InteropServices;

  sealed class Win32
  {
      [DllImport("user32.dll")]
      static extern IntPtr GetDC(IntPtr hwnd);

      [DllImport("user32.dll")]
      static extern Int32 ReleaseDC(IntPtr hwnd, IntPtr hdc);

      [DllImport("gdi32.dll")]
      static extern uint GetPixel(IntPtr hdc, int nXPos, int nYPos);

      static public System.Drawing.Color GetPixelColor(int x, int y)
      {
       IntPtr hdc = GetDC(IntPtr.Zero);
       uint pixel = GetPixel(hdc, x, y);
       ReleaseDC(IntPtr.Zero, hdc);
       Color color = Color.FromArgb((int)(pixel & 0x000000FF),
                    (int)(pixel & 0x0000FF00) >> 8,
                    (int)(pixel & 0x00FF0000) >> 16);
       return color;
      }
   }
Tony
No need to use PInvoke, that I know of: there appears to be equivalent functionality in the managed Bitmap class.
ChrisW
A: 

Try loading the image into a Bitmap instance, and then using the Bitmap.GetPixel method.

ChrisW
+2  A: 

If your images are files on disc, try this:

var image = Image.FromFile(fileName);
var bitmap = new Bitmap(image);
var color = bitmap.GetPixel(0, 0);

This returns a .NET Color object.

David M
+4  A: 

Something like this should work:

Bitmap bmp = new Bitmap ("somefile.jpg");
Color pixelColor = bmp.GetPixel (0, 0);
Tarydon
+5  A: 

I would use Bitmap.GetPixel to get the color and then convert it to hex using ColorTranslator.ToHtml.


// Load the bitmap
Bitmap bitmap = new Bitmap("test.gif");

// Get color from top left corner            
Color color = bitmap.GetPixel(0, 0);

// Convert it to hex
String htmlColor = System.Drawing.ColorTranslator.ToHtml(color);


Petr Havlicek