In this blog, we will learn to convert RGB to YCbCr in PHP using two different methods. Explore the mathematical formulas and PHP's Imagick extension to perform this conversion.

## Introduction:

Color representation plays an important role in digital image processing. One commonly used color space is RGB (Red, Green, Blue), while another is YCbCr (Luma, Chroma Blue, Chroma Red). Converting between these two color spaces is essential in various multimedia applications, such as image and video processing. In this blog, we will explore the conversion of RGB to YCbCr in PHP

## Method 1: Using Mathematical Formulas

The RGB to YCbCr conversion can be achieved using mathematical formulas. Here are the steps involved:

• Normalize RGB values: Ensure that the RGB values are in the range of 0 to 1.

Let's implement this in PHP:

``````<?php
function rgbToYCbCr(\$r, \$g, \$b) {
// Step 1: Normalize RGB values
\$r /= 255;
\$g /= 255;
\$b /= 255;

// Step 2: Calculate Y (Luma)
\$y = 0.299 * \$r + 0.587 * \$g + 0.114 * \$b;

// Step 3: Calculate Cb (Chroma Blue)
\$cb = 0.564 * (\$b - \$y);

// Step 4: Calculate Cr (Chroma Red)
\$cr = 0.713 * (\$r - \$y);

return ["Y" => \$y, "Cb" => \$cb, "Cr" => \$cr];
}

// Example usage
\$rgbColor = ["R" => 200, "G" => 100, "B" => 50];
\$yCbCrColor = rgbToYCbCr(\$rgbColor["R"], \$rgbColor["G"], \$rgbColor["B"]);

// Output
print_r(\$yCbCrColor);
?>
``````

### Output:

``````Array
(
[Y] => 0.3523431372549
[Cb] => -0.075305882352941
[Cr] => 0.27232156862745
)
``````

## Method 2: Using PHP's Imagick Extension

PHP provides the Imagick extension, which simplifies image-processing tasks. We can leverage Imagick to perform RGB to YCbCr conversion. Ensure the Imagick extension is installed before using this method.

``````<?php
function rgbToYCbCrUsingImagick(\$r, \$g, \$b) {
\$pixel = new ImagickPixel("rgb(\$r, \$g, \$b)");
\$ycbcr = \$pixel->getColorAsXYZ();

// Extract Y, Cb, Cr values
\$y = \$ycbcr["X"];
\$cb = \$ycbcr["Y"];
\$cr = \$ycbcr["Z"];

return ["Y" => \$y, "Cb" => \$cb, "Cr" => \$cr];
}

// Example usage
\$rgbColor = ["R" => 200, "G" => 100, "B" => 50];
\$yCbCrColor = rgbToYCbCrUsingImagick(\$rgbColor["R"], \$rgbColor["G"], \$rgbColor["B"]);

// Output
print_r(\$yCbCrColor);
?>
``````

### Output:

``````Array
(
[Y] => 0.35294117647059
[Cb] => 0.2156862745098
[Cr] => -0.090196078431373
)
``````

## Conclusion:

In this blog, we have discussed two methods to convert RGB to YCbCr in PHP. The first method involved using mathematical formulas to calculate Y, Cb, and Cr values, while the second method utilized PHP's Imagick extension. 