Idiom #154 Halfway between two hex color codes
Find color c, the average between colors c1, c2.
c, c1, c2 are strings of hex color codes: 7 chars, beginning with a number sign # .
Assume linear computations, ignore gamma corrections.
var buf [7]byte
buf[0] = '#'
for i := 0; i < 3; i++ {
sub1 := c1[1+2*i : 3+2*i]
sub2 := c2[1+2*i : 3+2*i]
v1, _ := strconv.ParseInt(sub1, 16, 0)
v2, _ := strconv.ParseInt(sub2, 16, 0)
v := (v1 + v2) / 2
sub := fmt.Sprintf("%02X", v)
copy(buf[1+2*i:3+2*i], sub)
}
c := string(buf[:])
r1, _ := strconv.ParseInt(c1[1:3], 16, 0)
r2, _ := strconv.ParseInt(c2[1:3], 16, 0)
r := (r1 + r2) / 2
g1, _ := strconv.ParseInt(c1[3:5], 16, 0)
g2, _ := strconv.ParseInt(c2[3:5], 16, 0)
g := (g1 + g2) / 2
b1, _ := strconv.ParseInt(c1[5:7], 16, 0)
b2, _ := strconv.ParseInt(c2[5:7], 16, 0)
b := (b1 + b2) / 2
c := fmt.Sprintf("#%02X%02X%02X", r, g, b)
String r1 = c1.substring(1,3);
String g1 = c1.substring(3,5);
String b1 = c1.substring(5,7);
String r2 = c2.substring(1,3);
String g2 = c2.substring(3,5);
String b2 = c2.substring(5,7);
String r = String.format("%02X", (Integer.parseInt(r1, 16)+Integer.parseInt(r2, 16))/2 );
String g = String.format("%02X", (Integer.parseInt(g1, 16)+Integer.parseInt(g2, 16))/2 );
String b = String.format("%02X", (Integer.parseInt(b1, 16)+Integer.parseInt(b2, 16))/2 );
String c = "#" + r + g + b;
StringBuilder sb = new StringBuilder("#");
for(int i=0;i<3;i++) {
String sub1 = c1.substring(1+2*i,3+2*i);
String sub2 = c2.substring(1+2*i,3+2*i);
int v1 = Integer.parseInt(sub1, 16);
int v2 = Integer.parseInt(sub2, 16);
int v = (v1 + v2)/2;
String sub = String.format("%02X", v);
sb.append(sub);
}
String c = sb.toString();
class RGB {
int r, g, b;
RGB(int x) {
r = (x & 0xff_00_00) >> 16;
g = (x & 0x00_ff_00) >> 8;
b = x & 0x00_00_ff;
}
RGB(String s) {
this(parseInt(s.substring(1), 16));
}
static int average(RGB a, RGB b) {
int R = (a.r + b.r) / 2,
G = (a.g + b.g) / 2,
B = (a.b + b.b) / 2;
return (R << 16) + (G << 8) + B;
}
}
var
c1, c2: string;
RGB1, RGB2: LongInt;
R1, G1, B1, R2, G2, B2: Byte;
c: TColor;
begin
RGB1 := ColorToRGB(StrToInt(StringReplace(c1,'#','$',[])));
RGB1 := ColorToRGB(StrToInt(StringReplace(c2,'#','$',[])));
RedGreenBlue(RGB1, R1, G1, B1);
RedGreenBlue(RGB2, R2, G2, B2);
c := RGBToColor(R1+R2 div 2, G1+G2 div 2, B1+B2 div 2);
end.
class RGB(numpy.ndarray):
@classmethod
def from_str(cls, rgbstr):
return numpy.array([
int(rgbstr[i:i+2], 16)
for i in range(1, len(rgbstr), 2)
]).view(cls)
def __str__(self):
self = self.astype(numpy.uint8)
return '#' + ''.join(format(n, 'x') for n in self)
c1 = RGB.from_str('#a1b1c1')
print(c1)
c2 = RGB.from_str('#1A1B1C')
print(c2)
print((c1 + c2) / 2)