画像を高品質に拡大縮小する「resampling.js」の使い方[公式]
画像を高品質に拡大、縮小する「resampling.js」の使い方です。
ブラウザがChromeの場合は、Chromeのセキュリティ仕様でローカルで実行するとエラーが発生します。回避策はサーバーにHTMLファイルをアップするか、エラー回避方法をご覧ください。
ダウンロード
resampling.js
ダウンロードの方法がわからない方はこちらからです。
使い方
サンプルコード
<script src="resampling.js"></script>
<button onclick="double();" style="font-size:32px;">size * 2</button>
<button onclick="half();" style="font-size:32px;">size * 0.5(50%)</button>
<p>[元画像]</p>
<img id="SrcImage" src="test.png">
<p>[拡大縮小後]</p>
<canvas id="DstCanvas"></canvas>
<script>
var src_img = document.getElementById("SrcImage");
var dst_canvas = document.getElementById("DstCanvas");
var dst_ctx = dst_canvas.getContext("2d");
function double(){
// 元画像の描画
dst_canvas.width = src_img.width;
dst_canvas.height = src_img.height;
dst_ctx.drawImage(src_img,0,0);
// ImageDataの生成
var source = dst_ctx.getImageData(0,0,dst_canvas.width,dst_canvas.height);
dst_canvas.width = (src_img.width) * 2;
dst_canvas.height = (src_img.height)* 2;
var destination = dst_ctx.createImageData(dst_canvas.width,dst_canvas.height);
// 拡大縮小の実行
EffectResampling(source,destination,BiCubic_Filter,false);
// canvasへ描画
dst_ctx.putImageData(destination,0,0);
}
function half(){
// 元画像の描画
dst_canvas.width = src_img.width;
dst_canvas.height = src_img.height;
dst_ctx.drawImage(src_img,0,0);
// ImageDataの生成
var source = dst_ctx.getImageData(0,0,dst_canvas.width,dst_canvas.height);
dst_canvas.width = Math.round((src_img.width) * 0.5);
dst_canvas.height = Math.round((src_img.height) * 0.5);
var destination = dst_ctx.createImageData(dst_canvas.width,dst_canvas.height);
// 拡大縮小の実行
EffectResampling(source,destination,BiCubic_Filter,true);
// canvasへ描画
dst_ctx.putImageData(destination,0,0);
}
</script>
テスト用画像のtest.pngはこちらからダウンロード可能です。
関数
| リサンプリング | |
|---|---|
| 関数 | EffectResampling (source,destination,interpolationfilter,prefilter) |
| 引数 | source : ImageDataオブジェクト destination: ImageDataオブジェクト interpolationfilter: 補間フィルタ ※常にBiCubic_Filter prefilter: [省略可能]事前フィルタ(ぼかし) true or false(null) |
| 戻り値 | destination |
| 備考 | 事前フィルタを使用すると高品質に縮小する事が可能です。逆に、拡大で使用すると品質が落ちますのでご注意ください。 |
応用
このまま関数を実行すると、JavaScriptはシングルスレッドですので重いです。そこで、HTML5の新機能であるWeb Workerを使用するとマルチスレッドで並列処理が可能です。
Web Workerの使い方はWeb Workerを使用してプログレスバーをマルチスレッドで動かすをご覧ください。
スポンサーリンク
関連記事
公開日:2016年12月14日 最終更新日:2016年12月15日
記事NO:02227
プチモンテ ※この記事を書いた人
![]() | |
![]() | 💻 ITスキル・経験 サーバー構築からWebアプリケーション開発。IoTをはじめとする電子工作、ロボット、人工知能やスマホ/OSアプリまで分野問わず経験。 画像処理/音声処理/アニメーション、3Dゲーム、会計ソフト、PDF作成/編集、逆アセンブラ、EXE/DLLファイルの書き換えなどのアプリを公開。詳しくは自己紹介へ |
| 🎵 音楽制作 BGMは楽器(音源)さえあれば、何でも制作可能。歌モノは主にロック、バラード、ポップスを制作。歌詞は抒情詩、抒情的な楽曲が多い。楽曲制作は🔰2023年12月中旬 ~ | |









