Created
September 16, 2011 13:20
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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'); ?> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$(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'}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Requires jQuery but can be done without it.