Skip to content

Instantly share code, notes, and snippets.

@craigmdennis
Created September 16, 2011 13:20
Show Gist options
  • Save craigmdennis/1222114 to your computer and use it in GitHub Desktop.
Save craigmdennis/1222114 to your computer and use it in GitHub Desktop.
Create a tileable background image from the left-most pixel of an image
<?php
function create_background($filename) {
// Get the file extension
$file_pieces = explode('.', $filename);
$file_name = $file_pieces[0];
$file_ext = $file_pieces[1];
$new_filename = $file_name.'_bg.'.$file_ext;
// If the background image doesn't exist then create it
if (!file_exists($new_filename)) {
// Get dimensions of the original image
list($current_width, $current_height) = getimagesize($filename);
// The x and y coordinates on the original image where we
// will begin cropping the image
$left = 0;
$top = 0;
// This will be the final size of the image (e.g. how many pixels
// left and down we will be going)
$crop_width = 1;
$crop_height = $current_height;
// Resample the image
$canvas = imagecreatetruecolor($crop_width, $crop_height);
// If the file is a png
if ($file_ext === 'png') {
$current_image = imagecreatefrompng($filename);
imagecopy($canvas, $current_image, 0, 0, $left, $top, $current_width, $current_height);
imagepng($canvas, $new_filename, 0);
// Else assume it is a jpeg
} else {
$current_image = imagecreatefromjpeg($filename);
imagecopy($canvas, $current_image, 0, 0, $left, $top, $current_width, $current_height);
imagejpeg($canvas, $new_filename, 100);
}
}
}
?>
<?php create_background('your-image-filename.ext'); ?>
$(document).ready( function(){
// Get the filename of the image and split it at the dot
var filename = $('img').attr('src').split('.');
// Reconstruct the filename to include the '_bg' created by the php and add the '.'
var bg = filename[0]+'_bg.'+filename[1];
// Apply the background image dynamically to the body
$('body').css({'background' : 'url('+bg+') repeat-x'});
});
@craigmdennis
Copy link
Author

Requires jQuery but can be done without it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment