Using PHP to grab a simplified colour palette from an image? - php

So far I have found examples on how to grab all the RGB values of each pixel in an image but I want something that will break down an image and give me a simplified color palette.
Is there a way to use imagetruecolortopalette to somehow spit out the reduced palette colours, or to break an image into 25 x 25 blocks and then grab the average value of that block?
Maybe there is an alternative I'm missing? I basically just want to be able to find the most common colors within an image.
Thanks in advance.

Hmm, well I have had created something like this for a client. The screenshot is below
The complete code is as follows
$microTime = microtime(true);
function textColor($R1, $G1, $B1) {
$a = (($R1 * 299) + ($G1 * 587 ) + ($B1 * 114 )) / 1000;
if ($a < 128)
return 'white';
else
return 'black';
}
function rgb2html($r, $g = -1, $b = -1) {
$hex = "#";
$hex.= str_pad(dechex($r), 2, "0", STR_PAD_LEFT);
$hex.= str_pad(dechex($g), 2, "0", STR_PAD_LEFT);
$hex.= str_pad(dechex($b), 2, "0", STR_PAD_LEFT);
return $hex;
if (is_array($r) && sizeof($r) == 3)
list($r, $g, $b) = $r;
$r = intval($r);
$g = intval($g);
$b = intval($b);
$r = dechex($r < 0 ? 0 : ($r > 255 ? 255 : $r));
$g = dechex($g < 0 ? 0 : ($g > 255 ? 255 : $g));
$b = dechex($b < 0 ? 0 : ($b > 255 ? 255 : $b));
$color = (strlen($r) < 2 ? '0' : '') . $r;
$color .= (strlen($g) < 2 ? '0' : '') . $g;
$color .= (strlen($b) < 2 ? '0' : '') . $b;
return '#' . $color;
}
function colorPalette($imageFile, $colorJump, $granularity = 5) {
$granularity = max(1, abs((int) $granularity));
$colors = array();
$ratio = array();
$wastageCount = array();
$occurrenceSCount = array();
$occurrenceMCount = array();
$size = #getimagesize($imageFile);
if ($size === false) {
return false;
}
$img = #imagecreatefromstring(file_get_contents($imageFile));
if (!$img) {
user_error("Unable to open image file");
return false;
}
for ($y = 0; $y < $size[1]; $y += $granularity) {
$lastColor = NULL;
$lastX = -1;
for ($x = 0; $x < $size[0]; $x += $granularity) {
$thisColor = imagecolorat($img, $x, $y);
$rgb = imagecolorsforindex($img, $thisColor);
$red = round(round(($rgb['red'] / $colorJump)) * $colorJump);
$green = round(round(($rgb['green'] / $colorJump)) * $colorJump);
$blue = round(round(($rgb['blue'] / $colorJump)) * $colorJump);
$thisRGB = $red . ',' . $green . ',' . $blue;
if ($lastColor != $thisRGB) {
if (array_key_exists($thisRGB, $wastageCount)) {
$wastageCount[$thisRGB]++;
} else {
$wastageCount[$thisRGB] = 1;
}
if ($lastX + 1 == $x) {
if (array_key_exists($lastColor, $occurrenceSCount)) {
$occurrenceSCount[$lastColor]++;
} else {
$occurrenceSCount[$lastColor] = 1;
}
}
if ($lastX + 1 != $x) {
if (array_key_exists($lastColor, $occurrenceMCount)) {
$occurrenceMCount[$lastColor]++;
} else {
$occurrenceMCount[$lastColor] = 1;
}
}
$lastColor = $thisRGB;
$lastX = $x;
}
if (array_key_exists($thisRGB, $colors)) {
$colors[$thisRGB]++;
} else {
$colors[$thisRGB] = 1;
}
}
}
$totalPixels = array_sum($colors);
foreach ($colors as $k => $v) {
$ratio[$k] = round(($v / $totalPixels ) * 100, 2);
}
return array($ratio, $wastageCount, $colors, $occurrenceSCount, $occurrenceMCount);
}
usage
$colorJump = 1;
$pixelJump = 1;
$paletteR = colorPalette($dbImgFile_dir, $colorJump, $pixelJump);
$palette = $paletteR[0];
$wastage = $paletteR[1];
$colorsFound = $paletteR[2];
$occSArray = $paletteR[3];
$occMArray = $paletteR[4];
$totalPixels = array_sum($colorsFound);
$totalTime = abs(microtime(true) - $microTime);
the looping around is more complex, as I have to get the pallet from the DB and to match the colors with them, and also the template parser is used which is full custom code, and will not help you.
Just ignore the Required Weight column from this, the single occurrences and multiple occurrences are calculated, if there is a single pixel, for example RED, RED, BLUE, RED, RED it will be 1 single occurrence and 2 multiple occurrence

Related

Pie chart problem does not show if data is missing

