User Tools

Site Tools


macro:rgbtohex

RGBtoHEX

This simple macro exemplifies how to use ImageJ macro functions to convert RGB color values into Hex notation.


Code:
// This simple macro exemplifies how to use ImageJ macro functions to convert RGB color
// values into Hex notation.
//
// After obtaining the RGB tripplet of the current foregound color, the macro prompts
// the user to choose an alpha blending value. Choice is then converted into a four-byte
// hex number (#AARRGGBB) that is copied to the clipboard and can be pasted directly into
// the 'Image>Overlay>Add Selection... [b]' dialog box.
//
// As for RGB values, alpha values range from 0 (fully transparent) to 255 (solid color).
// This wikipedia article on 'web colors' has more information on hex color notation:
// http://en.wikipedia.org/wiki/Web_colors
//
// T.Ferreira, 20010.01
 
    fColor = getValue("color.foreground");
    r = (fColor>>16)&0xff; g = (fColor>>8)&0xff; b = fColor&0xff;
    fColor = ""+r+", "+g+", "+b;
 
    Dialog.create("RGB to Hex");
    Dialog.addString("RGB values (0-255) separated by \",\":", fColor);
    Dialog.addNumber("Opacity value (0-100%):",100);
    Dialog.addMessage("(These values refer to current foreground color)");
    Dialog.show;
    cColor = Dialog.getString;
    cAlpha = Dialog.getNumber;
 
    fColor = split(cColor,",");
    if(fColor.length!=3)
        exit("Invalid input"); 
    r = toHex(fColor[0]); g = toHex(fColor[1]); b = toHex(fColor[2]);
    fAlpha = toHex(255*cAlpha/100);
    hex= "#" + pad(fAlpha) + ""+pad(r) + ""+pad(g) + ""+pad(b);
 
    String.resetBuffer; String.copy(hex);
    showMessage("RGB to Hex", "RGB value:  "+ cColor+" ("+cAlpha+"% Opacity)\n"+
                              "HEX value:  "+ hex +"\n \n"+
                              "(Result has been copied to clipboard)");
 
function pad(n) {
    n = toString(n);
    if(lengthOf(n)==1) n = "0"+n;
    return n;
}
macro/rgbtohex.txt ยท Last modified: 2019/04/12 13:13 by 127.0.0.1

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki