JavaScript过滤器GB
我目前正在将Java转换为JavaScript,需要更改一些图像的颜色 现在,每个图像都加载到JavaScript过滤器GB,java,javascript,image,canvas,Java,Javascript,Image,Canvas,我目前正在将Java转换为JavaScript,需要更改一些图像的颜色 现在,每个图像都加载到image类中,图像如下所示: class VDColorFilter extends RGBImageFilter { int fg; int bg; final int[] colors; public VDColorFilter(final int fgc, final int bgc) { super(); this.colors
image
类中,图像如下所示:
class VDColorFilter extends RGBImageFilter
{
int fg;
int bg;
final int[] colors;
public VDColorFilter(final int fgc, final int bgc) {
super();
this.colors = new int[] { 0, 16711680, 65280, 16776960, 255, 16711935, 65535, 16777215 };
this.fg = fgc;
this.bg = bgc;
this.canFilterIndexColorModel = true;
}
public int filterRGB(final int x, final int y, int rgb) {
if (rgb == -1) {
rgb = (0xFF000000 | this.colors[this.bg]);
}
else if (rgb == -16777216) {
rgb = (0xFF000000 | this.colors[this.fg]);
}
return rgb;
}
}
它是一个PNG,作为一个字符集工作,通过它发送的数据映射到图像中的每个字符
现有Java代码如下所示:
class VDColorFilter extends RGBImageFilter
{
int fg;
int bg;
final int[] colors;
public VDColorFilter(final int fgc, final int bgc) {
super();
this.colors = new int[] { 0, 16711680, 65280, 16776960, 255, 16711935, 65535, 16777215 };
this.fg = fgc;
this.bg = bgc;
this.canFilterIndexColorModel = true;
}
public int filterRGB(final int x, final int y, int rgb) {
if (rgb == -1) {
rgb = (0xFF000000 | this.colors[this.bg]);
}
else if (rgb == -16777216) {
rgb = (0xFF000000 | this.colors[this.fg]);
}
return rgb;
}
}
我希望能够对我的图像做同样的事情,但是使用JavaScript。我对Java没有太多的经验,因此我不确定filterRGB
如何实际应用RGB结果,而不是colors
数组
当然,这只是给图像的黑色上色,而不是白色
有没有类似的图书馆?如果没有,我获得相同结果的最佳方法是什么?您可以使用
getImageData()
和putImageData()
过滤图像。这需要实现跨源资源共享(CORS),例如,图像与页面来自同一服务器(浏览器中的安全机制)
如果这部分还可以,让我们用你的图片做一个例子-
最好是你的图像有一个阿尔法通道而不是白色背景。这将允许您使用复合操作符直接更改颜色,而无需解析像素
您可以通过两种方式执行此操作:
var data32 = new Uint32Array(idata.data.buffer);
有关详细信息,请参见下面的代码:
var img=newimage();
img.crossOrigin=“”;
img.onload=punchOut;
img.src=“//i.imgur.com/8NWz72w.png”;
函数punchOut(){
var canvas=document.createElement(“画布”),
ctx=canvas.getContext(“2d”);
document.body.appendChild(本文件);
document.body.appendChild(画布);
//设置画布大小=图像大小
canvas.width=this.naturalWidth;
canvas.height=this.naturalHeight;
//画图
ctx.drawImage(this,0,0);
//获取像素数据
var idata=ctx.getImageData(0,0,canvas.width,canvas.height),
data32=新的uint32数组(idata.data.buffer),//创建一个uint32缓冲区
i=0,len=data32.length;
而(我
body{background:#aaa}
这太棒了!然而,我的问题是,图像的颜色也需要根据上面的Java代码进行计算。对于屏幕上写的每个“字符”,颜色可以不同,并根据颜色进行过滤。“关于如何实现同样的效果,你有什么想法吗?”詹姆斯:当然,只要把fillRect限制在字母区域,这样只有字母会受到颜色变化的影响。好的,酷。最后,图像需要以某种颜色加载,然后我使用drawImage
功能将其添加到画布上,但当我应用上面的代码时,绘制的唯一图像是整个加载的图像,而不是剪下的字符?@James添加了第三个从地图上随机书写字母的演示。当然,随机的x和y应该被替换为使用字符串映射将所有字母转换为实际字母的索引。不要担心字符的书写,我现在已经有了一个:)我的问题是,我需要能够更改字符的颜色,然后对更改后的图像使用drawImage
。只是,这不适用于onload
。我几乎需要使用putImageData
或其他什么?