Skip to content

Commit

Permalink
添加一个获取图片数据的示例
Browse files Browse the repository at this point in the history
  • Loading branch information
plter committed Mar 21, 2018
1 parent b9d88cd commit 4f68bfb
Show file tree
Hide file tree
Showing 4 changed files with 61 additions and 0 deletions.
50 changes: 50 additions & 0 deletions GetPhotoData/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
(async function () {

function loadPhoto(src) {
return new Promise(function (resolve, reject) {
let img = new Image();
img.onload = function () {
resolve(img);
};
img.onerror = reject;
img.src = src;
});
}

let canvas = document.querySelector("#canvas");
let context2d = canvas.getContext("2d");
let img = await loadPhoto("spring.png");
context2d.drawImage(img, 0, 0);
let imageData = context2d.getImageData(0, 0, 200, 200);

let redImageData = context2d.createImageData(200, 200);
let greenImageData = context2d.createImageData(200, 200);
let blueImageData = context2d.createImageData(200, 200);
let blackAndWhiteImageData = context2d.createImageData(200, 200);
for (let i = 0; i < imageData.data.length; i += 4) {
redImageData.data[i] = imageData.data[i];
redImageData.data[i + 1] = 0;
redImageData.data[i + 2] = 0;
redImageData.data[i + 3] = 255;

greenImageData.data[i] = 0;
greenImageData.data[i + 1] = imageData.data[i + 1];
greenImageData.data[i + 2] = imageData.data[i + 2];
greenImageData.data[i + 3] = 255;

blueImageData.data[i] = 0;
blueImageData.data[i + 1] = 0;
blueImageData.data[i + 2] = imageData.data[i + 2];
blueImageData.data[i + 3] = 255;

let color = Math.round((imageData.data[i] + imageData.data[i + 1] + imageData.data[i + 2]) / 3);
blackAndWhiteImageData.data[i] = color;
blackAndWhiteImageData.data[i + 1] = color;
blackAndWhiteImageData.data[i + 2] = color;
blackAndWhiteImageData.data[i + 3] = 255;
}
context2d.putImageData(redImageData, 200, 0);
context2d.putImageData(greenImageData, 0, 200);
context2d.putImageData(blueImageData, 200, 200);
context2d.putImageData(blackAndWhiteImageData, 0, 400);
})();
11 changes: 11 additions & 0 deletions GetPhotoData/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<canvas style="border-style: solid;" width="400" height="600" id="canvas"></canvas>
<script src="app.js"></script>
</body>
</html>
Binary file added GetPhotoData/spring.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified 机器学习之手写识别.pptx
Binary file not shown.

0 comments on commit 4f68bfb

Please sign in to comment.