I have a PHP pie chart which uses data from Mysql to show the chart. However if one data is missing the whole chart turns to one color. For example for grading if the input is A, B, D and F(pay attention C grade input is missing) then the whole pie chart is in one color like Orange or red.
Can you please help me with this? Thanks
<?php
$show_label = true; // true = show label, false = don't show label.
$show_percent = true; // true = show percentage, false = don't show percentage.
$show_text = true; // true = show text, false = don't show text.
$show_parts = false; // true = show parts, false = don't show parts.
$label_form = 'square'; // 'square' or 'round' label.
$width = 199;
$background_color = 'FFFFFF'; // background-color of the chart...
$text_color = '000000'; // text-color.
$colors = array('0000ff', '006600', 'ffff00','DD7C1D', 'FF3300', 'CC6600','990000','520000','BFBFC1','808080'); // colors of the slices.
$shadow_height = 16; // Height on shadown.
$shadow_dark = true; // true = darker shadow, false = lighter shadow...
// DON'T CHANGE ANYTHING BELOW THIS LINE...
$data = $_GET["data"];
$label = $_GET["label"];
$height = $width/2;
$data = array_filter(explode('*',$data));
if ($label != '') $label = explode('*',$label);
for ($i = 0; $i < count($label); $i++)
{
if ($data[$i]/array_sum($data) < 0.1) $number[$i] = ' '.number_format(($data[$i]/array_sum($data))*100,1,',','.').'%';
else $number[$i] = number_format(($data[$i]/array_sum($data))*100,1,',','.').'%';
if (strlen($label[$i]) > $text_length) $text_length = strlen($label[$i]);
}
if (is_array($label))
{
$antal_label = count($label);
$xtra = (5+15*$antal_label)-($height+ceil($shadow_height));
if ($xtra > 0) $xtra_height = (5+15*$antal_label)-($height+ceil($shadow_height));
$xtra_width = 5;
if ($show_label) $xtra_width += 20;
if ($show_percent) $xtra_width += 45;
if ($show_text) $xtra_width += $text_length*8;
if ($show_parts) $xtra_width += 35;
}
$img = ImageCreateTrueColor($width+$xtra_width, $height+ceil($shadow_height)+$xtra_height);
ImageFill($img, 0, 0, colorHex($img, $background_color));
foreach ($colors as $colorkode)
{
$fill_color[] = colorHex($img, $colorkode);
$shadow_color[] = colorHexshadow($img, $colorkode, $shadow_dark);
}
$label_place = 5;
if (is_array($label))
{
for ($i = 0; $i < count($label); $i++)
{
if ($label_form == 'round' && $show_label)
{
imagefilledellipse($img,$width+11,$label_place+5,10,10,colorHex($img, $colors[$i % count($colors)]));
imageellipse($img,$width+11,$label_place+5,10,10,colorHex($img, $text_color));
}
else if ($label_form == 'square' && $show_label)
{
imagefilledrectangle($img,$width+6,$label_place,$width+16,$label_place+10,colorHex($img, $colors[$i % count($colors)]));
imagerectangle($img,$width+6,$label_place,$width+16,$label_place+10,colorHex($img, $text_color));
}
if ($show_percent) $label_output = $number[$i].' ';
if ($show_text) $label_output = $label_output.$label[$i].' ';
if ($show_parts) $label_output = $label_output.$data[$i];
imagestring($img,'2',$width+20,$label_place,$label_output,colorHex($img, $text_color));
$label_output = '';
$label_place = $label_place + 15;
}
}
$centerX = round($width/2);
$centerY = round($height/2);
$diameterX = $width-4;
$diameterY = $height-4;
$data_sum = array_sum($data);
$start = 270;
for ($i = 0; $i < count($data); $i++)
{
$value += $data[$i];
$end = ceil(($value/$data_sum)*360) + 270;
$slice[] = array($start, $end, $shadow_color[$value_counter % count($shadow_color)], $fill_color[$value_counter % count($fill_color)]);
$start = $end;
$value_counter++;
}
for ($i=$centerY+$shadow_height; $i>$centerY; $i--)
{
for ($j = 0; $j < count($slice); $j++)
{
ImageFilledArc($img, $centerX, $i, $diameterX, $diameterY, $slice[$j][0], $slice[$j][1], $slice[$j][2], IMG_ARC_PIE);
}
}
for ($j = 0; $j < count($slice); $j++)
{
ImageFilledArc($img, $centerX, $centerY, $diameterX, $diameterY, $slice[$j][0], $slice[$j][1], $slice[$j][3], IMG_ARC_PIE);
}
OutputImage($img);
ImageDestroy($img);
function colorHex($img, $HexColorString)
{
$R = hexdec(substr($HexColorString, 0, 2));
$G = hexdec(substr($HexColorString, 2, 2));
$B = hexdec(substr($HexColorString, 4, 2));
return ImageColorAllocate($img, $R, $G, $B);
}
function colorHexshadow($img, $HexColorString, $mork)
{
$R = hexdec(substr($HexColorString, 0, 2));
$G = hexdec(substr($HexColorString, 2, 2));
$B = hexdec(substr($HexColorString, 4, 2));
if ($mork)
{
($R > 99) ? $R -= 100 : $R = 0;
($G > 99) ? $G -= 100 : $G = 0;
($B > 99) ? $B -= 100 : $B = 0;
}
else
{
($R < 220) ? $R += 35 : $R = 255;
($G < 220) ? $G += 35 : $G = 255;
($B < 220) ? $B += 35 : $B = 255;
}
return ImageColorAllocate($img, $R, $G, $B);
}
function OutputImage($img)
{
header('Content-type: image/jpg');
ImageJPEG($img,NULL,100);
}
?>

