Gray = R*0.299 + G*0.587 + B*0.114
Gray=(R*30+G*59+B*11)/100
1 import java.io.*; 2 import javax.imageio.ImageIO; 3 import java.awt.image.*; 4 5 6 public class imageTest() { 7 public static void main(String args[]){ 8 BufferedImage grayImage = null; 9 grayImage = imageTest.imageToGray("C:\\imageForTest.jpg"); 10 //会保存在当前工程的目录下 11 ImageIO.write(grayImage, "JPEG", new File("grayImage.jpg")); 12 } 13 14 public static BufferedImage imageToGray(String imagePath){ 15 BufferedImage image = null; 16 BufferedImage grayImage = null; 17 int gray = 0; 18 try { 19 File imagef = new File(imagePath); 20 image = ImageIO.read(imagef); 21 22 if(!imagef.exists()){ 23 System.out.println("image not found!"); 24 return grayImage; 25 } 26 int height = image.getHeight(); 27 int width = image.getWidth(); 28 int minX = image.getMinX(); 29 int minY = image.getMinY(); 30 31 grayImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); 32 33 for(int i=minX; i<width; i++) { 34 for(int j=minY; j<height; j++) { 35 int[] RGB = {0, 0, 0}; 36 //将24bit中存储的RGB值单个提取出来,可以理解为byte转int 37 RGB[0] = (image.getRGB(i, j) & 0xff0000) >> 16; 38 RGB[1] = (image.getRGB(i, j) & 0xff00) >> 8; 39 RGB[2] = (image.getRGB(i, j) & 0xff); 40 41 //这里是将RGB分别乘上一个权重,得出相应的灰度值gray 42 gray = (30*RGB[0] + 59*RGB[1] + 11*RGB[2]) / 100; 43 //将得出的灰度值转换成计算机中存储的模式 44 int rgb_togray = ((gray & 0xff)<<16 ) | ((gray & 0xff)<<8) | (gray & 0xff); 45 grayImage.setRGB(i, j, rgb_togray); 46 } 47 } 48 }catch(IOException e) { 49 e.printStackTrace(); 50 } 51 return grayImage; 52 } 53 }