我想在画布上保存图像的像素值。我编写了一个代码来提取点击位置(图像上)的像素值。我想将r,g,b的值保存到文本文件中,以便在python flask中完成的服务器端处理中使用它们。
var imageLoader = document.getElementById('imageLoader');
imageLoader.addEventListener('change', handleImage, false);
var canvas = document.getElementById('imageCanvas');
var ctx = canvas.getContext('2d');
function handleImage(e){
var reader = new FileReader();
reader.onload = function(event){
var img = new Image();
img.onload = function(){
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img,0,0);
}
img.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
}
canvas.onclick = function(e) {
var x = e.pageX;
var y = e.pageY;
var canvasColor = context.getImageData(x, y, 1,1); // rgba e [0,255]
var pixels = canvasColor.data;
var r = pixels[0];
var g = pixels[1];
var b = pixels[2];
// i want to save r,g,b values in a text file for usage in the flask backend
}
<script type = "text/javascript" src="http://fiddle.jshell.net/js/lib/mootools-core-1.4.5-nocompat.js"></script>
<label>Image File:</label><br/>
<input type="file" id="imageLoader" name="imageLoader"/>
<canvas id="imageCanvas"></canvas>
答案 0 :(得分:0)
您可以修改您的功能,如:
canvas.onclick = function(e) {
var x = e.pageX;
var y = e.pageY;
var canvasColor = context.getImageData(x, y, 1,1); // rgba e [0,255]
var pixels = canvasColor.data;
var r = pixels[0];
var g = pixels[1];
var b = pixels[2];
// i want to save r,g,b values in a text file for usage in the flask backend
//asign rgb values to the input
document.getElementById('imageLoader').value = r + ',' + g + ',' + b;
}
然后使用常规表单(提交按钮)使用Ajax o发送并保存在文本文件中。