Skip to content

Instantly share code, notes, and snippets.

@shankarcabus
Last active December 26, 2015 18:39
Show Gist options
  • Save shankarcabus/7195958 to your computer and use it in GitHub Desktop.
Save shankarcabus/7195958 to your computer and use it in GitHub Desktop.
Upload image with crop
<div class="add-offer-field-image">
<div class="add-offer-upload-image">
<input class="add-offer-field-file" type="file" name="image">
Adicionar imagem<i class="icon-picture"></i>
</div>
<div class="add-offer-image-preview">
<img src="" alt="">
</div>
</div>
/* Image upload and crop */
$(".add-offer-field-file").on("change", function(){
if (this.files && this.files[0]) {
var reader = new FileReader(),
$imgToCrop = $(".add-offer-image-preview"),
$img = $imgToCrop.find("img"),
$imgPreviewHome = $(".offer-preview-home-img img"),
$imgPreviewPage = $(".offer-preview-page-img img");
reader.onload = function (e) {
$img.attr('src', e.target.result);
$img.load(function(){
var imgWidth = $img.width(),
imgHeight = $img.height(),
landscape = imgWidth > imgHeight,
lowerSide = landscape ? imgHeight : imgWidth,
x1, x2, y1, y2, h, w;
var aspectRatio = 205/140;
// Calculates the initial crop position
if (landscape) {
h = lowerSide;
w = h * aspectRatio;
x1 = (imgWidth - w)/2;
x2 = x1 + w;
y1 = 0;
y2 = lowerSide;
} else {
w = lowerSide;
h = w / aspectRatio;
x1 = 0;
x2 = lowerSide;
y1 = (imgHeight - h)/2;
y2 = y1 + h;
}
$img.Jcrop({
onChange: showPreview,
onSelect: showPreview,
aspectRatio: aspectRatio,
setSelect: [x1, y1, x2, y2]
});
$imgPreviewHome.add($imgPreviewPage).attr('src', e.target.result);
})
}
reader.readAsDataURL(this.files[0]);
$(".add-offer-upload-image").hide();
$imgToCrop.show();
function showPreview(coords) {
var rx = 95 / coords.w,
ry = 65 / coords.h;
// The croped image has 205x140, but this preview should show 65x65
// So, the aditional margin left is: 95 - 65 = 30. 30/2 = 15
var aditionalMarginLeft = 15;
$imgPreviewHome.css({
width: Math.round(rx * $img.width()),
height: Math.round(ry * $img.height()),
marginLeft: - Math.round(rx * coords.x) - aditionalMarginLeft,
marginTop: - Math.round(ry * coords.y)
});
rx = 205 / coords.w,
ry = 140 / coords.h;
$imgPreviewPage.css({
width: Math.round(rx * $img.width()),
height: Math.round(ry * $img.height()),
marginLeft: - Math.round(rx * coords.x),
marginTop: - Math.round(ry * coords.y)
});
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment