how to count number of pixels in image (php) - php

Please help me to count number of pixels in image, or put out the array of RGB.
So this is the script thet give me one element from array:
<?php
$img = "1.png";
$imgHand = imagecreatefrompng("$img");
$imgSize = GetImageSize($img);
$imgWidth = $imgSize[0];
$imgHeight = $imgSize[1];
echo '<img src="'.$img.'"><br><br>';
for ($l = 0; $l < $imgHeight; $l++) {
for ($c = 0; $c < $imgWidth; $c++) {
$pxlCor = ImageColorAt($imgHand,$c,$l);
$pxlCorArr = ImageColorsForIndex($imgHand, $pxlCor);
}
}
print_r($pxlCorArr);
?>
sorry for my english i from ukraine

The number of pixels in an image is simply the height multiplied by the width.
However, I think this is what you want:
<?php
$img = "1.png";
$imgHand = imagecreatefrompng("$img");
$imgSize = GetImageSize($img);
$imgWidth = $imgSize[0];
$imgHeight = $imgSize[1];
echo '<img src="'.$img.'"><br><br>';
// Define a new array to store the info
$pxlCorArr= array();
for ($l = 0; $l < $imgHeight; $l++) {
// Start a new "row" in the array for each row of the image.
$pxlCorArr[$l] = array();
for ($c = 0; $c < $imgWidth; $c++) {
$pxlCor = ImageColorAt($imgHand,$c,$l);
// Put each pixel's info in the array
$pxlCorArr[$l][$c] = ImageColorsForIndex($imgHand, $pxlCor);
}
}
print_r($pxlCorArr);
?>
This will store all the pixel data for the image in the pxlCor and pxlCorArr arrays, which you can then manipulate to output what you want.
The array is a 2d array, meaning you can refrence an individual pixel with an $pxlCorArr[y][x] starting at [0][0].

Related

How to convert a grayscale image to pure black and white in php?

I'm trying to convert a grayscale image to pure black and white in PHP using the GD library.
The purpose would be to detect the cervical cells within the image.
I'll leave the PHP code and a MatLab one (I wrote this code in MatLab and I'm trying to obtain the same result in PHP). Basically, I'm having trouble accessing each individual pixel's color and modifying it. sample image
PHP:
<?php
$im = imagecreatefromjpeg("celule.jpg");
function imagetograyscale($im)
{
if (imageistruecolor($im)) {
imagetruecolortopalette($im, false, 256);
}
for ($c = 0; $c < imagecolorstotal($im); $c++) {
$col = imagecolorsforindex($im, $c);
$gray = round(0.299 * $col['red'] + 0.587 * $col['green'] + 0.114 * $col['blue']);
imagecolorset($im, $c, $gray, $gray, $gray);
}
}
imagetograyscale($im);
//imagefilter($im, IMG_FILTER_CONTRAST, -255); //i'm not looking for this effect
header('Content-type: image/jpeg');
imagejpeg($im);
$C = imagesx($im); //width
$L = imagesy($im); //height
echo "Dimensiuni imagine: latime $C, inaltime $L <br>";
//scanning through the image
for($x = 0; $x < $L; $x++) { //each line
for($y = 0; $y < $C; $y++) { //each column
// pixel color at (x, y)
$color = imagecolorat($im, $y, $x);
$color = imagecolorsforindex($im, $color); //getting rgb values
$RED[$x][$y] = $color["red"]; //each rgb component
$GREEN[$x][$y] = $color["green"];
$BLUE[$x][$y] = $color["blue"];
}
}
?>
MATLAB:
clear all, clc, close all;
I = imread('celule.jpg');
imshow(I)
title('original');
a=rgb2gray(I);
figure;
imshow(a)
title('grayscale');
s=size(a);
for i=1:s(1)
for j=1:s(2)
if a(i,j)>190
a(i,j)=0;
else a(i,j)=255;
end
end
end
figure;
imshow(a)
title('pure black and white');
Here's a way to do that with gd:
#!/usr/bin/php -f
<?php
// Open image and get dimensions
$im = imagecreatefromjpeg("cellule.jpg");
$w = imagesx($im);
$h = imagesy($im);
// Convert to greyscale
imagefilter($im,IMG_FILTER_GRAYSCALE);
imagepng($im, "grey.png"); // DEBUG only
// Allocate a new palette image to hold the b&w output
$out = imagecreate($w,$h);
// Allocate b&w palette entries
$black = imagecolorallocate($out,0,0,0);
$white = imagecolorallocate($out,255,255,255);
// Iterate over all pixels, thresholding to pure b&w
for ($x = 0; $x < $w; $x++) {
for ($y = 0; $y < $h; $y++) {
// Get current color
$index = imagecolorat($im, $x, $y);
$grey = imagecolorsforindex($im, $index)['red'];
// Set pixel white if below threshold - don't bother settting black as image is initially black anyway
if ($grey <= 190) {
imagesetpixel($out,$x,$y,$white);
}
}
}
imagepng($out, "result.png");
?>

