對Java圖片處理的內容涉獵不深,言辭簡陋望請見諒。
java實現色階調整,即調整圖片rgb分量,進而也可以調節圖片亮度。
測試代碼
1
2
3
4
5
6
7
8
|
public static void main(String[] args) { //文件與BufferedImage間的轉換 BufferedImage bi=file2img( "test.jpg" ); //讀取圖片 BufferedImage bii=img_color_gradation(bi, 100 , 0 , 0 ); img2file(bii, "jpg" , "test1.jpg" ); //生成圖片 } |
色階調整代碼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
//圖片色階調整,調整rgb的分量 public static BufferedImage img_color_gradation(BufferedImage imgsrc, int r, int g, int b) { try { //創建一個不帶透明度的圖片 BufferedImage back= new BufferedImage(imgsrc.getWidth(), imgsrc.getHeight(),BufferedImage.TYPE_INT_RGB); int width = imgsrc.getWidth(); int height = imgsrc.getHeight(); for ( int i = 0 ; i < height; i++) { for ( int j = 0 ; j < width; j++) { int pixel = imgsrc.getRGB(j, i); Color color = new Color(pixel); int red= color.getRed()+r; if (red> 255 ) red= 255 ; if (red< 0 ) red= 0 ; int green= color.getGreen()+g; if (green> 255 ) green= 255 ; if (green< 0 ) green= 0 ; int blue= color.getBlue()+b; if (blue> 255 ) blue= 255 ; if (blue< 0 ) blue= 0 ; color = new Color(red,green,blue); int x=color.getRGB(); back.setRGB(j,i,x); } } return back; } catch (Exception e) { e.printStackTrace(); return null ; } } |
圖片讀取,和存儲函數
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
//讀取圖片 public static BufferedImage file2img(String imgpath) { try { BufferedImage bufferedImage=ImageIO.read( new File(imgpath)); return bufferedImage; } catch (Exception e) { e.printStackTrace(); return null ; } } //保存圖片,extent為格式,"jpg"、"png"等 public static void img2file(BufferedImage img,String extent,String newfile) { try { ImageIO.write(img, extent, new File(newfile)); } catch (Exception e) { e.printStackTrace(); } } |
分享:
下面先給出亮度和對比度的計算公式
(RGB表示原圖的色彩分量的值,nRGB表不處理后的值,mBrightness表示調整的亮度值,mContrast表示調整的對比度值,avg表示整個圖像像素的平均值)
亮度:nRGB=RGB+mBrightness
對比度:nRGB=(RGB-avg)*(1-percent%)+avg percent%取值范圍為(-1~1) 0為原始值
對比度公式也很好證明,將其展開
nRGB=RGB-RGB*percent%-avg+avg*percent%+avg
nRGB=RGB-RGB*percent%+avg*percent%
對于整個圖像矩陣來說,要保證亮度不變,即整個矩陣的代數和不變。
而avg=(RGB1+RGB2+....RGBn)/n (1)
(nRGB1+nRGB2+.....nRGBn)=(RGB1+RGB2+...RGBn)+n*avg*percent%-(RGB1+RGB2+...RGBn)*percent% (2)
將(1)式代入(2)式即可
總結
以上就是本文關于java圖片色階調整和亮度調整代碼示例的全部內容,希望對大家有所幫助。如有不足之處,歡迎留言指出。
原文鏈接:https://www.cnblogs.com/topo/p/7671444.html