Archive

Posts Tagged ‘image’

Sequentially Rename All Image Files In A Directory With PHP

March 2nd, 2009 Tech 1 comment

The following function will rename all of the image files in a directory to be sequential. The parameters are the path of the directory that the files are in and the name of a function that will be used to sort the array of files through the PHP usort() funciton.

function sequentialImages($path, $sort=false) {
 $i = 1;
 $files = glob($path."/{*.gif,*.jpg,*.jpeg,*.png}",GLOB_BRACE|GLOB_NOSORT);
 
 if ( $sort !== false ) {
  usort($files, $sort);
 }
 
 $count = count($files);
 foreach ( $files as $file ) {
  $newname = str_pad($i, strlen($count)+1, '0', STR_PAD_LEFT);
  $ext = substr(strrchr($file, '.'), 1);
  $newname = $path.'/'.$newname.'.'.$ext;
  if ( $file != $newname ) {
   rename($file, $newname);
  }
  $i++;
 }
}

The following function can be used in the second parameter to sort the files by their last modified time.

function sort_by_mtime($file1, $file2) {
 $time1 = filemtime($file1);
 $time2 = filemtime($file2);
 if ( $time1 == $time2 ) {
  return 0;
 }
 return ($time1 < $time2) ? 1 : -1;
}

Putting these two function together we can call the sequentialImages() function like this.

sequentialImages('files','sort_by_mtime');

This function takes the following set of images:

file1.gif
file2.gif
wibble.gif
wobble.gif
02.gif

And renames them to the following:

01.gif
02.gif
03.gif
04.gif
05.gif

Categories: PHP Tags: , , , , , , , , , ,

Enabling Image Formatting In Your Wordpress Template

November 20th, 2008 Tech No comments

One neat thing about Wordpress is the ability to add images to your posts in a quick and easy manner. You can also create thumbnails of larger images and link to them using a captioned image. The only problem is that when you have sorted out how your images look in your post in the admin section they just don’t appear the same in your template once you have published it.

This is because Wordpress creates a set of styles that are used in the admin section and the default Wordpress templates. However, these styles are usually left out of custom template stylesheets. If you want to use the same sort of formatting that the Wordpress admin section has then open up your stylesheet file in your template and put the following stylesheet rules in at the bottom.

.alignleft {
float:left;
margin:20px 20px 20px 0pt;
}
 
.alignright {
float:right;
margin:20px 0pt 20px 20px;
}
 
.aligncenter {
display:block;
margin-left:auto;
margin-right:auto;
}
 
.wp-caption {
-moz-border-radius-bottomleft:3px;
-moz-border-radius-bottomright:3px;
-moz-border-radius-topleft:3px;
-moz-border-radius-topright:3px;
background-color:#F3F3F3;
border:1px solid #DDDDDD;
margin:10px;
padding-top:4px;
text-align:center;
color:#000000;
}
 
.wp-caption img {
border:0pt none;
margin:0pt;
padding:0pt;
}
 
.wp-caption p.wp-caption-text {
font-size:11px;
line-height:17px;
margin:0pt;
padding:0pt 4px 5px;
}

With this simple fix you will now have much better looking image styles.

One note for blog writers out there is that if you want to float an image left or right then you need to place it before the text you need to wrap it around. When you align things to the center the text will not wrap around it.

Create Images Thumbnails And Cache Them In PHP

November 14th, 2008 Tech No comments

Creating image thumbnails is a pretty common practice, and there are a few scripts available that allow you to do this in PHP using the GD2 library. However, they are normally overkill for what should be a simple task, so after a bit of searching and testing I found the following ImageResize class, which is taken from http://shiege.com/scripts/thumbnail/. I have modified the code to be PHP5, but if you want the PHP4 version then you can get it from the site.

class ImageResize{
  public $img;
 