Storing Image pixel values in a 2D array using PHP and then access them using a loop

I have this code that I tried to store Image pixel values in 2D Array and then try to access them so that I can recreate the same Image from the pixels stored in the array, the following was what I was trying to do but it only access the array in 1 Dimension, any who can help will much appreciate it
$resource = imagecreatefromjpeg("Broadway_tower_edit.jpg");
$width = 3;
$height = 3;
$arrayPixels = array();
//put pixels values in an array
for($x = 0; $x < $width; $x++) {
for($y = 0; $y < $height; $y++) {
// pixel color at (x, y)
$color = imagecolorat($resource, $x, $y);
$arrayPixels1 = array("$color");
//$myArray[$x][$y] = array('item' => "$color");
$arrayPixels[] = $arrayPixels1;
}
}
//access pixel values an try to create a image
$img = imagecreatetruecolor($width, $height);
for ($y = 0; $y < $height; ++$y) {
for ($x = 0; $x < $width; ++$x) {
imagesetpixel($img, $x, $y, $arrayPixels[$y][$x]);
}
}
// Dump the image to the browser
header('Content-Type: image/jpg');
imagejpeg($img);
// Clean up after ourselves
imagedestroy($img);
Your array is as you say, just the rows, you need to either build up each row and then add it to a list of rows
$arrayPixels = array();
//put pixels values in an array
for($x = 0; $x < $width; $x++) {
$row = array();
for($y = 0; $y < $height; $y++) {
// pixel color at (x, y)
$row[] = imagecolorat($resource, $x, $y);
}
$arrayPixels[] = $row;
}
or do the same as you do when you re-create the image and use the x and y co-ords...
//put pixels values in an array
for($x = 0; $x < $width; $x++) {
for($y = 0; $y < $height; $y++) {
// pixel color at (x, y)
$arrayPixels[$y][$x] = imagecolorat($resource, $x, $y);
}
}

Jumbling up an image

So I want to be able to jumble up an image so as to distort the original image. What I mean is this. Load an image, loop through the image and take 32x32 blocks and store each individual block in an array. Then reassemble them as a new picture with the blocks in random order.
this is the code I have currently to take and store the blocks from original image and then create reassemble the image (Note this doesn't have the randomization part yet). But for some reason it doesn't output correctly.
<?php
$name = "pic.jpg";
$src = imagecreatefromjpeg($name);
list($width, $height, $type, $attr) = getimagesize($name);
$x_size = floor($width/32);
$y_size = floor($height/32);
$mixed = array();
$new_image = imagecreatetruecolor(32,32);
$x = 0;
$y = 0;
for($y = 0; $y < $height; $y+= 32) {
for($x = 0; $x < $width; $x+=32) {
imagecopy($new_image, $src, 0, 0, $x, $y, 32, 32);
array_push($mixed, $new_image);
}
}
$final_image = imagecreatetruecolor($width, $height);
$i = 0;
$x1 = 0;
$y1 = 0;
for($i = 0; $i < sizeof($mixed); $i++) {
$x1++;
if($x1 >= $x_size) {
$x1 = 0;
$y1++;
}
imagecopymerge($final_image, $mixed[$i], $x1, $y1, 0,0,32,32,100);
}
header('Content-Type: image/jpeg');
imagejpeg($final_image);
?>
Original Image:
http://puu.sh/236XS
Output:
http://puu.sh/236YO
If you can help it wouldbe greatly appreciated.
Thanks.
I solved my own question using the following code:
<?php
include("test.php");
//global variables
$name = "pic.jpg";
$size = 64;
$x = 0;
$y = 0;
$spots = array("0,0", "0,1", "0,2", "0,3",
"1,0", "1,1", "1,2", "1,3",
"2,0", "2,1", "2,2", "2,3",
"3,0", "3,1", "3,2", "3,3");
//open image from file (Original image)
$src = imagecreatefromjpeg($name);
//load image details
list($width, $height, $type, $attr) = getimagesize($name);
//calculate amount of tiles on x/y axis.
$x_size = floor($width/$size);
$y_size = floor($height/$size);
$new_image = imagecreatetruecolor($size,$size);
$final_image = imagecreatetruecolor($width, $height);
$used = array();
for($y = 0; $y < $height; $y+= $size) {
for($x = 0; $x < $width; $x+= $size) {
//generate random x/y coordinates
redo:
$spot = rand(0, sizeof($spots)-1);
if(!in_array($spot, $used)) {
$coords = explode(",", $spots[$spot]);
//grab 32x32 square from original image
imagecopy($new_image, $src, 0, 0, $x, $y, $size, $size);
//place 32x32 square into new image at randomly generated coordinates
imagecopy($final_image, $new_image, $coords[0]*$size, $coords[1]*$size, 0,0,$size,$size);
array_push($used, $spot);
} else {
goto redo;
}
}
}
//display final image
header('Content-Type: image/jpeg');
imagejpeg($final_image);
print_r($used);
?>
Might not be the most efficient code, but it works :)

