Convert Rgb Color to Cmyk

How can I convert RGB to CMYK and vice versa in python?

Here's a Python port of a Javascript implementation.

RGB_SCALE = 255
CMYK_SCALE = 100

def rgb_to_cmyk(r, g, b):
if (r, g, b) == (0, 0, 0):
# black
return 0, 0, 0, CMYK_SCALE

# rgb [0,255] -> cmy [0,1]
c = 1 - r / RGB_SCALE
m = 1 - g / RGB_SCALE
y = 1 - b / RGB_SCALE

# extract out k [0, 1]
min_cmy = min(c, m, y)
c = (c - min_cmy) / (1 - min_cmy)
m = (m - min_cmy) / (1 - min_cmy)
y = (y - min_cmy) / (1 - min_cmy)
k = min_cmy

# rescale to the range [0,CMYK_SCALE]
return c * CMYK_SCALE, m * CMYK_SCALE, y * CMYK_SCALE, k * CMYK_SCALE

Is there any way to convert RGB values (0-255) to CMYK value (0-99) in android studio?

Here is a simple class that will convert RGB to CMYK, normal cmyk is from 0.0 to 1.0, just use a scaler to get from 0 to 99. There is no android color converter that I have found native to convert to cmyk.

public class CMYK
{
float cyan = 0.0f;
float magenta = 0.0f;
float yellow = 0.0f;
float black = 0.0f;

public void convertRGBtoCMYK(int r, int g, int b)
{

float _r = (float) (r / 255);
float _g = (float) (g / 255);
float _b = (float) (b / 255);

black = 1.0f - max(_r, _g, _b);

cyan = (1.0f - _r - black) / (1.0f - black);
magenta = (1.0f - _g - black) / (1.0f - black);
yellow = (1.0f - _b - black) / (1.0f - black);
}

private float max(float a, float b, float c)
{
if (a > b && a > c)
return a;
if (b > a && b > c)
return b;
if (c > a && c > b)
return c;

// all equal just return a
return a;
}
}

how to convert RGB or HEX to CMYK

Check this code

function openColor(evt, colorName) {  var i, x, tablinks;  x = document.getElementsByClassName("color");  for (i = 0; i < x.length; i++) {    x[i].style.display = "none";  }  tablinks = document.getElementsByClassName("tablink");  for (i = 0; i < x.length; i++) {    tablinks[i].className = tablinks[i].className.replace(" active", "");  }  document.getElementById(colorName).style.display = "flex";  evt.currentTarget.className += " active";}

function rgb2cmyk (r,g,b) { var computedC = 0; var computedM = 0; var computedY = 0; var computedK = 0;
//remove spaces from input RGB values, convert to int var r = parseInt( (''+r).replace(/\s/g,''),10 ); var g = parseInt( (''+g).replace(/\s/g,''),10 ); var b = parseInt( (''+b).replace(/\s/g,''),10 );
if ( r==null || g==null || b==null || isNaN(r) || isNaN(g)|| isNaN(b) ) { console.log ('Please enter numeric RGB values!'); return; } if (r<0 || g<0 || b<0 || r>255 || g>255 || b>255) { console.log ('RGB values must be in the range 0 to 255.'); return; }
// BLACK if (r==0 && g==0 && b==0) { computedK = 1; return [0,0,0,1]; }
computedC = 1 - (r/255); computedM = 1 - (g/255); computedY = 1 - (b/255);
var minCMY = Math.min(computedC, Math.min(computedM,computedY)); computedC = Math.round((computedC - minCMY) / (1 - minCMY) * 100) ; computedM = Math.round((computedM - minCMY) / (1 - minCMY) * 100) ; computedY = Math.round((computedY - minCMY) / (1 - minCMY) * 100 ); computedK = Math.round(minCMY * 100);
return {c: computedC,m: computedM,y: computedY,k: computedK};}

