Improving on a photo resize/thumbnail creator plug-in...
Ok, below is the modified code for a plugin I obtained from www.webmotionuk.com. Their version took a fixed width image and allows the user to create a fixed width crop window while previewing the cropped image in another div. I've made a few adjustments to allow the image to be any h & w and maintain the scale of the crop. This will allow a user to upload a photo, have it resize automatically, then create a 160x160 image for their profile. The problem I'm having is twofold:
- Restricting the footprint of the image (100k max sounds about right)
- Preloading the image: Right now, the unresized image loads, then on beginning to create the crop box it resizes to spec.
Here's the page:
click
<script type="text/javascript">
function preview(img, selection) {
var scaleX = 160 / selection.width;
var scaleY = 160 / selection.height;
var big_width=img.offsetWidth;
var big_height=img.offsetHeight;
$('.story-small img').each(function() {
var maxWidth = 500; // Max width for the image
var maxHeight = 500; // Max height for the image
var ratio = 0; // Used for aspect ratio
var width = $(this).width(); // Current image width
var height = $(this).height(); // Current image height
// Check if the current width is larger than the max
if(width > maxWidth){
ratio = maxWidth / width; // get ratio for scaling image
$(this).css("width", maxWidth); // Set new width
$(this).css("height", height * ratio); // Scale height based on ratio
height = height * ratio; // Reset height to match scaled image
width = width * ratio; // Reset width to match scaled image
}
// Check if current height is larger than max
if(height > maxHeight){
ratio = maxHeight / height; // get ratio for scaling image
$(this).css("height", maxHeight); // Set new height
$(this).css("width", width * ratio); // Scale width based on ratio
width = width * ratio; // Reset width to match scaled image
}
});
$('#thumbnail + div > img').css({
width: Math.round(scaleX * big_width) + 'px',
height: Math.round(scaleY * big_height) + 'px',
marginLeft: '-' + Math.round(scaleX * selection.x1) + 'px',
marginTop: '-' + Math.round(scaleY * selection.y1) + 'px'
});
$('#x1').val(selection.x1);
$('#y1').val(selection.y1);
$('#x2').val(selection.x2);
$('#y2').val(selection.y2);
$('#w').val(selection.width);
$('#h').val(selection.height);
}
$(document).ready(function () {
$('#save_thumb').click(function() {
var x1 = $('#x1').val();
var y1 = $('#y1').val();
var x2 = $('#x2').val();
var y2 = $('#y2').val();
var w = $('#w').val();
var h = $('#h').val();
if(x1=="" || y1=="" || x2=="" || y2=="" || w=="" || h==""){
alert("You must make a selection first");
return false;
}else{
return true;
}
});
});
$(window).load(function () {
$('#thumbnail').imgAreaSelect({ aspectRatio: '1:1', onSelectChange: preview });
});
</script>
Thanks for any help...