PHP - Create one image from images

i have n-images and want to create one with php code. I use imagecopymerge(), but can't make it. Some example please?
Code:
$numberOfImages = 3;
$x = 940;
$y = 420;
$background = imagecreatetruecolor($x, $y*3);
$firstUrl = '/images/upload/photoalbum/photo/1.jpg';
$secondUrl = '/images/upload/photoalbum/photo/2.jpg';
$thirdUrl = '/images/upload/photoalbum/photo/3.jpg';
$outputImage = $background;
$first = imagecreatefromjpeg($firstUrl);
$second = imagecreatefromjpeg($secondUrl);
$third = imagecreatefromjpeg($thirdUrl);
imagecopymerge($outputImage,$first,0,0,0,0, $x, $y,100);
imagecopymerge($outputImage,$second,0,$y,0,0, $x, $y,100);
imagecopymerge($outputImage,$third,0,$y*2,0,0, $x, $y,100);
imagejpeg($outputImage, APPLICATION_PATH .'/images/upload/photoalbum/photo/test.jpg');
imagedestroy($outputImage);
Thanks kruksmail,
I adapted your answer for a specific project in which the images could be unknown. So I made your answer work with an array of images.
It also gives the ability to specify how many rows or columns you want. I added some comments to help also.
$images = array('/images/upload/photoalbum/photo/1.jpg','/images/upload/photoalbum/photo/2.jpg','/images/upload/photoalbum/photo/3.jpg');
$number_of_images = count($images);
$priority = "columns"; // also "rows"
if($priority == "rows"){
$rows = 3;
$columns = $number_of_images/$rows;
$columns = (int) $columns; // typecast to int. and makes sure grid is even
}else if($priority == "columns"){
$columns = 3;
$rows = $number_of_images/$columns;
$rows = (int) $rows; // typecast to int. and makes sure grid is even
}
$width = 150; // image width
$height = 150; // image height
$background = imagecreatetruecolor(($width*$columns), ($height*$rows)); // setting canvas size
$output_image = $background;
// Creating image objects
$image_objects = array();
for($i = 0; $i < ($rows * $columns); $i++){
$image_objects[$i] = imagecreatefromjpeg($images[$i]);
}
// Merge Images
$step = 0;
for($x = 0; $x < $columns; $x++){
for($y = 0; $y < $rows; $y++){
imagecopymerge($output_image, $image_objects[$step], ($width * $x), ($height * $y), 0, 0, $width, $height, 100);
$step++; // steps through the $image_objects array
}
}
imagejpeg($output_image, 'test.jpg');
imagedestroy($output_image);
print "<div><img src='test.jpg' /></div>";

using getimagesize() to check width and height in array of external images

I have an array made of external image locations.
$theSize = array();
foreach($images as $imageChoices) {
$theSize[] = getimagesize($imageChoices);
How do I loop through the array $theSizes and return images with a width > 70 and a width > 60
Thanks!
This will loop through the images and compare width,height...if it is greater than the set valid dimensions, then it will insert it into the array $validImgs.
$validImgs = array();
$validWidth = 60;
$validHeight = 70;
foreach($images as $imageChoices){
list($width, $height) = getimagesize($imageChoices);
if($width >= $validWidth && $height >= $validHeight){
$validImgs[] = $imageChoices;
}
}
Try this.
$theSize = array();
foreach($images as $imageChoices) {
list($width, $height, $type, $attr) = getimagesize($imageChoices);
if($width > 60 && $height > 70) $theSize[] = getimagesize($imageChoices);
}
//array contents only images ,(width > 60 and height > 70)
print_r($theSize);
Here's a crude mockup how this can be done:
$image_60 = array();
$image_70 = array();
foreach($images as $imageChoices) {
$data = getimagesize($imageChoices);
if ($data[0] > 60) $image_60[] = $imageChoices;
if ($data[0] > 70) $image_70[] = $imageChoices;
}
Note that I create two arrays $image_60 and $image_70, one for images with the width > 60 and one for images with the width > 70. What to do there depends on what you want to archive with those images.

Categories