  public function ImageResize($imgfile){
    //detect image format
    $this->img["format"] = ereg_replace(".*\.(.*)$","\\1",$imgfile);
    $this->img["format"] = strtoupper($this->img["format"]);
    if($this->img["format"] == "JPG" || $this->img["format"] == "JPEG"){
      //JPEG
      $this->img["format"] = "JPEG";
      $this->img["src"] = ImageCreateFromJPEG ($imgfile);
    }elseif($this->img["format"] == "PNG"){
      //PNG
      $this->img["format"] = "PNG";
      $this->img["src"] = ImageCreateFromPNG ($imgfile);
    }elseif($this->img["format"] == "GIF"){
      //GIF
      $this->img["format"] = "GIF";
      $this->img["src"] = ImageCreateFromGif($imgfile);
    }elseif($this->img["format"] == "WBMP"){
      //WBMP
      $this->img["format"] = "WBMP";
      $this->img["src"] = ImageCreateFromWBMP ($imgfile);
    }else{
      //DEFAULT
      echo "Not Supported File";
      exit();
    };
    $this->img["lebar"] = imagesx($this->img["src"]);
    $this->img["tinggi"] = imagesy($this->img["src"]);
    //default quality jpeg
    $this->img["quality"] = 75;
  }
 
  public function size_height($size = 100){
    //height
    $this->img["tinggi_thumb"] = $size;
    $this->img["lebar_thumb"] = ($this->img["tinggi_thumb"]/$this->img["tinggi"])*$this->img["lebar"];
  }
 
  public function size_width($size = 100){
    //width
    $this->img["lebar_thumb"] = $size;
    $this->img["tinggi_thumb"] = ($this->img["lebar_thumb"]/$this->img["lebar"])*$this->img["tinggi"];
  }
 
  public function size_auto($size = 100){
    //size
    if($this->img["lebar"]> = $this->img["tinggi"]){
      $this->img["lebar_thumb"] = $size;
      $this->img["tinggi_thumb"] = ($this->img["lebar_thumb"]/$this->img["lebar"])*$this->img["tinggi"];
    }else{
      $this->img["tinggi_thumb"] = $size;
      $this->img["lebar_thumb"] = ($this->img["tinggi_thumb"]/$this->img["tinggi"])*$this->img["lebar"];
    };
  }
 
  public function jpeg_quality($quality = 75){
    //jpeg quality
    $this->img["quality"] = $quality;
  }
 
  public function show(){
    //show thumb
    header("Content-Type: image/".$this->img["format"]);
 
    /* change ImageCreateTrueColor to ImageCreate if your GD not supported ImageCreateTrueColor function*/
    $this->img["des"] = ImageCreateTrueColor($this->img["lebar_thumb"],$this->img["tinggi_thumb"]);
    imagecopyresampled($this->img["des"], $this->img["src"], 0, 0, 0, 0, $this->img["lebar_thumb"], $this->img["tinggi_thumb"], $this->img["lebar"], $this->img["tinggi"]);
 
    if($this->img["format"] == "JPG" || $this->img["format"] == "JPEG"){
      //JPEG
      imageJPEG($this->img["des"],"",$this->img["quality"]);
    }elseif($this->img["format"] == "PNG"){
      //PNG
      imagePNG($this->img["des"]);
    }elseif($this->img["format"] == "GIF"){
      //GIF
      imageGIF($this->img["des"]);
    }elseif($this->img["format"] == "WBMP"){
      //WBMP
      imageWBMP($this->img["des"]);
    };
  }
 
  public function save($save = ""){
    //save thumb
    if(empty($save)){
      $save = strtolower("./thumb.".$this->img["format"]);
    }
    /* change ImageCreateTrueColor to ImageCreate if your GD not supported ImageCreateTrueColor function*/
    $this->img["des"] = ImageCreateTrueColor($this->img["lebar_thumb"],$this->img["tinggi_thumb"]);
    imagecopyresampled($this->img["des"], $this->img["src"], 0, 0, 0, 0, $this->img["lebar_thumb"], $this->img["tinggi_thumb"], $this->img["lebar"], $this->img["tinggi"]);
 
    if($this->img["format"] == "JPG" || $this->img["format"] == "JPEG"){
      //JPEG
      imageJPEG($this->img["des"],"$save",$this->img["quality"]);
    }elseif($this->img["format"] == "PNG"){
      //PNG
      imagePNG($this->img["des"],"$save");
    }elseif($this->img["format"] == "GIF"){
      //GIF
      imageGIF($this->img["des"],"$save");
    }elseif($this->img["format"] == "WBMP"){
      //WBMP
      imageWBMP($this->img["des"],"$save");
    };
  }
}

