在画布内部渲染图像后,我试图获取图像的rgb值。但是我得到全0的回报。我在渲染图像后不确定是否为什么要得到0来尝试使用getImageData()。
我的代码:
fileSelected: File;
preview: any;
context: CanvasRenderingContext2D;
hue: any;
myImageData:any
onFileSelect(e: any) {
let canvas = this.mycanvas.nativeElement;
let context = canvas.getContext('2d');
context.clearRect(0, 0, canvas.width, canvas.height)
let imgData;
this.fileSelected = e.target.files[0];
let reader = new FileReader()
reader.onload = (e: any) => {
var image = new Image();
image.onload = function () {
image.width = canvas.width;
image.height = canvas.height;
context.drawImage(image, 0, 0, canvas.width, canvas.height)
};
image.src = e.target.result
}
reader.readAsDataURL(this.fileSelected);
this.myImageData = context.getImageData(0, 0, 100, 100);
this.hue = this.calculateHue(this.fileSelected, this.myImageData);
}
calculateHue(file, myImageData) {
console.log("rgb====", myImageData.data)
return null
}
我已经通过这些链接getImageData() returning all zeros,getImageData() returning all 0's,getImageData always returning 0
但是没有一个答案能解决它。我在做什么错了?
答案 0 :(得分:1)
加载图像后,您将立即写入画布,但是一旦选择了文件,便尝试从画布中读取内容,
this.myImageData = context.getImageData(0, 0, 100, 100);
this.hue = this.calculateHue(this.fileSelected, this.myImageData);
进入image.onload
并在context.drawImage(image, 0, 0, canvas.width, canvas.height)
调用之后,因此确保有可以读取的图像数据。
它应该看起来像这样:
onFileSelect(e: any) {
let canvas = this.mycanvas.nativeElement;
let context = canvas.getContext('2d');
context.clearRect(0, 0, canvas.width, canvas.height)
let imgData;
this.fileSelected = e.target.files[0];
let reader = new FileReader();
let self = this;
reader.onload = (e: any) => {
var image = new Image();
image.onload = () => {
image.width = canvas.width;
image.height = canvas.height;
context.drawImage(image, 0, 0, canvas.width, canvas.height)
// Move it here
self.myImageData = context.getImageData(0, 0, 100, 100);
self.hue = this.calculateHue(self.fileSelected, self.myImageData);
};
image.src = e.target.result
}
reader.readAsDataURL(this.fileSelected);
}