Piechart creation in pdf file using fpdf in php

I want to create piechart in my pdf file created using fpdf. already i had created pdf with fpdf . then i want to create pie chart in that using same table data, is there any option to create pie chart using fpdf ?
Please Help.
Thanks in advance
Try this make changes in code as per your requirements:
You can display following view file on your pdf using pdf helper.
you can use dom pdf helper download it from following link.
http://code.google.com/p/dompdf/downloads/detail?name=dompdf_0-6-0_beta3.zip
<?php
$show_label = true; // true = show label, false = don't show label.
$show_percent = true; // true = show percentage, false = don't show percentage.
$show_text = true; // true = show text, false = don't show text.
$show_parts = false; // true = show parts, false = don't show parts.
$label_form = 'square'; // 'square' or 'round' label.
$width = 199;
$background_color = 'FFFFFF'; // background-color of the chart...
$text_color = '000000'; // text-color.
$colors = array('003366', 'CCD6E0', '7F99B2','F7EFC6', 'C6BE8C', 'CC6600','990000','520000','BFBFC1','808080'); // colors of the slices.
$shadow_height = 16; // Height on shadown.
$shadow_dark = true; // true = darker shadow, false = lighter shadow...
// DON'T CHANGE ANYTHING BELOW THIS LINE...
$data = $_GET["data"];
$label = $_GET["label"];
$height = $width/2;
$data = explode('*',$data);
if ($label != '') $label = explode('*',$label);
for ($i = 0; $i < count($label); $i++)
{
if ($data[$i]/array_sum($data) < 0.1) $number[$i] = ' '.number_format(($data[$i]/array_sum($data))*100,1,',','.').'%';
else $number[$i] = number_format(($data[$i]/array_sum($data))*100,1,',','.').'%';
if (strlen($label[$i]) > $text_length) $text_length = strlen($label[$i]);
}
if (is_array($label))
{
$antal_label = count($label);
$xtra = (5+15*$antal_label)-($height+ceil($shadow_height));
if ($xtra > 0) $xtra_height = (5+15*$antal_label)-($height+ceil($shadow_height));
$xtra_width = 5;
if ($show_label) $xtra_width += 20;
if ($show_percent) $xtra_width += 45;
if ($show_text) $xtra_width += $text_length*8;
if ($show_parts) $xtra_width += 35;
}
$img = ImageCreateTrueColor($width+$xtra_width, $height+ceil($shadow_height)+$xtra_height);
ImageFill($img, 0, 0, colorHex($img, $background_color));
foreach ($colors as $colorkode)
{
$fill_color[] = colorHex($img, $colorkode);
$shadow_color[] = colorHexshadow($img, $colorkode, $shadow_dark);
}
$label_place = 5;
if (is_array($label))
{
for ($i = 0; $i < count($label); $i++)
{
if ($label_form == 'round' && $show_label && $data[$i] > 0)
{
imagefilledellipse($img,$width+11,$label_place+5,10,10,colorHex($img, $colors[$i % count($colors)]));
imageellipse($img,$width+11,$label_place+5,10,10,colorHex($img, $text_color));
}
else if ($label_form == 'square' && $show_label && $data[$i] > 0)
{
imagefilledrectangle($img,$width+6,$label_place,$width+16,$label_place+10,colorHex($img, $colors[$i % count($colors)]));
imagerectangle($img,$width+6,$label_place,$width+16,$label_place+10,colorHex($img, $text_color));
}
if ($data[$i] > 0)
{
if ($show_percent) $label_output = $number[$i].' ';
if ($show_text) $label_output = $label_output.$label[$i].' ';
if ($show_parts) $label_output = $label_output.$data[$i];
imagestring($img,'2',$width+20,$label_place,$label_output,colorHex($img, $text_color));
$label_output = '';
$label_place = $label_place + 15;
}
}
}
$centerX = round($width/2);
$centerY = round($height/2);
$diameterX = $width-4;
$diameterY = $height-4;
$data_sum = array_sum($data);
$start = 270;
for ($i = 0; $i < count($data); $i++)
{
$value += $data[$i];
$end = ceil(($value/$data_sum)*360) + 270;
$slice[] = array($start, $end, $shadow_color[$value_counter % count($shadow_color)], $fill_color[$value_counter % count($fill_color)]);
$start = $end;
$value_counter++;
}
for ($i=$centerY+$shadow_height; $i>$centerY; $i--)
{
for ($j = 0; $j < count($slice); $j++)
{
if ($slice[$j][0] != $slice[$j][1]) ImageFilledArc($img, $centerX, $i, $diameterX, $diameterY, $slice[$j][0], $slice[$j][1], $slice[$j][2], IMG_ARC_PIE);
}
}
for ($j = 0; $j < count($slice); $j++)
{
if ($slice[$j][0] != $slice[$j][1]) ImageFilledArc($img, $centerX, $centerY, $diameterX, $diameterY, $slice[$j][0], $slice[$j][1], $slice[$j][3], IMG_ARC_PIE);
}
OutputImage($img);
ImageDestroy($img);
function colorHex($img, $HexColorString)
{
$R = hexdec(substr($HexColorString, 0, 2));
$G = hexdec(substr($HexColorString, 2, 2));
$B = hexdec(substr($HexColorString, 4, 2));
return ImageColorAllocate($img, $R, $G, $B);
}
function colorHexshadow($img, $HexColorString, $mork)
{
$R = hexdec(substr($HexColorString, 0, 2));
$G = hexdec(substr($HexColorString, 2, 2));
$B = hexdec(substr($HexColorString, 4, 2));
if ($mork)
{
($R > 99) ? $R -= 100 : $R = 0;
($G > 99) ? $G -= 100 : $G = 0;
($B > 99) ? $B -= 100 : $B = 0;
}
else
{
($R < 220) ? $R += 35 : $R = 255;
($G < 220) ? $G += 35 : $G = 255;
($B < 220) ? $B += 35 : $B = 255;
}
return ImageColorAllocate($img, $R, $G, $B);
}
function OutputImage($img)
{
header('Content-type: image/jpg');
ImageJPEG($img,NULL,100);
}
?>
Hope this will help you... :)

