Created
February 14, 2012 15:18
-
-
Save dux/1827509 to your computer and use it in GitHub Desktop.
JavaScript image reseize and crop, inline-onload, imgur.com optimized
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
window.resize_crop = (img) -> | |
org = new Image() | |
org.src = img.src | |
org.onload = -> | |
j_img = $(img) | |
src = @src | |
img_w = parseInt j_img.css "width" | |
img_h = parseInt j_img.css "height" | |
if /imgur\.com\/(\w+)/.test(src) | |
img_url = RegExp.$1 | |
img_url = img_url.replace(/(\w)$/, "") | |
img_ext = RegExp.$1 | |
img_url += img_ext unless /[sml]/.test(img_ext) | |
switch | |
when img_w < 90 then img_url += 's' | |
when img_w < 320 then img_url += 'm' | |
else img_url += 'l' | |
src = src.replace(/\/[^\/]+$/, '/'+img_url+'.jpg') | |
target = (if parseInt(@width) / img_w > parseInt(@height) / img_h then "height" else "width") | |
clip = """clip:rect(0px #{img_w}px #{img_h}px 0px);""" | |
if target is "height" | |
aspect = @width / @height | |
if aspect > 1 | |
shift_x = parseInt((img_w * aspect - img_w) / 2) | |
clip = """clip:rect(0px #{img_w + shift_x}px #{img_h}px #{shift_x}px); margin-left:-#{shift_x}px;""" | |
img_html = """<img style="#{target}:#{j_img.css(target)}; position:absolute; top:0px; left:0px; #{clip}" src="#{src}" />""" | |
j_img.replaceWith """<div style="border:1px solid red; position:relative; display:inline-block; #{j_img.attr('style')}">#{img_html}</div>""" | |
# <img src="http://i.imgur.com/QFTMU.jpg" style="width:200px; height:200px;" onload="resize_crop(this)" /> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment