如何在Android OpenGL中实现亮度与对比度合一滤镜
Combined Brightness & Contrast Filter Implementation
Got it! Combining brightness and contrast into a single filter is a great way to keep your code streamlined while letting both parameters work independently. Here's a complete, modified implementation that does exactly that:
Full Filter Class Code
public class GlBrightnessContrastFilter extends GlFilter { private static final String FRAGMENT_SHADER = "" + "precision mediump float;" + " varying vec2 vTextureCoord;\n" + " \n" + " uniform lowp sampler2D sTexture;\n" + " uniform lowp float brightness;\n" + " uniform lowp float contrast;\n" + " \n" + " void main()\n" + " {\n" + " lowp vec4 textureColor = texture2D(sTexture, vTextureCoord);\n" + " \n" + " // First adjust contrast, then brightness to keep parameters independent\n" + " lowp vec3 adjustedColor = ((textureColor.rgb - vec3(0.5)) * contrast + vec3(0.5));\n" + " adjustedColor += vec3(brightness);\n" + " \n" + " gl_FragColor = vec4(adjustedColor, textureColor.w);\n" + " }"; private float brightness = 0f; private float contrast = 1f; // Default: no contrast change public GlBrightnessContrastFilter() { super(DEFAULT_VERTEX_SHADER, FRAGMENT_SHADER); } public void setBrightness(float brightness) { this.brightness = brightness; } public void setContrast(float contrast) { this.contrast = contrast; } @Override public void onDraw() { // Pass both parameters to the shader GLES20.glUniform1f(getHandle("brightness"), this.brightness); GLES20.glUniform1f(getHandle("contrast"), this.contrast); } }
Key Changes Explained
1. Fragment Shader Updates
- Added the
contrastuniform variable alongsidebrightness - Adjusted the color calculation order:
- First handle contrast by shifting colors around the neutral gray value (
0.5), multiplying by the contrast factor, then shifting back. This ensures contrast adjustments don't alter the base brightness level. - Then add the brightness offset to the contrast-adjusted color, keeping both effects independent.
- First handle contrast by shifting colors around the neutral gray value (
2. Java Class Updates
- Renamed the class to
GlBrightnessContrastFilterto reflect its new functionality - Added a
contrastmember variable with a default value of1.0(which means no contrast change initially) - Implemented the
setContrast()setter method to update the contrast parameter - Updated the
onDraw()method to pass both the brightness and contrast values to the shader usingglUniform1f()
Parameter Range Recommendations
- Brightness: Stick to values between
-1.0(full black) and1.0(full white).0.0is the original image brightness. - Contrast: Use values between
0.0(flat gray image) and2.0(high contrast).1.0maintains the original image contrast.
内容的提问来源于stack exchange,提问作者Aadi
相关产品推荐
相关产品推荐

