Last active
August 29, 2015 14:05
-
-
Save mgng/a847ca74732c04c30f4d to your computer and use it in GitHub Desktop.
canvas 使って画像リサイズしてダウンロードさせる
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
<p><button id="id_100x100_download">100x100でダウンロード</button></p> | |
<p><img id="id_original_image" src="/img/sample.jpg" alt="" /></p> | |
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> | |
<script> | |
;$(function(){ | |
'use strict'; | |
$("#id_100x100_download").on("click.download", function(){ | |
var w = 100, h = 100, img = new Image(); | |
img.src = document.getElementById("id_original_image").src; | |
img.onload = function(){ | |
// リサイズ処理 | |
// canvasにリサイズして描画してbase64で取りだす | |
var canvas = document.createElement( "canvas" ); | |
canvas.width = w; | |
canvas.height = h; | |
canvas.getContext("2d").drawImage( img, 0, 0, w, h ); | |
var base64_resized = canvas.toDataURL( "image/png" ); | |
// ダウンロード処理 | |
// html5 から追加された download 属性使って click 発火させればよい | |
var a = document.createElement('a'); | |
a.download = "resized.png"; | |
a.href = base64_resized; | |
var evt = document.createEvent('MouseEvent'); | |
evt.initEvent("click", true, false); | |
a.dispatchEvent( evt ); | |
// // jQuery.trigger だと動かない... | |
// $("<a />").attr({ | |
// download : "resized.png", | |
// href : base64_resized | |
// }).trigger( "click" ); | |
}; | |
}); | |
}); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment