GD/PHP: Image Resize Based on Width

There are two versions of an application I made to resize images with a fixed width (can also be edited for fixed height) by using php and the image library gd. The first version uses content-type to change the header to display the image on the page. The second version encodes the image data into base64 and puts into json format, which would be better in some cases for api calls. Both use ‘get’ variables to access the url of the image and the width. This can also be edited to deal with your particular needs. More information about different functions that gd has can be found on the php website.

GD Functions used for this application:

  • imagecreatefromjpeg() – creates a new image from a url or a file
  • imagesx() – returns the width of an image
  • imagesy() – returns the height of an image
  • imagecreatetruecolor() – create an empty image container for the resized image, therefore, the dimensions should be for the resized image
  • imagecopyresized() – copies the original image and places into into a new destination image resized to the specified size
  • imagejpeg() – displays image

Version 1: Content-Type: image/jpeg 

1) First setup the content-type (this should be the first line in the file, after php)

header('Content-Type: image/jpeg');

2) Get variables from url

$url = $_GET['url'];
$width = $_GET['width'];

3) Create image data from the url, and generate the dimensions of the original image

$image = imagecreatefromjpeg($url);
$orig_width = imagesx($image);
$orig_height = imagesy($image);

4) Calculate the new height of the image

$height = (($orig_height * $width) / $orig_width);

5) Generate the new image container with the new dimensions, and create the new image

$new_image = imagecreatetruecolor($width, $height);
imagecopyresized($new_image, $image,
	0, 0, 0, 0,
	$width, $height,
	$orig_width, $orig_height);

6) Finally print the image to the screen

imagejpeg($new_image);

7) Here is the complete code for version 1

<?php
header('Content-Type: image/jpeg');

$url = $_GET['url'];
$width = $_GET['width'];

// Loading the image and getting the original dimensions
$image = imagecreatefromjpeg($url);
$orig_width = imagesx($image);
$orig_height = imagesy($image);

// Calc the new height
$height = (($orig_height * $width) / $orig_width);

// Create new image to display
$new_image = imagecreatetruecolor($width, $height);

// Create new image with changed dimensions
imagecopyresized($new_image, $image,
	0, 0, 0, 0,
	$width, $height,
	$orig_width, $orig_height);

// Print image
imagejpeg($new_image);
?>

Version 2: JSON Base64 Encode

The only difference with this one is that the header() line needs to be removed and the display image part is a bit different.

The idea of this one is that you want to store in data of the image into a buffer and save it into a variable. Then encode that data into base64 and wrap it in json.

ob_start();
imagejpeg($new_image);
$data = ob_get_contents();
ob_end_clean();
echo json_encode(array('image' => base64_encode($data)));

Complete code for version 2

<?php
$url = $_GET['url'];
$width = $_GET['width'];

// Loading the image and getting the original dimensions
$image = imagecreatefromjpeg($url);
$orig_width = imagesx($image);
$orig_height = imagesy($image);

// Calc the new height
$height = (($orig_height * $width) / $orig_width);

// Create new image to display
$new_image = imagecreatetruecolor($width, $height);

// Create new image with change dimensions
imagecopyresized($new_image, $image,
	0, 0, 0, 0,
	$width, $height,
	$orig_width, $orig_height);

// Print image
ob_start();
imagejpeg($new_image);
$data = ob_get_contents();
ob_end_clean();
echo json_encode(array('image' => base64_encode($data)));
?>

CAS Apache2: Password Protect Directory

*Note tutorial based on linux type os, not sure how it would work for anything else

Prerequisites:

  • Web Server running apache2
  • Knowledge of what the CAS login URL is
  • Knowledge of what the CAS validate URL is
  • Knowledge of what the CAS certificate is

Step 1: Installing the CAS module

sudo apt-get install libapache2-mod-auth-cas

Step 2: Enabling the CAS module

cd /etc/apache2/mods-available/
sudo a2enmod auth_cas

Step 3: Creating the certificate

sudo vim /etc/ssl/certs/cert.pem

Then paste the certificate into the file.

Step 4: Editing the VHost File

sudo vim /etc/apache2/sites-available/default

Paste in:

<IfModule mod_auth_cas.c>
  CASLoginURL <URL GOES HERE>
  CASValidateURL <URL GOES HERE>
  CASCertificatePath /etc/ssl/certs/cert.pem
  CASCookiePath /tmp/
  CASValidateServer On
  CASDebug Off
</IfModule>

<Directory "/var/www/path/to/directory">
 <IfModule mod_auth_cas.c>
   AuthType CAS
   AuthName "CAS Login"
 </IfModule>
    AuthGroupFile /var/secureusers
    Require group secureusers
    Satisfy All
</Directory>

**Note, add in the correct urls. The “AuthGroupFile”, and “Require group” are optional. Step 5 explains what you do if you included them.

Step 5 (Optional): Creating users restrictions

sudo vim /var/secureusers

Paste in:

secureusers: user-name user-name

How to Install Ruby on Rails on Debian Squeeze

I was looking for a nice and clean way to install Ruby on Rails on a Debian Squeeze server, but couldn’t really find anything that actually worked. Most of the information I saw wanted you to compile gems by source and I tried that, but it didn’t work. Then I looked for the gems package from Debian, and tried installing that. It worked like a charm.

Here’s the commands I used:

sudo apt-get install ruby

sudo apt-get install rubygems

gem install rails

Note: as of today (10/15/11) apt-get install ruby installs version 1.8.7. Also, installing rails takes forever so be prepared for that.

Also, rails is located at:

/var/lib/gems/1.8/bin

Git on a Web Server without using Gitosis

It’s not that I have a problem with Gitosis. It’s just annoying to use and not very fast to get up and running let alone make a new repositories. Therefore, my mission was to find a way to use git without using Gitosis.

First off, I’m using a linux based server (Debian to be exact). Then to get up and running with git on a web server, I used this awesome tutorial that let me install a nice clean install of git. No make files, no cloning, just clean and simple unix commands to get it up and running.

The tutorial works great and all if you don’t want to have some visual way to see changes in a repository like github does. Since, I was looking for something close to github that I can run privately on my own server my task was to find a web interface that didn’t use Gitosis or GitWeb. I looked at several sites and suggestions. Most of it seemed to use the projects listing from Gitosis, that’s no good. However, there was one that I found to be pleasant looking and seemed to do the job cleanly. It’s called ViewGit.

Screenshot of my server running ViewGit with my own template tweaks

ViewGit is a pure and simple php application that provides a web interface for your repositories. The fact that there was no installation was something that I was really looking for in an interface. I didn’t want to have to run special stuff that usually never goes right the first time. To get ViewGit up and running, it was a simple config change to tell the application what directory(s) your repositories are in.

Copy file /inc/config.php to /inc/localconfig.php with command cp.
Then I commented out or deleted the line(7):

$conf['projects'] = array(
	'name' => array('repo' => '/path/to/repo'),
);

And uncommented the line(17) and put in the path to my repos:

conf['projects_glob'] = array('/home/git/*.git');

There you have it, a web server using git without Gitosis. Thank goodness.

Using LightOpenID With Google

LightOpneID is a php openid class that can be used to login with openid services like Google and Twitter.

In this example, I wanted to show how to use LightOpenID to login to remote sites with Google, and also returning the Google email address associated with the account.

Once LightOpenID is download, take a look at the example-google.php file. If you just run this file along with the openid.php file on your webserver it will work just fine. However, if you want it to return the email address associated with the account you will need to change the code a bit.

Lines 1-12 are what handles the auth redirect and step-up of the authentication with google. Make sure you place your domain where it states localhost. Then after line 9 which states the identity:

$openid->identity = 'https://www.google.com/accounts/o8/id';

Add the line:

$openid->required = array('namePerson/friendly', 'contact/email');

Therefore, the result should look something like this:

<?php
require 'openid.php';
try {
    $openid = new LightOpenID('example.com');
    if(!$openid->mode) {
        if(isset($_GET['login'])) {
            $openid->identity = 'https://www.google.com/accounts/o8/id';
            $openid->required = array('namePerson/friendly', 'contact/email');
            header('Location: ' . $openid->authUrl());
        }
?>

This code tells Google that you want the email address also returned in the authentication process. Now the next step to get to the email address from the class when a valid authentication has occurred.

Therefore, I’m going to change up the return code (aka elseif statement) to get and display the returned email variable. To do this I’m going to change the echo string into an if else statement since I need to add a few lines of code.
String to be changed:

echo 'User ' . ($openid->validate() ? $openid->identity . ' has ' : 'has not ') . 'logged in.';

The return variables from google are stored in a associative array, this array can be accessed from calling this function:

$openid->getAttributes();

The index needed to access the variable is called ‘contact/email’ which will allow you to access the email address information.

Therefore, the resulting code looks like this:

        if($openid->validate()) {
            $returnVariables = $openid->getAttributes();
            echo 'User ' . $openid->identity . ' has logged in with this email address ' . $returnVariables['contact/email'];
        } else {
            echo 'User has not logged in.';
        }

You can download the complete source for the google example here.

How to include CSS in CakePHP (1.3)

It took me quite a bit of time finding how to add CSS to CakePHP layouts. Therefore, I’m going to write a bit about it to hopefully help people out. The hardest part was finding where everything went. So here we go:

The HTML layout is placed in:

/app/view/layout/default.ctp

You can find out more about layouts here.
The layout has to include:

<?php echo $scripts_for_layout; ?>

somewhere in the head to allow the addition of the sytlesheet or any other scripts you might have.

Now you have to place the stylesheet in this location:

/app/webroot/css/style.css

Then in your view you need to add the code:

<?php echo $html->css('style', null, array('inline' => false)); ?>

Where ‘style’ is the name of the stylesheet without the extension. That’s it. It should work.