Change the alpha value of a BufferedImage?

后端 未结 6 1704
清酒与你
清酒与你 2020-12-11 04:21

How do I change the global alpha value of a BufferedImage in Java? (I.E. make every pixel in the image that has a alpha value of 100 have a alpha value of 80)

6条回答
  •  無奈伤痛
    2020-12-11 04:41

    This is an old question, so I'm not answering for the sake of the OP, but for those like me who find this question later.

    AlphaComposite

    As @Michael's excellent outline mentioned, an AlphaComposite operation can modify the alpha channel. But only in certain ways, which to me are somewhat difficult to understand:

    enter image description here

    is the formula for how the "over" operation affects the alpha channel. Moreover, this affects the RGB channels too, so if you have color data that needs to be unchanged, AlphaComposite is not the answer.

    BufferedImageOps

    LookupOp

    There are several varieties of BufferedImageOp (see 4.10.6 here). In the more general case, the OP's task could be met by a LookupOp, which requires building lookup arrays. To modify only the alpha channel, supply an identity array (an array where table[i] = i) for the RGB channels, and a separate array for the alpha channel. Populate the latter array with table[i] = f(i), where f() is the function by which you want to map from old alpha value to new. E.g. if you want to "make every pixel in the image that has a alpha value of 100 have a alpha value of 80", set table[100] = 80. (The full range is 0 to 255.) See how to increase opacity in gaussian blur for a code sample.

    RescaleOp

    But for a subset of these cases, there is a simpler way to do it, that doesn't require setting up a lookup table. If f() is a simple, linear function, use a RescaleOp. For example, if you want to set newAlpha = oldAlpha - 20, use a RescaleOp with a scaleFactor of 1 and an offset of -20. If you want to set newAlpha = oldAlpha * 0.8, use a scaleFactor of 0.8 and an offset of 0. In either case, you again have to provide dummy scaleFactors and offsets for the RGB channels:

    new RescaleOp({1.0f, 1.0f, 1.0f, /* alpha scaleFactor */ 0.8f},
                  {0f, 0f, 0f, /* alpha offset */ -20f}, null)
    

    Again see 4.10.6 here for some examples that illustrate the principles well, but are not specific to the alpha channel.

    Both RescaleOp and LookupOp allow modifying a BufferedImage in-place.

提交回复
热议问题