Php imagebmp for monochrome bitmap - php

How to implement imagebmp() function for monochrome BMP?
I found many implementation for 24bit bitmap but nothing about 1bit bitmap.

This is a working implemenation.
I used a bindec function, I can be optimized using shift operators, but I found very easy the string padding function.
function imagebmp(&$img, $filename = false)
{
$wid = imagesx($img);
$hei = imagesy($img);
$wid_pad = str_pad('', (4-ceil($wid/8) % 4) %4, "\0");
$size = 62 + ( ceil($wid/8) + strlen($wid_pad)) * $hei;
//prepare & save header
$header['identifier'] = 'BM';
$header['file_size'] = dword($size);
$header['reserved'] = dword(0);
$header['bitmap_data'] = dword(62);
$header['header_size'] = dword(40);
$header['width'] = dword($wid);
$header['height'] = dword($hei);
$header['planes'] = word(1);
$header['bits_per_pixel'] = word(1);
$header['compression'] = dword(0);
$header['data_size'] = dword(0);
$header['h_resolution'] = dword(0);
$header['v_resolution'] = dword(0);
$header['colors'] = dword(0);
$header['important_colors'] = dword(0);
$header['white'] = chr(255).chr(255).chr(255).chr(0);
$header['black'] = chr(0).chr(0).chr(0).chr(0);
if ($filename)
{
$f = fopen($filename, "wb");
foreach ($header AS $h)
{
fwrite($f, $h);
}
//save pixels
$str="";
for ($y=$hei-1; $y>=0; $y--)
{
$str="";
for ($x=0; $x<$wid; $x++)
{
$rgb = imagecolorat($img, $x, $y);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
$gs = (($r*0.299)+($g*0.587)+($b*0.114));
if($gs>150) $color=0;
else $color=1;
$str=$str.$color;
if($x==$wid-1){
$str=str_pad($str, 8, "0");
}
if(strlen($str)==8){
fwrite($f, chr((int)bindec($str)));
$str="";
}
}
fwrite($f, $wid_pad);
}
fclose($f);
}
else
{
foreach ($header AS $h)
{
echo $h;
}
//save pixels
for ($y=$hei-1; $y>=0; $y--)
{
for ($x=0; $x<$wid; $x++)
{
$rgb = imagecolorat($img, $x, $y);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
$gs = (($r*0.299)+($g*0.587)+($b*0.114));
if($gs>150) $color=0;
else $color=1;
$str=$str.$color;
if($x==$wid-1){
$str=str_pad($str, 8, "0");
}
if(strlen($str)==8){
echo chr((int)bindec($str));
$str="";
}
}
echo $wid_pad;
}
}
}
function dword($n)
{
return pack("V", $n);
}
function word($n)
{
return pack("v", $n);
}

Related

PHP keeps skipping to 144, but when echoed, is correct value