Put this into a file called class.ImageResize.php and you can use it to resize and show any image you want.

include('class.ImageResize.php');
// create ImageResize object
$originalImage = new ImageResize("anImage.jpg");
// use the show function to print this image to screen
$originalImage->show();
// use the save function to save this image to another file - leave empty to save as thumb.anImage.jpg
$originalImage->save("anotherFile.png");
// use one of the size functions to resize the image
$originalImage->size_width(120);
// save it again...
$originalImage->save("thumb_anotherFile.png");

If you want to create a simple thumbnail caching function then you can use the following code. It checks to see if the image exists and if it is older than 30 days. If it is then the file is deleted and because the file no longer exists (or if it never existed) the next part of the code where the thumbnail is created is run.

$imageName = str_replace(dirname("./images/", "" , "http://www.example.com/images/an_image.jpg");
 
if ( file_exists("./thumb_cache".$imageName) ) {
  // 2592000 = 30 days
  if ( time() - filemtime("./thumb_cache".$imageName) > 2592000 ) {
    unlink("./thumb_cache".$imageName);
  }
}
if ( !file_exists("./thumb_cache".$imageName) ) {
  include('class.ImageResize.php');
  // if cache file does not exist then create it.
  $originalImage = new ImageResize("./images/".$_result['image_path']);
  $originalImage->size_width(120);
  $originalImage->save("./thumb_cache".$imageName);
}

Categories: PHP Tags: , , , ,

External Script Files And Printing Objects With Flex

November 6th, 2008 Tech No comments

Yesterday I talked about using the Flex Script element to run code within the mxml file, you can also use the source attribute of the Script element to reference external files. To create an external script file FlashDevelop go to the File->New and select Blank Document. You can also do this by pressing Ctrl+N. This will create a blank document that you must save into your src folder of your project with the extension as. Note that if you call this file sourcefile.as then you must reference this in your script tag like this.

<mx:Script source="sourcefile.as">

</mx:Script>

When you do this you will notice that the script file will be part of the Main.mxml file. You can add functions in the same way as you would with an inline script tag.

Printing

With this external script file we will now create some images and print them using the built in printing object that Flex has. This object is called FlexPrintJob and you must include this at the top of your script file if you want to use it. Put the following line at the top of your script file.

import mx.printing.FlexPrintJob;

Create a button in your mxml file that will be used to print.

<mx:Button id="print" label="Print" click="printImage();" />

Add in an image that will be printed.

<mx:Image source="one.png" id="one" />

Here is the image that will be used.

Flex test image

Flex test image

Go back into the script file and add the function that will print the image out. We called this function printImage() in our Button declaration. This function works by creating a new FlexPrintJob object called printJob. This function start() is then used to try and print. Basically, this function returns true if the print job worked, and false if the user clicked cancel.

If the start() function returns true then the object to be printed (in this case the image with the id of "one" is added to the printJob object. Finally, the send() function is called which sends the data off to the printer. Here is the function.

public function printImage():void
{
 // Create a FlexPrintJob instance.
 var printJob:FlexPrintJob = new FlexPrintJob();
 
 // Start the print job and check that it worked
 if (printJob.start() != true) {
  return;
 }
 
 // add object to be printed to the print job
 printJob.addObject(one);
 
 // send to printer
 printJob.send();
}

This is the simplest use of the FlexPrintJob function as there are controls that can be used to format the pages.

It is possible to print off multiple objects, especially if they are children to another object, by adding the parent object to the FlexPrintJob object. Take the following section of mxml, which defines a Canvas element, with three positioned images as children.

<mx:Canvas id="images">
 <mx:Image source="one.png" id="one" x="0" y="0" />
 <mx:Image source="two.png" id="two" x="100" y="0" />
 <mx:Image source="three.png" id="three" x="0" y="100" />
</mx:Canvas>

This produces the following application.

Three images in a canvas

Three images in a canvas

To print out all three images at once just include the Canvas object instead of the single image object. Change line 11 in the printImage() function from this:

 printJob.addObject(one);

To this.

 printJob.addObject(images);

The printJob object knows about inheritance and will print out everything contained within that element. This includes buttons or any other element that you put into the canvas element.

See the Flex documentation for more information about the FlexPrintJob object.

Creating Some Simple Flex Interface Elements

November 4th, 2008 Tech 1 comment

Following on from my previous blog post about installing Flex on Windows I thought I would go through how to create an interface using mxml. When you create a Flex 3 project the first file you are given is called Main.mxml, which has the following content.

<?xml version="1.0"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
 
</mx:Application>

This file is used to compile and run your Flex project and is the central starting point for all the rest of the compile process. This file controls your interface of your program. At first this file might look daunting, but there are lots of elements to select from and if you know CSS then you should be somewhat familiar with how elements are coloured, padded and positioned.

When you compile your application it will create a swf file in the folder called bin. You can compile and run this file from FlashDevelop, but if you want to just compile it you can navigate to this folder and run the swf file separately.

I will now go through some of the elements that you are likely to need to create a simple interface. It is best to get used to the look and feel of your applications before you get into coding so this post will go over simple interface design and the actual actions will be covered in subsequent posts.

Application

The application element must be the root element of your mxml document. It is basically a container for all the other elements of your application.

Label

The label element is used to add some text to your interface and has the following syntax.
<mx:Label text="A label with some text." />
This will produce the following output.

Label Element

Label Element

Button

The button is exactly what it sounds like, it just adds a button to your interface. The following creates a button called "abutton" with the text "A button", but which has no action.
<mx:Button id="abutton" label="A button" />
This creates the following element.

Button Element

Button Element

Image

Again, the image element is exactly what it sounds like, it adds an image to your application. Here is the syntax.
<mx:Image source="image.jpg" />
This produces the following output with a simple gradient image.

Image Element

Image Element


However, one thing to note is that the source of the image is relative to the path of the swf file in the bin directory. Remember that if you move your swf file you will need to move these files along with it. This took me a while to figure out.

Panel

The panel element is used to contain other elements and create sections in your interface. It is an example of a layout container, which is useful if you want to create a left and right hand panel with different elements in each.
The following example creates a single panel, the full width of the application window, that contains the label, button and image elements that have been previously discussed in this post.
<mx:Panel title="Some example elements" width="100%">
 <mx:Label text="A label with some text." />
 <mx:Button id="abutton" label="A button" />
 <mx:Image source="logo.jpg" />
</mx:Panel>

This produces the following output.

Panell Element

Panell Element

The panel element comes with a fancy set of borders and a header element, if you want to get rid of these then use the following attributes for your panel.

<mx:Panel width="100%"
headerHeight="0"
highlightAlphas="[0, 0]"
borderThicknessTop="0"
borderThicknessLeft="0"
borderThicknessRight="0"
borderThicknessBottom="0"
backgroundAlpha="0"
dropShadowEnabled="false"
cornerRadius="0">
</mx:Panel>

With the addition of the other elements, as in the previous example, this panel now looks like this.

Blank Panel Element

Blank Panel Element

Canvas

The canvas element is like the panel element in that it allows you to add other elements to it and is a layout container. The major difference arises when the elements are rendered. The panel element will stop child elements from overlapping, whereas the canvas element doesn’t care and will overlap elements unless you specify x and y coordinates. The following example shows a canvas element that contains a image and a button, both of which are positioned absolutely.

<mx:Canvas width="50%" height="50%" autoLayout="false">
<mx:Image x="0" y="0" source="logo.jpg" />
<mx:Button x="0" y="100" id="abutton" label="A button" />
</mx:Canvas>

This generates the following output.

Canvas Element

Canvas Element

Spacer

The spacer element is used to provide some space between two elements. It is a blank element that should not contain any children and should be used only to add padding between elements. It has the following syntax, in this case the spacer will create a space of 10 pixels in height.
<mx:Spacer height="10" />

There are plenty of other elements to chose from, and this is only a very brief overview of some of the simpler ones. If you want to know more than check out the Flex 3 API Documentation which has more information on all of the elements discussed here, as well as information on many more which can’t all be covered here. However, it should be noted that not all of the things discussed on in the API are interface elements. There are things like the Date object which exists simply to provide a wrapper for date functions and form part of your application script, which I will do an introduction to in my next post.