Given an RGB value what would be the best way to find the closest match in the database?

前端 未结 8 1588
别跟我提以往
别跟我提以往 2020-12-04 17:02

I have a rgb value and if it doesn\'t exist in the color table in my database I need to find the closest color. I was thinking of comparing all values and finding the diffe

8条回答
  •  借酒劲吻你
    2020-12-04 17:22

    Let the database do it for you:

    select top 1
      c.r,
      c.b,
      c.g
    from
      color c
    order by
      (square(c.r - @r) + square(c.g - @g) + square(c.b - @b))
    

    Where @r, @g, and @b are the r,g,b values of the color that you're searching for (SQL Server parameter syntax, since you didn't specify a database). Note that this is still going to have to do a table scan since the order by has a function call in it.

    Note that the extra square root call isn't actually required since it's a monotonic function. Not that it would probably matter very much, but still.

提交回复
热议问题