I'm currently trying to get all pixel data inside of an image, and return it in JSON after encoding an Array. However, when I try to insert the $y data into the array, it always inserts 144. No in-between, always 144. When I echo $y, however, I get "0, 1, 2, etc."
$x, $r, $g, and $b are correct.
Any ideas? Here's my code:
<?php
header('Content-Type: application/json');
class PixelData {
private $ar = array(
"pixeldata" => [
]
);
public function getPixel($x, $y, $im) {
echo $y; // echoes "0, 1, 2, 3, etc."
global $ar;
$ar["pixeldata"][$x]["x"] = $x;
$ar["pixeldata"][$x]["y"] = $y;
$rgb = imagecolorat($im, $x, $y);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
$ar["pixeldata"][$x]["r"] = $r;
$ar["pixeldata"][$x]["g"] = $g;
$ar["pixeldata"][$x]["b"] = $b;
}
}
$src = "D:\Pictures\Test.png";
$im = imagecreatefrompng($src);
$size = getimagesize($src);
$width = imagesx($im);
$height = imagesy($im);
for($x = 0; $x < $width; $x++)
{
for($y = 0; $y < $height; $y++)
{
$pd = new PixelData();
$pd->getPixel($x, $y, $im);
}
}
$js = json_encode($ar);
echo $js;
?>
To elaborate further on my comment:
Your array is basically one-dimensional, because the only variable aspect is $ar['pixeldata'][$x]; you're never adding $y as another dimension. So, every time you increment $y in the inner-most for loop to go to the next level of $height you're overwriting the previous $x values. Basically, by the time your script is done, pixeldata will only contain the data of the top-most row of pixels, therefore they're always 144.
I also didn't notice until now, but if you wanted to store the data within the PixelData private array, you can't create a new instance within the for loops, you'd need to do that outside of the for loops.
This is probably what you want. As you can see, I've added an extra dimension to you pixeldata array, so as to include both $x and $y dimensions.
<?php
header('Content-Type: application/json');
class PixelData {
private $ar = array(
"pixeldata" => [
]
);
public function getPixel($x, $y, $im) {
echo $y; // echoes "0, 1, 2, 3, etc."
// Instantiate an array for this pixel
$this->ar["pixeldata"][$x][$y] = [];
$this->ar["pixeldata"][$x][$y]["x"] = $x;
$this->ar["pixeldata"][$x][$y]["y"] = $y;
$rgb = imagecolorat($im, $x, $y);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
$this->ar["pixeldata"][$x][$y]["r"] = $r;
$this->ar["pixeldata"][$x][$y]["g"] = $g;
$this->ar["pixeldata"][$x][$y]["b"] = $b;
}
public function getAr() {
return $this->ar;
}
}
$src = "D:\Pictures\Test.png";
$im = imagecreatefrompng($src);
$size = getimagesize($src);
$width = imagesx($im);
$height = imagesy($im);
$pd = new PixelData();
for($x = 0; $x < $width; $x++)
{
for($y = 0; $y < $height; $y++)
{
$pd->getPixel($x, $y, $im);
}
}
$js = json_encode($pd->getAr());
echo $js;
?>

How to pixelar image in php

What I'm trying to do is to pixelate an image of a url, add another image above it and last save that image.
I have obtained this internet code to pixelate images but I think it does not work correctly. It does not show me the pixelated image nor does it save it. Just the black screen remains.
$pixel = 15;
$getImagen = 'https://ep00.epimg.net/elpais/imagenes/2017/06/05/album/1496652756_562670_1496654035_album_normal.jpg';
$imagen = imagecreatefromjpeg($getImagen);
if(!$imagen) exit('ERROR');
list($ancho,$alto)=getimagesize($getImagen);
$superficieTotal = $ancho*$alto;
//
$superficieRecorrida = 0;
$auxX=0;
$auxY=0;
while($superficieRecorrida <= $superficieTotal){
$posX=0;$posY=0;$data = array();
while($posX <= $pixel and (($auxX + $posX) < $ancho)){
$posY=0;
while($posY <= $pixel and (($auxY + $posY) < $alto)){
$rgb = imagecolorat($imagen, ($auxX + $posX), ($auxY + $posY));
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
$data[] = array($r,$g,$b);
$posY++;
}
$posX++;
}
// Busco promedio
$r = 0; $g = 0; $b = 0;
foreach($data as $d){
$r+= $d[0];
$g+= $d[1];
$b+= $d[2];
}
$totalArray = count($data);
if($totalArray == 0) $totalArray = 1;
$r = $r/$totalArray;
$g = $g/$totalArray;
$b = $b/$totalArray;
$colorPromedio = imagecolorallocate($imagen, $r, $g, $b);
imagefilledrectangle($imagen, $auxX, $auxY, ($auxX + $pixel), ($auxY + $pixel), $colorPromedio);
//
$auxX+= $pixel;
if($auxX >= $ancho){
$auxX = 0;
$auxY+= ($pixel+1);
}
$superficieRecorrida+= $pixel*$pixel;
}
//
Header("Content-type: image/jpeg");
imagejpeg($imagen);
imagedestroy($imagen);
Thanks for your future answers. a greeting

PHP - JPEG Image to RGB value Array

