4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Canvas を使って画像をグレースケールに変換する

Last updated at Posted at 2016-11-05

Canvas を使って、画像をグレースケールに変換する方法です。
処理の流れは以下の通りです。

  1. Canvas に元画像を描画する
  2. Canvas 上で画像をグレースケールに変換する
  3. 変換した画像を base64 形式で書き出す
  4. 画像の src 属性を書き換える

ソース

app.js
$(window).load(function() {
	$("img").each(function() {

		// キャンバスに画像を描画する
		var canvas = document.createElement("canvas");
		var ctx = canvas.getContext("2d");
		var img = new Image();
		img.src = $(this).attr("src");
		canvas.width = img.width;
		canvas.height = img.height;
		ctx.drawImage(img, 0, 0);

		// 画像の各ピクセルをグレースケールに変換する
		var pixels = ctx.getImageData(0, 0, canvas.width, canvas.height);
		for (var y = 0; y < pixels.height; y++) {
			for (var x = 0; x < pixels.width; x++) {
				var i = (y * 4) * pixels.width + x * 4;
				var rgb = parseInt((pixels.data[i] + pixels.data[i + 1] + pixels.data[i + 2]) / 3, 10);
				pixels.data[i] = rgb;
				pixels.data[i + 1] = rgb;
				pixels.data[i + 2] = rgb;
			}
		}
		ctx.putImageData(pixels, 0, 0, 0, 0, pixels.width, pixels.height);

		// 画像を差し替える
		$(this).attr("src", canvas.toDataURL());
	});
});
index.html
<!DOCTYPE html>
<html lang="ja">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width">
	<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
	<script src="js/app.js"></script>
	<title>Image to Grayscale</title>
</head>
<body>
	<p><img src="img/photo_1.jpg"></p>
	<p><img src="img/photo_2.jpg"></p>
	<p><img src="img/photo_3.jpg"></p>
</body>
</html>

結果

grayscale.png

4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?