How to detect "light" colors with PHP

I am working on a dynamic store project and I use a loop to print all color options for a product as color boxes, however I really need to add a "border" to these colors which are light. I tried something like the following but It is very limited, it is actually limited to white color only, it won't catch something like #ddd, #eea... etc
Here is my loop:
foreach($colors as $color) {
$color = trim($color);
if (!empty($color)) {
if (in_array($color, array('white','White','#fff','#FFF','#FFFFFF','#ffffff'))) {
$bordercolor = '#bbb';
} else {
$bordercolor = $color;
}
}
}
Colors is an array from backend like: White, #000, #cc0000, etc. It is not practical to add all exceptions in the if/else condition too, any quick idea?
Transform HTML colour to RGB, then to Hue-Saturation-Lightnes (HSV)
<?php
function HTMLToRGB($htmlCode)
{
if($htmlCode[0] == '#')
$htmlCode = substr($htmlCode, 1);
if (strlen($htmlCode) == 3)
{
$htmlCode = $htmlCode[0] . $htmlCode[0] . $htmlCode[1] . $htmlCode[1] . $htmlCode[2] . $htmlCode[2];
}
$r = hexdec($htmlCode[0] . $htmlCode[1]);
$g = hexdec($htmlCode[2] . $htmlCode[3]);
$b = hexdec($htmlCode[4] . $htmlCode[5]);
return $b + ($g << 0x8) + ($r << 0x10);
}
function RGBToHSL($RGB) {
$r = 0xFF & ($RGB >> 0x10);
$g = 0xFF & ($RGB >> 0x8);
$b = 0xFF & $RGB;
$r = ((float)$r) / 255.0;
$g = ((float)$g) / 255.0;
$b = ((float)$b) / 255.0;
$maxC = max($r, $g, $b);
$minC = min($r, $g, $b);
$l = ($maxC + $minC) / 2.0;
if($maxC == $minC)
{
$s = 0;
$h = 0;
}
else
{
if($l < .5)
{
$s = ($maxC - $minC) / ($maxC + $minC);
}
else
{
$s = ($maxC - $minC) / (2.0 - $maxC - $minC);
}
if($r == $maxC)
$h = ($g - $b) / ($maxC - $minC);
if($g == $maxC)
$h = 2.0 + ($b - $r) / ($maxC - $minC);
if($b == $maxC)
$h = 4.0 + ($r - $g) / ($maxC - $minC);
$h = $h / 6.0;
}
$h = (int)round(255.0 * $h);
$s = (int)round(255.0 * $s);
$l = (int)round(255.0 * $l);
return (object) Array('hue' => $h, 'saturation' => $s, 'lightness' => $l);
}
$colour = '#F12346';
$rgb = HTMLToRGB($colour);
$hsl = RGBToHSL($rgb);
var_dump($hsl);
Usage:
$colour = '#F12346';
$rgb = HTMLToRGB($colour);
$hsl = RGBToHSL($rgb);
if($hsl->lightness > 200) {
// this is light colour!
}
Source:
http://www.caperna.org/computing/repository/hsl-rgb-color-conversion-php
Demo:
http://codepad.org/X7KV4n4n
What I'd do in this situation is detect the lightness of the color using HSL, and compare that against a certain percentage. For example, the lightness attribute in the HSL algorithm takes the chroma (M - m where M is the largest RGB value and m is the smallest RGB value) and divides that by 2.
function lightness($R = 255, $G = 255, $B = 255) {
return (max($R, $G, $B) + min($R, $G, $B)) / 510.0; // HSL algorithm
}
The above function would return a percentage of how light the color you've selected is (simple hex -> rgb conversions are required for this also, but that should be pretty easy). The reason I divided by 510 instead of 2 is because in order to get the percentage after dividing by 2, you divide by 255. To make it faster you can simply say: (x / 2) / 255 = x / 510. Then I'd compare the value returned by the above function to, say, 80%.
$r = hexdec($hex[0].$hex[1]);
$g = hexdec($hex[2].$hex[3]);
$b = hexdec($hex[4].$hex[5]);
if(lightness($r, $g, $b) >= .8) {
// add border
} else {
// no border
}
In addition to other formulas given by other answers, you may want to consider Luma.
function luma($r, $g, $b)
{
return (0.2126 * $r + 0.7152 * $g + 0.0722 * $b) / 255;
}
$l = luma(0, 15, 255);
Values closer to 0 will be darker. Values closer to 1 will be lighter.
Short way if you have RGB color as hexadecimal string:
$hexRGB = "4488BB";
if(hexdec(substr($hexRGB,0,2))+hexdec(substr($hexRGB,2,2))+hexdec(substr($hexRGB,4,2))> 381){
//bright color
}else{
//dark color
}
Note: The thereshold 381 is the sum of the values at average level. If you want the thereshold to be lighter or darker, upper or lower 381 in the range 1 - 765.
There also is a simpler way with even less code:
<?php
//Functions
function getRGB($colorCode) {
//Turn html color code into RGB
$var_R = substr($colorCode, 0, 2);
$var_G = substr($colorCode, 2, 2);
$var_B = substr($colorCode, 4, 2);
//Get Hex values
$val_R = hexdec($var_R);
$val_G = hexdec($var_G);
$val_B = hexdec($var_B);
//Red is seen as light too, gets fixed with this
$remRed = hexdec('99');
if ($val_R > $remRed) {
$RGB = $val_G.' '.$val_B;
} else {
$RGB = $val_R.' '.$val_G.' '.$val_B;
}
return $RGB;
}
function getHSL($R = 255, $G = 255, $B = 255) {
$hsl = (max($R, $G, $B) + min($R, $G, $B)) / 510.0;
return $hsl;
}
?>
Now the calling:
$color = 0000FF; //Blue
$RGBcode = getRGB($color); //Returns 0 0 255
$RGBcode = str_replace(' ', ', ', $RGBcode); //Replaces an empty space with a ,
$val_HSL = getHSL($RGBcode); //Returns value from 0.5 to 1
if ($val_HSL >= 0.8) {
//Reject color
} else {
//Accept Color
$color = '#'.$color; //Sets it to html: #0000FF
}
Here’s a short derived version from #Luca C.’s answer for colors in HEX format (e.g. #FFFFFF or #FFF)
<?php
function isDark($hex){
$average = 381; // range 1 - 765
if(strlen(trim($hex)) == 4){
$hex = "#" . substr($hex,1,1) . substr($hex,1,1) . substr($hex,2,1) . substr($hex,2,1) . substr($hex,3,1) . substr($hex,3,1);
}
return ((hexdec(substr($hex,1,2))+hexdec(substr($hex,3,2))+hexdec(substr($hex,5,2)) < $average) ? true : false);
}
var_dump( isDark("#000000") ); // bool(true)
?>