I am wanting to get an array of RGB values from an image. E.g. (2 X 2 pix example.)
[[[R, G, B], [R, G, B]], [[R, G, B], [R, G, B]]]
The code I have now:
<?php
// open an image
$image = imagecreatefromjpeg('image.jpg'); // imagecreatefromjpeg/png/
// get image dimension, define colour array
$width = imagesx($image);
$height = imagesy($image);
$colors = [];
for ($y = 0; $y < $height; $y++)
{
for ($x = 0; $x < $width; $x++)
{
$rgb = imagecolorat($image, $x, $y);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
}
}
print_r($colors);
?>
The above is not working.
My image is now just a 2 X 2 pix jpeg which should output:
[[[0, 255, 0], [255, 0, 0]], [[0, 0, 255], [255, 255, 255]]]
Any help greatly appreciated!
OK, nailed it. Thanks to all.
<?php
$image = imagecreatefromjpeg('image.jpg'); // imagecreatefromjpeg/png/
$width = imagesx($image);
$height = imagesy($image);
$colors = array();
for ($y = 0; $y < $height; $y++) {
$y_array = array() ;
for ($x = 0; $x < $width; $x++) {
$rgb = imagecolorat($image, $x, $y);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
$x_array = array($r, $g, $b) ;
$y_array[] = $x_array ;
}
$colors[] = $y_array ;
}
print_r($colors);
?>
Comments correct, added $r, $g, $b. Restructured #jari answer and now getting a good output.
Cheers!
function getArrayOfPixelsFromFile($source) {
$image = imagecreatefromjpeg($source); // imagecreatefromjpeg/png/
$width = imagesx($image);
$height = imagesy($image);
$colors = array();
for ($y = 0; $y < $height; $y++) {
$y_array = array();
for ($x = 0; $x < $width; $x++) {
//Seleciona a cor localizada em ($x, $y)
$rgb = imagecolorat($image, $x, $y);
//echo $rgb." = ".decbin($rgb),"<br>";
//Seleciona os primeiros dois bytes que representam vermelho
$r = ($rgb >> 16) & 0xFF;
//Seleciona os dois bytes do meio que representam o verde
$g = ($rgb >> 8) & 0xFF;
//Seleciona os dois Ășltimos bytes que representam o azul
$b = $rgb & 0xFF;
$x_array = array($r, $g, $b);
$y_array[] = $x_array;
}
$colors[] = $y_array;
}
return $colors;
}
I fixed your code by creating subarrays and adding elements to it as it should be.
for ($y = 0; $y < $height; $y++)
{
$height_arr = array() ;
for ($x = 0; $x < $width; $x++)
{
$rgb = imagecolorat($image, $x, $y);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
$width_arr = array($r, $g, $b) ;
$height_array[] = $width_arr ;
}
$colors[] = $height_arr ;
}
How about this?
[...]
$colors = [];
for ($y = 0; $y < $height; $y++) {
for ($x = 0; $x < $width; $x++) {
$rgb = imagecolorat($image, $x, $y);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
$colors[$y][$x] = array($r,$g,$b); // or, $colors[$x][$y] = array($r,$g,$b);
}
}
print_r($colors);

Find White Pixel Lines

I want to replace all white pixel from a completely white column with other color and if I have a black pixel on column don't change anything, but I don't know where is the problem...
Here is the code:
function findLines() {
$blank = 1;
$im_1 = imageCreateFromPng('resize_1.png');
for($i=0; $i<1090; $i++) {
if($blank == 1) {
for($j=0; $j<240; $j++) {
$rgb = imageColorAt($im_1, $i, $j);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
$c = $r.$g.$b;
if($c === "0 0 0") {
$blank = 0;
}
$color = imageColorAllocate($im_1, 0, 255, 255);
imageSetPixel($im_1, $i, $j, $color);
}
}
if ($blank == 0) {
for($j=0; $j<240; $j++) {
$rgb = imageColorAt($im_1, $i, $j);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
$c = $r . " " . $g . " " . $b;
if($c === "255 255 255") {
$blank = 1;
}
}
} else {
$blank = 0;
}
}
header("Content-Type: image/png");
imagepng($im_1);
}
This is the right one. Thanks anyway!
function findLines() {
$im_1 = imageCreateFromPng('resize_1.png');
for($i=0; $i<1090; $i++) {
$blank = 1;
for($j=0; $j<240; $j++) {
$rgb = imageColorAt($im_1, $i, $j);
if($rgb == 0) {
$blank = 0;
}
}
if ($blank == 1) {
for($j=0; $j<240; $j++) {
$color = imageColorAllocate($im_1, 155, 155, 155);
imageSetPixel($im_1, $i, $j, $color);
}
} else {
$blank = 0;
}
}
header("Content-Type: image/png");
imagepng($im_1);
}

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