Skip to content

Instantly share code, notes, and snippets.

@terryjsmith
Last active December 22, 2015 09:48
Show Gist options
  • Save terryjsmith/6453876 to your computer and use it in GitHub Desktop.
Save terryjsmith/6453876 to your computer and use it in GitHub Desktop.
Automatically resize an image to the browser window width and height to use as a background image (crops from the center for different resolutions, uses jQuery).
<script type="text/javascript">
// Adding an extra 10% in here because both iPhone and Android are repeating the background despite
// the no-repeat and this fixes it
$('body').css('background', "url('/image.php?w=" + ($(window).width() * 1.1) + "&h=" + ($(window).height() * 1.1) + "')");
</script>
<?php
header('Content-type: image/jpeg');
$screen_width = $_GET['w'];
$screen_height = $_GET['h'];
// Should probably add some caching code here if the image size we need already exists
// Basically just an if(file_exists("cache/{$screen_width}x{$screen_height}.jpg")) {
// include("cache/{$screen_width}x{$screen_height}.jpg"); die;
// }
// or you could roll something more complicated; you'll also need to add some saving code to the end
$image = imagecreatefromjpeg('images/background2.jpg'); // Change this to the location of your image file
// Figure out what the scaled image size will be before cropping, might have to be thinner for 4:3 screens
$image_width = imagesx($image);
$image_height = imagesy($image);
$width_ratio = $screen_width / $image_width;
$height_ratio = $screen_height / $image_height;
$new_width = ($width_ratio > $height_ratio) ? $screen_width : ($height_ratio * $image_width);
$new_height = ($width_ratio > $height_ratio) ? ($width_ratio * $image_height) : $screen_height;
$temp = imagecreatetruecolor($new_width, $new_height);
imagecopyresized($temp, $image, 0, 0, 0, 0, $new_width, $new_height, $image_width, $image_height);
// Figure out which side we need to crop
$final_width = ($width_ratio > $height_ratio) ? $new_width : $screen_width;
$final_height = ($width_ratio > $height_ratio) ? $screen_height : $new_height;
$final = imagecreatetruecolor($final_width, $final_height);
imagecopy($final, $temp, 0, 0, abs(($final_width - $new_width) / 2), abs(($final_height - $new_height) / 2), $final_width, $final_height);
imagejpeg($final);
@kennberg
Copy link

kennberg commented Jan 4, 2014

You'd better off pre-generating a bunch of images with different sizes and then picking the one closest to width/height. Basically a server-side srcset http://www.w3.org/html/wg/drafts/srcset/w3c-srcset/

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