var colorPicker = new iro.ColorPicker("#color-picker-container", {
width: 200, color: "rgb(255, 0, 0)", borderWidth: 1, borderColor: "#fff",});
let colorHEX = document.getElementById("color-hex");let colorRGB = document.getElementById("color-rgb");let valuesHEX = document.getElementById("values-hex");let valuesRGB = document.getElementById("values-rgb");let colorText = document.querySelectorAll('.change-placeholder p');let colorBtn = document.querySelectorAll('.change-placeholder button');let colorCMYK = document.getElementById("color-cmyk");let valuesCMYK = document.getElementById("values-cmyk");
function showMessage() { //Show message in alert() textbox = document.getElementById('textbox').value; alert(textbox);}colorPicker.on(["color:init", "color:change"], function (color) { colorHEX.style.backgroundColor = color.hexString; valuesHEX.value = color.hexString; colorRGB.style.backgroundColor = color.hexString; valuesRGB.value= color.rgbString;
const { r, g, b } = color.rgb; const { c, m, y, k } = rgb2cmyk(r, g ,b); colorCMYK.style.backgroundColor = color.hexString; valuesCMYK.value = `cmyk(${c}%, ${m}%, ${y}%, ${k}%)`; for( let i=0; i< colorText.length; i++){ colorText[i].style.color = color.rgbString; } for( let i=0; i< colorBtn.length; i++){ colorBtn[i].style.backgroundColor = color.rgbString; } });
 .color-types {  list-style-type: none;  margin: 0;  padding: 0;  text-align: left;}.color-types li {  display: inline-block;  padding: 10px;  border-bottom: 2px solid transparent;  -webkit-transition: border-color 0.6s ease;  transition: border-color 0.6s ease;  cursor: pointer;}.color-types li.active {  color: #82B23E;  border-color: #82B23E;} .color {  border-bottom: 2px solid #000;  display: flex;  padding: 25px 0 10px;  align-items: center;}#color-hex,  #color-rgb, #color-cmyk {  height: 25px;  width: 25px;  border-radius: 50%;  display: inline-block;  cursor: pointer;} #values-hex, #values-rgb, #values-cmyk {  border: none;  outline: none;}
<script src="https://cdn.jsdelivr.net/npm/@jaames/iro/dist/iro.min.js"></script>     <div class="color-scheme-container">                                            <div id="color-scheme-content">                                                <ul class="color-types">                                                    <li class=" tablink active" onclick="openColor(event,'Hex')">HEX                                                    </li>                                                    <li class="tablink" onclick="openColor(event,'Rgb')">RGB</li>                                                    <li class="tablink" onclick="openColor(event,'Cmyk')">CMYK</li>                                                </ul>
<div id="Hex" class="color"> <div id="color-hex"></div> <input type="text" id="values-hex"> <!-- <div id="values-hex"></div> --> <button type="button" onclick="onColorChange()">Update</button> </div><!--hex--> <div id="Rgb" class="color" style="display:none">
<div id="color-rgb"></div> <input type="text" id="values-rgb"> <div id="values-rgb"></div> <button>Update</button> </div><!--rgb-->
<div id="Cmyk" class="color" style="display:none"> <div id="color-cmyk"></div> <input type="text" id="values-cmyk"> <div id="values-cmyk"></div> <button>Update</button> </div><!--cmyk--> <!--color-scheme-content--> <div id="color-picker-container"></div> </div> <!--olor-scheme-content--> </div>

RGB to CMYK Conversion Algorithm

That is simply not true. All RGB colors can be represented as CMYK, but not the opposite. The link you sent works, but it seems the range of the three R, G, B components is [0,255], while the range of the four C, M, Y, K components is [0,1]. This is usual, the RGB coordinates expressed as integers and the CMYK as floating-point numbers. Almost all the algorithms you can find on the web will work like this.

PS: here is a sample implementation of the algorithm, http://www.javascripter.net/faq/rgb2cmyk.htm .

EDIT:

I'm afraid it can be long to explain in detail, but here we go. On one hand, you have the components of each color. On the other hand, you have the display of a certain color on a device. Since each color is physically a function on the wavelength, the RGB representation is a rough approximation of that function.

The problem with that arises when you need to match a certain color on a device. For instance, two screens can show slightly different colors for the same RGB color. To overcome the difficulty of perceptually matching a color with the displayed value on a given device, there exist the so-called color profiles, which specify how the device matches the RGB (or CMYK, or LAB, or whatever color system you use) coordinates with the actual displayed color.

As I understand the situation, the conversion you want to perform involves color profiles. Moreover, when we say RGB we are usually talking about screens, and when we say CMYK we are usually talking about printers (the CMYK components usually specify the amount of ink pigments the printer uses to represent the color). The Wikipedia entry can give you more information on this: https://en.wikipedia.org/wiki/Color_space

Let me finally point out that the conversion you want to perform involves exploring the color profiles associated to the involved devices and is not trivial. However, the first step in RGB->CMYK conversion would be to do a straight conversion with the simple algorithm we discussed first. Then, apply if needed a color correction.

Swift: Convert RGB (UIColor) to CMYK with ICC Profile

You can use NSData to load the profile's data from your bundle.
NSData and CFData are toll-free bridged so can use a NSData instance whenever an API requires aCFData one.

I moved your color conversion method into an extension:

extension UIColor {
func colorComponentsByMatchingToColorSpace(colorSpace: CGColorSpace) -> (c: CGFloat, m: CGFloat, y: CGFloat, k: CGFloat) {
let intent = CGColorRenderingIntent.RenderingIntentPerceptual
let cmykColor = CGColorCreateCopyByMatchingToColorSpace(colorSpace, intent, self.CGColor, nil)
let c: CGFloat = round(CGColorGetComponents(cmykColor)[0] * 100)
let m: CGFloat = round(CGColorGetComponents(cmykColor)[1] * 100)
let y: CGFloat = round(CGColorGetComponents(cmykColor)[2] * 100)
let k: CGFloat = round(CGColorGetComponents(cmykColor)[3] * 100)
return (c, m, y, k)
}
}

To load the .icc file from your bundle and call the extension method you can use the following:

guard let iccProfileURL = NSBundle.mainBundle().resourceURL?.URLByAppendingPathComponent("CoatedGRACoL2006.icc") else {
return;
}
guard let iccProfileData = NSData(contentsOfURL: iccProfileURL) else {
return;
}
guard let colorSpace = CGColorSpaceCreateWithICCProfile(iccProfileData) else {
return;
}
let components = UIColor.redColor().colorComponentsByMatchingToColorSpace(colorSpace);
print("\(components)")

Note that the above loads the profile from your bundle resources and not from the asset catalog. (So you have to make sure that the .icc file is copied into your bundle during the "Copy Bundle Resources" build phase).
If you want to use the asset catalog and you target iOS 9.0 or later, you can look into NSDataAsset.



Related Topics



Leave a reply



Submit