Get Image From PHP using Cocoa-Touch

I got this php code.. that creates a pie Chart
when you go to the site: http://localhost/social/Test.php?data=100*200*100
How do i get this image from the php file to my Xcode project?
When you enter the site the image will download
But when you enter the site on the iPhone the image will only show
<?php
$show_label = true; // true = show label, false = don't show label.
$show_percent = true; // true = show percentage, false = don't show percentage.
$show_text = true; // true = show text, false = don't show text.
$show_parts = false; // true = show parts, false = don't show parts.
$label_form = 'square'; // 'square' or 'round' label.
$width = 199;
$background_color = 'FFFFFF'; // background-color of the chart...
$text_color = '000000'; // text-color.
$colors = array('003366', 'CCD6E0', '7F99B2','F7EFC6', 'C6BE8C', 'CC6600','990000','520000','BFBFC1','808080'); // colors of the slices.
$shadow_height = 16; // Height on shadown.
$shadow_dark = true; // true = darker shadow, false = lighter shadow...
// DON'T CHANGE ANYTHING BELOW THIS LINE...
$data = $_GET["data"];
$label = $_GET["label"];
$height = $width/2;
$data = explode('*',$data);
if ($label != '') $label = explode('*',$label);
for ($i = 0; $i < count($label); $i++)
{
if ($data[$i]/array_sum($data) < 0.1) $number[$i] = ' '.number_format(($data[$i]/array_sum($data))*100,1,',','.').'%';
else $number[$i] = number_format(($data[$i]/array_sum($data))*100,1,',','.').'%';
if (strlen($label[$i]) > $text_length) $text_length = strlen($label[$i]);
}
if (is_array($label))
{
$antal_label = count($label);
$xtra = (5+15*$antal_label)-($height+ceil($shadow_height));
if ($xtra > 0) $xtra_height = (5+15*$antal_label)-($height+ceil($shadow_height));
$xtra_width = 5;
if ($show_label) $xtra_width += 20;
if ($show_percent) $xtra_width += 45;
if ($show_text) $xtra_width += $text_length*8;
if ($show_parts) $xtra_width += 35;
}
$img = ImageCreateTrueColor($width+$xtra_width, $height+ceil($shadow_height)+$xtra_height);
ImageFill($img, 0, 0, colorHex($img, $background_color));
foreach ($colors as $colorkode)
{
$fill_color[] = colorHex($img, $colorkode);
$shadow_color[] = colorHexshadow($img, $colorkode, $shadow_dark);
}
$label_place = 5;
if (is_array($label))
{
for ($i = 0; $i < count($label); $i++)
{
if ($label_form == 'round' && $show_label && $data[$i] > 0)
{
imagefilledellipse($img,$width+11,$label_place+5,10,10,colorHex($img, $colors[$i % count($colors)]));
imageellipse($img,$width+11,$label_place+5,10,10,colorHex($img, $text_color));
}
else if ($label_form == 'square' && $show_label && $data[$i] > 0)
{
imagefilledrectangle($img,$width+6,$label_place,$width+16,$label_place+10,colorHex($img, $colors[$i % count($colors)]));
imagerectangle($img,$width+6,$label_place,$width+16,$label_place+10,colorHex($img, $text_color));
}
if ($data[$i] > 0)
{
if ($show_percent) $label_output = $number[$i].' ';
if ($show_text) $label_output = $label_output.$label[$i].' ';
if ($show_parts) $label_output = $label_output.$data[$i];
imagestring($img,'2',$width+20,$label_place,$label_output,colorHex($img, $text_color));
$label_output = '';
$label_place = $label_place + 15;
}
}
}
$centerX = round($width/2);
$centerY = round($height/2);
$diameterX = $width-4;
$diameterY = $height-4;
$data_sum = array_sum($data);
$start = 270;
for ($i = 0; $i < count($data); $i++)
{
$value += $data[$i];
$end = ceil(($value/$data_sum)*360) + 270;
$slice[] = array($start, $end, $shadow_color[$value_counter % count($shadow_color)], $fill_color[$value_counter % count($fill_color)]);
$start = $end;
$value_counter++;
}
for ($i=$centerY+$shadow_height; $i>$centerY; $i--)
{
for ($j = 0; $j < count($slice); $j++)
{
if ($slice[$j][0] != $slice[$j][1]) ImageFilledArc($img, $centerX, $i, $diameterX, $diameterY, $slice[$j][0], $slice[$j][1], $slice[$j][2], IMG_ARC_PIE);
}
}
for ($j = 0; $j < count($slice); $j++)
{
if ($slice[$j][0] != $slice[$j][1]) ImageFilledArc($img, $centerX, $centerY, $diameterX, $diameterY, $slice[$j][0], $slice[$j][1], $slice[$j][3], IMG_ARC_PIE);
}
OutputImage($img);
ImageDestroy($img);
function colorHex($img, $HexColorString)
{
$R = hexdec(substr($HexColorString, 0, 2));
$G = hexdec(substr($HexColorString, 2, 2));
$B = hexdec(substr($HexColorString, 4, 2));
return ImageColorAllocate($img, $R, $G, $B);
}
function colorHexshadow($img, $HexColorString, $mork)
{
$R = hexdec(substr($HexColorString, 0, 2));
$G = hexdec(substr($HexColorString, 2, 2));
$B = hexdec(substr($HexColorString, 4, 2));
if ($mork)
{
($R > 99) ? $R -= 100 : $R = 0;
($G > 99) ? $G -= 100 : $G = 0;
($B > 99) ? $B -= 100 : $B = 0;
}
else
{
($R < 220) ? $R += 35 : $R = 255;
($G < 220) ? $G += 35 : $G = 255;
($B < 220) ? $B += 35 : $B = 255;
}
return ImageColorAllocate($img, $R, $G, $B);
}
function OutputImage($img)
{
header('Content-type: image/jpg');
ImageJPEG($img,NULL,100);
}
?>
please do a post request form php server to your app, convert the image to base64 encoding and pass this as a string, then save this file as .jpg or .png etc as required.
Thanks
djrecker
Retrieve the image data via dataWithContentsOfUrl and then either
Use imageWithData to get your UIImage; or
Write the NSData to a file with writeToFile and then you can later retrieve the image via imageWithContentsOfFile
Note, you'll have to put that PHP code on a web server accessible by the iPhone (as obviously localhost won't work). So, it might look like (I've replaced your localhost reference with host.com ... you'll have to replace that with the URL of the web site you put your PHP code on):
NSString *urlString = #"http://host.com/social/Test.php?data=100*200*100";
NSURL *url = [NSURL URLWithString:urlString];
NSError *err;
NSData *imageData = [NSData dataWithContentsOfURL:url options:0 error:&err];
NSAssert(imageData, #"Unable to retrieve image");
Now you can use that image:
self.imageView.image = [UIImage imageWithData:imageData];
Or, alternatively, now you can write it to a file on your iPhone, too, if you want:
NSString *documentsFolder = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *documentFullPath = [documentsFolder stringByAppendingPathComponent:#"pie.jpg"]; // I noticed from the php source that this is a jpg
BOOL success = [imageData writeToFile:documentFullPath options:0 error:&err];
NSAssert(success, #"Unable to write file");
Which you can retrieve later:
self.imageView.image = [UIImage imageWithContentsOfFile:documentFullPath];
Note, this is an inefficient way to draw a pie chart in iOS (to have php server generate jpg that you then download, requiring Internet connection and download at 3G speeds if you're not on wifi, etc.). I'd probably do something with Core Graphics or grab one of the various charting/graphing APIs out there. If you google "ios 3d pie chart" you'll get a bunch of hits. This one looks pretty cool, though I've never tried it.

Face detection in PHP

Does anybody know of a good way to do face detection in PHP? I came across some code here that claims to do this, but I can't seem to get it to work properly. I'd like to make this work (even though it will be slow) and any help you can give me would be really appreciated.
Here's the code from the link:
<?php
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
// #Author Karthik Tharavaad
// karthik_tharavaad#yahoo.com
// #Contributor Maurice Svay
// maurice#svay.Com
class Face_Detector {
protected $detection_data;
protected $canvas;
protected $face;
private $reduced_canvas;
public function __construct($detection_file = 'detection.dat') {
if (is_file($detection_file)) {
$this->detection_data = unserialize(file_get_contents($detection_file));
} else {
throw new Exception("Couldn't load detection data");
}
//$this->detection_data = json_decode(file_get_contents('data.js'));
}
public function face_detect($file) {
if (!is_file($file)) {
throw new Exception("Can not load $file");
}
$this->canvas = imagecreatefromjpeg($file);
$im_width = imagesx($this->canvas);
$im_height = imagesy($this->canvas);
//Resample before detection?
$ratio = 0;
$diff_width = 320 - $im_width;
$diff_height = 240 - $im_height;
if ($diff_width > $diff_height) {
$ratio = $im_width / 320;
} else {
$ratio = $im_height / 240;
}
if ($ratio != 0) {
$this->reduced_canvas = imagecreatetruecolor($im_width / $ratio, $im_height / $ratio);
imagecopyresampled($this->reduced_canvas, $this->canvas, 0, 0, 0, 0, $im_width / $ratio, $im_height / $ratio, $im_width, $im_height);
$stats = $this->get_img_stats($this->reduced_canvas);
$this->face = $this->do_detect_greedy_big_to_small($stats['ii'], $stats['ii2'], $stats['width'], $stats['height']);
$this->face['x'] *= $ratio;
$this->face['y'] *= $ratio;
$this->face['w'] *= $ratio;
} else {
$stats = $this->get_img_stats($this->canvas);
$this->face = $this->do_detect_greedy_big_to_small($stats['ii'], $stats['ii2'], $stats['width'], $stats['height']);
}
return ($this->face['w'] > 0);
}
public function toJpeg() {
$color = imagecolorallocate($this->canvas, 255, 0, 0); //red
imagerectangle($this->canvas, $this->face['x'], $this->face['y'], $this->face['x']+$this->face['w'], $this->face['y']+ $this->face['w'], $color);
header('Content-type: image/jpeg');
imagejpeg($this->canvas);
}
public function toJson() {
return "{'x':" . $this->face['x'] . ", 'y':" . $this->face['y'] . ", 'w':" . $this->face['w'] . "}";
}
public function getFace() {
return $this->face;
}
protected function get_img_stats($canvas){
$image_width = imagesx($canvas);
$image_height = imagesy($canvas);
$iis = $this->compute_ii($canvas, $image_width, $image_height);
return array(
'width' => $image_width,
'height' => $image_height,
'ii' => $iis['ii'],
'ii2' => $iis['ii2']
);
}
protected function compute_ii($canvas, $image_width, $image_height ){
$ii_w = $image_width+1;
$ii_h = $image_height+1;
$ii = array();
$ii2 = array();
for($i=0; $i<$ii_w; $i++ ){
$ii[$i] = 0;
$ii2[$i] = 0;
}
for($i=1; $i<$ii_w; $i++ ){
$ii[$i*$ii_w] = 0;
$ii2[$i*$ii_w] = 0;
$rowsum = 0;
$rowsum2 = 0;
for($j=1; $j<$ii_h; $j++ ){
$rgb = ImageColorAt($canvas, $j, $i);
$red = ($rgb >> 16) & 0xFF;
$green = ($rgb >> 8) & 0xFF;
$blue = $rgb & 0xFF;
$grey = ( 0.2989*$red + 0.587*$green + 0.114*$blue )>>0; // this is what matlab uses
$rowsum += $grey;
$rowsum2 += $grey*$grey;
$ii_above = ($i-1)*$ii_w + $j;
$ii_this = $i*$ii_w + $j;
$ii[$ii_this] = $ii[$ii_above] + $rowsum;
$ii2[$ii_this] = $ii2[$ii_above] + $rowsum2;
}
}
return array('ii'=>$ii, 'ii2' => $ii2);
}
protected function do_detect_greedy_big_to_small( $ii, $ii2, $width, $height ){
$s_w = $width/20.0;
$s_h = $height/20.0;
$start_scale = $s_h < $s_w ? $s_h : $s_w;
$scale_update = 1 / 1.2;
for($scale = $start_scale; $scale > 1; $scale *= $scale_update ){
$w = (20*$scale) >> 0;
$endx = $width - $w - 1;
$endy = $height - $w - 1;
$step = max( $scale, 2 ) >> 0;
$inv_area = 1 / ($w*$w);
for($y = 0; $y < $endy ; $y += $step ){
for($x = 0; $x < $endx ; $x += $step ){
$passed = $this->detect_on_sub_image( $x, $y, $scale, $ii, $ii2, $w, $width+1, $inv_area);
if( $passed ) {
return array('x'=>$x, 'y'=>$y, 'w'=>$w);
}
} // end x
} // end y
} // end scale
return null;
}
protected function detect_on_sub_image( $x, $y, $scale, $ii, $ii2, $w, $iiw, $inv_area){
$mean = ( $ii[($y+$w)*$iiw + $x + $w] + $ii[$y*$iiw+$x] - $ii[($y+$w)*$iiw+$x] - $ii[$y*$iiw+$x+$w] )*$inv_area;
$vnorm = ( $ii2[($y+$w)*$iiw + $x + $w] + $ii2[$y*$iiw+$x] - $ii2[($y+$w)*$iiw+$x] - $ii2[$y*$iiw+$x+$w] )*$inv_area - ($mean*$mean);
$vnorm = $vnorm > 1 ? sqrt($vnorm) : 1;
$passed = true;
for($i_stage = 0; $i_stage < count($this->detection_data); $i_stage++ ){
$stage = $this->detection_data[$i_stage];
$trees = $stage[0];
$stage_thresh = $stage[1];
$stage_sum = 0;
for($i_tree = 0; $i_tree < count($trees); $i_tree++ ){
$tree = $trees[$i_tree];
$current_node = $tree[0];
$tree_sum = 0;
while( $current_node != null ){
$vals = $current_node[0];
$node_thresh = $vals[0];
$leftval = $vals[1];
$rightval = $vals[2];
$leftidx = $vals[3];
$rightidx = $vals[4];
$rects = $current_node[1];
$rect_sum = 0;
for( $i_rect = 0; $i_rect < count($rects); $i_rect++ ){
$s = $scale;
$rect = $rects[$i_rect];
$rx = ($rect[0]*$s+$x)>>0;
$ry = ($rect[1]*$s+$y)>>0;
$rw = ($rect[2]*$s)>>0;
$rh = ($rect[3]*$s)>>0;
$wt = $rect[4];
$r_sum = ( $ii[($ry+$rh)*$iiw + $rx + $rw] + $ii[$ry*$iiw+$rx] - $ii[($ry+$rh)*$iiw+$rx] - $ii[$ry*$iiw+$rx+$rw] )*$wt;
$rect_sum += $r_sum;
}
$rect_sum *= $inv_area;
$current_node = null;
if( $rect_sum >= $node_thresh*$vnorm ){
if( $rightidx == -1 )
$tree_sum = $rightval;
else
$current_node = $tree[$rightidx];
} else {
if( $leftidx == -1 )
$tree_sum = $leftval;
else
$current_node = $tree[$leftidx];
}
}
$stage_sum += $tree_sum;
}
if( $stage_sum < $stage_thresh ){
return false;
}
}
return true;
}
}
Usage:
$detector = new Face_Detector('detection.dat');
$detector->face_detect('maurice_svay_150.jpg');
$detector->toJpeg();
The problem I am running into, seems to be coming up in the comments on that page as well. "imagecolorat() [function.imagecolorat]: 320,1 is out of bounds." So, I added a error_reporting(0) to the top of the file (not really the solution), and it seems to work sometimes while other times it just doesn't do anything.
Any thoughts?
It would probably be easier/safer to do this with OpenCV, which is written in lower-level code. PHP is interpreted, so it's likely going to be hella slow when doing the job.
Hope this helps!
You need to turn off error reporting
<?php
ini_set( 'display_errors', 1 );
error_reporting( E_ALL ^ E_NOTICE );
require_once('face_detector.php');
$detector = new Face_Detector('detection.dat');
$detector->face_detect('img/8.jpg');
$detector->toJpeg();
?>
The project has been upgraded on github repository by following this link Face detection
The problem was on the loop, this code works fine :
for ($i=1; $i<$ii_h-1; $i++) {
$ii[$i*$ii_w] = 0;
$ii2[$i*$ii_w] = 0;
$rowsum = 0;
$rowsum2 = 0;
for ($j=1; $j<$ii_w-1; $j++) {
$rgb = ImageColorAt($canvas, $j, $i);
$red = ($rgb >> 16) & 0xFF;
$green = ($rgb >> 8) & 0xFF;
$blue = $rgb & 0xFF;
$grey = (0.2989*$red + 0.587*$green + 0.114*$blue)>>0; // this is what matlab uses
$rowsum += $grey;
$rowsum2 += $grey*$grey;
$ii_above = ($i-1)*$ii_w + $j;
$ii_this = $i*$ii_w + $j;
$ii[$ii_this] = $ii[$ii_above] + $rowsum;
$ii2[$ii_this] = $ii2[$ii_above] + $rowsum2;
}
}
Good luck
Try removing the +1 from these lines:
$ii_w = $image_width+1;
$ii_h = $image_height+1;
This code is trying to check the colors from positions 1 to 320 instead of 0 to 319 in the 320 pixel image.
This is an old topic but still this fix is better than any I saw so far so, it might help someone
// Turn off error reporting...
$ctl = error_reporting();
error_reporting(0);
$detector = new Face_Detector('detection.dat');
$detector->face_detect('img/8.jpg');
$detector->toJpeg();
// Turn on reporting...if you wish
error_reporting($ctl);
Quick fix: in the compute_ii function
Replace:
$rgb = ImageColorAt($canvas, $j, $i);
With:
$rgb = ImageColorAt($canvas, $j-1, $i-1);

Categories