How to programmatically change contrast of a bitmap in android?

前端 未结 8 2046
眼角桃花
眼角桃花 2020-12-02 17:35

I want to programmatically change the contrast of bitmap. Till now I have tried this.

private Bitmap adjustedContrast(Bitmap src, double value)
    {
                


        
8条回答
  •  孤街浪徒
    2020-12-02 18:10

    Assumption - ImageView is used to display the bitmap

    I did a more enhancement in the Ruslan's answer

    Instead of replacing bitmap every time (which makes it slow if you are using seek bar) we can work on the Color Filter of the ImageView.

    float contrast;
    float brightness = 0;
    ImageView imageView;
    
    // SeekBar ranges from 0 to 90
    // contrast ranges from 1 to 10  
    mSeekBarContrast.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                contrast = (float) (i + 10) / 10;
                // Changing the contrast of the bitmap
                imageView.setColorFilter(getContrastBrightnessFilter(contrast,brightness));
            }
    
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
    
            }
    
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
    
            }
    });
    
    ColorMatrixColorFilter getContrastBrightnessFilter(float contrast, float brightness) {
        ColorMatrix cm = new ColorMatrix(new float[]
                {
                        contrast, 0, 0, 0, brightness,
                        0, contrast, 0, 0, brightness,
                        0, 0, contrast, 0, brightness,
                        0, 0, 0, 1, 0
                });
        return new ColorMatrixColorFilter(cm);
    }
    

    P.S - Brightness can also be changed along with contrast using this method

提交回复
热议问题