之前也寫過一個代碼給一張圖片然后把圖片變暗,今天我們換一種思路,或者是是另外的一種方式將圖片至暗,當然方法也是很簡單的,但是對于菜鳥的我在這個地方停留了一天半的時間,將圖片至暗
現在我們要將這樣的一張圖片
變成為
雖然說變暗之后確實沒有之間亮的好看,但是不管了,反正那么漂亮的美女和我的關系我不太大,如果說硬是有關系的話,那應該是在夢中了,好了我們直接上代碼
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
|
package com.epoint.wdg.test; import java.awt.Color; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; public class ImgTest { public static void main(String[] args) throws IOException { File file= new File( "C://Users/wdg/Desktop/people.png" ); //showParamterofImg(file); File file2=changeImgtoGray(file); grayPicToBW(file2); } public static void getRGB(File file) throws IOException{ int []rgb = new int [ 3 ]; BufferedImage img=ImageIO.read(file); int pixel=img.getRGB( 2 , 3 ); // 下面三行代碼將一個數字轉換為RGB數字 rgb[ 0 ] = (pixel & 0xff0000 ) >> 16 ; rgb[ 1 ] = (pixel & 0xff00 ) >> 8 ; rgb[ 2 ] = (pixel & 0xff ); System.out.println(rgb[ 0 ]+ "-" +rgb[ 1 ]+ "-" +rgb[ 2 ]); } //把圖片變灰色 public static File changeImgtoGray(File file) throws IOException{ float []rgb = new float [ 3 ]; BufferedImage img=ImageIO.read(file); //現在我需要獲取到沒一點的rgb int y=img.getHeight(); int x=img.getWidth(); BufferedImage grayImage = new BufferedImage(x, y, BufferedImage.TYPE_BYTE_GRAY); for ( int i= 0 ;i<x;i++){ for ( int j= 0 ;j<y;j++){ int pixel=img.getRGB(i, j); // grayImage.setRGB(startX, startY, w, h, rgbArray, offset, scansize); rgb[ 0 ] = (pixel & 0xff0000 ) >> 16 ; rgb[ 1 ] = (pixel & 0xff00 ) >> 8 ; rgb[ 2 ] = (pixel & 0xff ); int gray=( int ) (rgb[ 0 ] * 0.3 + rgb[ 1 ] * 0.59 + rgb[ 2 ] * 0.11 ); Color color= new Color(gray,gray,gray); img.setRGB(i, j, color.getRGB()); } } File newFile = new File( "C://Users/wdg/Desktop/" + "/method5.jpg" ); ImageIO.write(img, "jpg" , newFile); // grayPicToBW(newFile); return newFile; } |
其中最為重要的是這一部分:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
int y=img.getHeight(); int x=img.getWidth(); for ( int i= 0 ;i<x;i++){ for ( int j= 0 ;j<y;j++){ int pixel=img.getRGB(i, j); rgb[ 0 ] = (pixel & 0xff0000 ) >> 16 ; rgb[ 1 ] = (pixel & 0xff00 ) >> 8 ; rgb[ 2 ] = (pixel & 0xff ); int gray=( int ) (rgb[ 0 ] * 0.3 + rgb[ 1 ] * 0.59 + rgb[ 2 ] * 0.11 ); Color color= new Color(gray,gray,gray); img.setRGB(i, j, color.getRGB()); } } File newFile = new File( "C://Users/wdg/Desktop/" + "/method5.jpg" ); ImageIO.write(img, "jpg" , newFile); |
這一部分是獲取到到圖片的每一點的像素或者說ARGB:
1
|
int pixel=img.getRGB(i, j); |
然后進一步的獲取到RGB,然后我們獲取到這點像素的灰度值,
1
|
int gray=( int ) (rgb[ 0 ] * 0.3 + rgb[ 1 ] * 0.59 + rgb[ 2 ] * 0.11 ); |
并且創建一個顏色:
1
2
3
|
lor color= new Color(gray,gray,gray); img.setRGB(i, j, color.getRGB()); |
這樣我們將圖片打印出來就是我們第二張圖片那樣了
以上這篇java將圖片至暗的實現方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。