Several different formats are used to represent color. For example, the primary
ID: 3649108 • Letter: S
Question
Several different formats are used to represent color. For example, the primary format for LCD displays, digital cameras, and web pages, known as the RGB format, specifies the level of red (R), green (G), and blue (B) on an integer scale from 0 to 255. The primary format for publishing books and magazines, known as the CMYK format, specifies the level of cyan (C), magenta (M), yellow (Y), and black (K) on a real scale from 0.0 to 1.0.Write a program RGBtoCMYK.java that converts RGB to CMYK. Read three integers r, g, and b from the command line, and print the equivalent CMYK values. If the RGB values are all 0, then the CMY values are all 0 and the K value is 1; otherwise, use these formulas (also available in Exercise 1.2.32 on page 43 of the SW textbook):
w = max (r / 255, g / 255, b / 255)
c = (w - (r / 255)) / w
m = (w - (g / 255)) / w
y = (w - (b / 255)) / w
k = 1 - w
Hint: Math.max(x, y) returns the maximum of x and y.
> java RGBtoCMYK 75 0 130 // indigo
cyan = 0.423076923076923
magenta = 1.0
yellow = 0.0
black = 0.4901960784313726
Explanation / Answer
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) ) { alert ('Please enter numeric RGB values!'); return; } if (r255) { alert ('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 = (computedC - minCMY) / (1 - minCMY) ; computedM = (computedM - minCMY) / (1 - minCMY) ; computedY = (computedY - minCMY) / (1 - minCMY) ; computedK = minCMY; return [computedC,computedM,computedY,computedK]; }Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.