使用Processing处理图像的不透明度

时间:2011-11-03 13:56:08

标签: java image opacity processing

我想在这里做的很简单。我想在彼此的顶部有2张图片。当我使用拖动并单击顶部图像的鼠标事件时,所选顶级图像的区域将淡入淡出并使较低的图像可见。

我看到它的方式,我有两种方法可以做到这一点:

我可以让顶部图像随着时间的推移变得透明(在所选区域内) 要么 我可以以喷雾风格的方式单独删除像素。想想当天用MS涂料喷涂的工具。

这是我开始的一些非常基本的代码,它只是将图像放在彼此之上

  PImage sand;
  PImage fossil;

void setup()
{
  size(400,400);
  background(255,255,0);
  frameRate(30);

  fossil = loadImage("foss.jpg");
  sand = loadImage("sand.jpeg");
}

void draw()
{

   image(fossil, 0, 0, width,height);
   image(sand, 0, 0, width,height);
   smooth();

 if (mousePressed) {
    fill(0);
    tint(255,127); //the opacity function
  } else {
    fill(255);
  } 
}

那么有没有人对这两种创造不透明度的方法有任何评论,或者有一种我忽略的简单方法?


也许我在我的规范中并不清楚,因为下面的2条评论要求澄清。

最简单的说法是,我有两张图像。我希望能够对顶层图像进行一些修改,使底部图像可见。但是,我需要对顶级图像的一部分进行此修改。

我想知道哪个是更好的选择。使用tint()使顶部图像的一部分变为透明或从顶层删除像素。

然后我将继续这种方法。任何有关如何做的指示也表示赞赏。

我希望这可以解决任何困惑。

1 个答案:

答案 0 :(得分:3)

如果您只想在图像之间进行交叉淡入淡出,则可以使用tint()代码建议。你其实非常接近:

PImage sand;
PImage fossil;

void setup()
{
  size(400, 400);
  fossil = loadImage("CellNoise.jpg");
  sand = loadImage("CellVoronoi.jpg");
}

void draw()
{
  //tint from 255 to 0 for the top image
  tint(255,map(mouseX,0,width,255,0));
  image(fossil, 0, 0, width, height);
  //tint from 0 to 255 for the bottom image - 'cross fade'
  tint(255,map(mouseX,0,width,0,255));
  image(sand, 0, 0, width, height);
}

对于“喷雾风格”侵蚀,您只需将源图像中的像素复制到目标图像即可。这取决于你如何循环像素(多少,什么顺序等)以获得你想要的“喷雾”效果,但这里是如何使用copy()函数的基本示例:

PImage sand,fossil;
int side = 40;//size of square 'brush'
void setup()
{
  size(400, 400);
  fossil = loadImage("CellNoise.jpg");
  sand = loadImage("CellVoronoi.jpg");
}
void draw()
{
  image(fossil, 0, 0, 400, 400);
  if(mousePressed) {
    for(int y = 0 ; y < side ; y++){
       for(int x = 0; x < side; x++){
        //copy pixel from 'bottom' image to the top one
        //map sketch dimensions to sand/fossil an dimensions to copy from/to right coords
        int srcX = (int)map(mouseX+x,0,width+side,0,sand.width);
        int srcY = (int)map(mouseY+y,0,height+side,0,sand.height);
        int dstX = (int)map(mouseX+x,0,width+side,0,fossil.width);
        int dstY = (int)map(mouseY+y,0,height+side,0,fossil.height);
        fossil.set(dstX, dstY, sand.get(srcX,srcY));
       }
     }
  }
}

请注意我只是循环复制一个正方形(在我的情况下为40x40),但你可以找到其他有趣的循环方式并获得不同的效果。

玩得开心!