Posts Tagged ‘PHP’

Check size constraints for multidimensional arrays

Monday, February 8th, 2010

Multidimensional arrays are commonly used as a complex data structure. Moreover, they are used to convey data between software systems internally. In some programming languages however, there is no way to constrain the size of arrays at any stage of the array’s lifetime. PHP for instance has no ability to do this. Therefore a way must be devised to make sure the structure of the passed data conforms to what the receiving system expects.

Think for instance pixel convolution matrices. These are usually 3 by 3.

Check out my recursive PHP function to check sizes at any dimensional depth possible:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
function isDimension($arr, $dimensions)
{
   $pass = true;
   $amount = array_shift($dimensions);
 
   if($amount === -1 || count($arr) === $amount)
   {
      if(!empty($dimensions))
      {
         foreach($arr as $element)
         {
            if(is_array($element))
            {
               if(!isDimension($element, $dimensions))
               {
                  $pass = false;
               }
            }
            else
            {
               $pass = false;
            }
         }
      }
   }
   else
   {
      $pass = false;
   }
   return $pass;
}

And when we utilize this function in the following way:

1
2
3
4
5
6
7
8
9
10
11
12
$subject = array(	array(1,2,3),
			array(2,3,4),
			array(3,4,5));
 
if(isDimension($subject, array(3,3)))
{
   print "Yay";
}
else
{
   print "Nay";
}

The output will be:

Yay

If at a certain dimension size does not matter you can skip it by entering -1 as the expected size:

1
2
3
4
5
6
7
8
$subject = array(	array(1,2,3),
			array(2,3,4),
			array(3,4,5)
			array(4,5,6));
 
$wellIsIt = isDimension($subject, array(-1,3)); // Returns true
$wellIsIt = isDimension($subject, array(4,3)); // Returns true
$wellIsIt = isDimension($subject, array(3,3)); // Returns false

This is a recursive function, meaning that it calls itself from within itself until a certain condition is met. Then it cascades the result back to the initial function call which in turn passes it back to whatever script called the function. More about this can be read on wikipedia.

There ya go

PHP: Image Resizer Class

Thursday, June 19th, 2008

Being able to resize images automatically is a must for websites where users can upload their own images, avatars and so on. In PHP we can do this with the GD library. We don’t want users to upload pictures that are 2000 pixels wide and 1 pixel high. This will disrupt the layout of the site on which they are shown.

Thus we want the image to be resized to sane proportions and dimensions so that we can be sure they fit nicely into our websites’ layout.

Therefore I made an image resizing class myself. It actually resamples the images for better results. Here are some of the features:

  • Handles JPG, GIF, PNG and BMP image files
  • Can make multiple resized copies
  • Can simply duplicate the original
  • Can crop images to a certain aspect ratio, maintaining proportions
  • Can save to JPG, GIF, PNG and BMP
  • Can return the image as a string (for i.e. database storage)
  • Can return the image to the browser
  • Throws exceptions for unexpected behaviour

Here is some code that shows how to utilize the class in your PHP application:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
include "imageresizer.php";
 
// Increase the allowed memory size for the bigger images
ini_set('mem_size', 32000);
 
try {
	$image = new imageResizer('original.jpg');
 
	// Make a smaller version of the original
	$image->resize(400, 300, 400, 100);
	$image->save('result.gif', GIF);
 
	// Make a thumbnail of the original
	$image->resize(100, 100);
	$image->save('thumb_result.png', PNG);
 
	// Retrieve the thumbnail as a string as BMP and show it in the browser as JPG
	$string = $image->getString(BMP);
	$image->show(JPG);
}
catch(Exception $e) {
	// Catch and display any exceptional behaviour
	print $e->getMessage();
	exit();
}
 
// Destroy object (executes the destructor) and more importantly, frees up memory
$image = null;

The resize method can have four values passed to it, namely: maximum width, maximum height, minimum width and minimum height. Either the width or the height should be the same when you use this functionality. Suppose we have the width at 400 pixels. The height of the result should be between 300 and 100 pixels. If we can’t fit the original in this aspect ratio constraint it will crop off the edges until it fits. This way the image is not stretched or compressed and we have control over both proportions and dimensions.

Download the imageResizer class here!

If you come up with any improvements or bugs please let me know.

Convert Magic eDeveloper / Pervasive date: `Days since AD` in PHP

Friday, December 21st, 2007

A while ago I was working on a PHP web-application that uses a Pervasive SQL database which belonged to a Magic eDeveloper application. I encountered a really weird date format in the database which I couldn’t really place. I had a hunch that it might be the amount of days since AD (01-01-0000). This turned out to be right. Me and a friend devised a way to convert these dates to a unix timestamp in the following manner:

  • Determine the amount of days from AD (01-01-0000) to the Unix epoch (01-01-1970). Outcome: 719163.
  • Subtract the weird date with the amount determined above.
  • Multiply the outcome by the amount of seconds in a day (86400).

Presto, there you have your unix timestamp.

The code in PHP:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// A simple way to convert Magic date to a unix timestamp and vice versa
define("AD_TO_UNIXEPOCH", 719163);
define("SECONDS_IN_DAY", 86400);
 
// Function that converts the days to unixtime
function days2unixtime($date) {
   return ($date - AD_TO_UNIXEPOCH) * SECONDS_IN_DAY;
}
 
// The other way around
function unixtime2days($date) {
   return AD_TO_UNIXEPOCH + round($date / SECONDS_IN_DAY, 0);
}
 
// Proof of concept
$magicdate = 732468;
$unixtime = days2unixtime($magicdate);
print strftime("%d-%m-%Y", $unixtime) . "\n"; // Prepare for a hellish output ;)
print unixtime2days($unixtime); // And converted back

NB: For dates before the Unix epoch you will get a negative result.

Hope this helps someone who’s encountered the same problem.
If you know a better solution please leave a comment or mail.