Chuyển hình màu thành hình trắng xám trong Java? | How to convert color image to gray scale image?

Bài viết này sẽ hướng dẫn các bạn cách để chuyển đổi hình ảnh màu thành hình ảnh trắng xám (convert image color to image gray scale) trong ngôn ngữ lập trình Java.

JavaSource - Mã nguồn Java.

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package z.test;

/**
* @Author BUI NGOC SON
* @Website: http://vnlives.net/
* @Create: 21-11-2014
*
* Utility to convert a color image into gray color.
*/

import java.awt.color.ColorSpace;
import java.awt.image.BufferedImage;
import java.awt.image.ColorConvertOp;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class JavaConvertImageToGreyScale {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
JavaConvertImageToGreyScale jcitg = new JavaConvertImageToGreyScale();
jcitg.runTest();

}

public void runTest() {

String inputImageFilePath="D:/Image.JPG";
String outputImageFilePath="D:/Image_GrayScale.JPG";

System.out.print("Reading input image...");
BufferedImage inputImage = readImage(inputImageFilePath);
System.out.println("Successfully Read Image: "+inputImageFilePath);

System.out.print("\nConverting the image to Gray colors...");
BufferedImage imageGrayScale = convertToGrayScale(inputImage);
System.out.println("Successful...");

System.out.print("\nWriting gray image to filesystems...");
writeImage(imageGrayScale,outputImageFilePath , "jpg");
System.out.println("Successfully Wrote Image To: "+outputImageFilePath);

}

/**
* This function reads an image from the file to BufferedImage
* @param pathImage[String] (eg. "C:/testImage.jpg").
* @return BufferedImage (of the file read).
*/
public BufferedImage readImage(String pathImage) {
BufferedImage img = null;
try {
img = ImageIO.read(new File(pathImage));
} catch (IOException e) {
e.printStackTrace(System.out);
}
return img;
}

/**
* This function is use convert any BufferedImage Object
* to gray scale BufferedImage Object.
* @param BufferedImage (eg. "C:/testImage.jpg").
* @return BufferedImage (with gray scale).
*/
public BufferedImage convertToGrayScale(BufferedImage img) {
ColorConvertOp colorConvert = new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_GRAY), null);
colorConvert.filter(img, img);
return img;
}



/**
* This method writes a buffered image to a file
* @param img[BufferedImage]
* @param pathImage[String] (Write file with name to location e.g. "C:/testImage.jpg").
* @param extension[String] (e.g. "jpg","gif","png").
*/
public void writeImage(BufferedImage img, String pathImage, String extension) {
try {
BufferedImage bi = img;
File outputfile = new File(pathImage);
ImageIO.write(bi, extension, outputfile);
} catch (IOException e) {
e.printStackTrace(System.out);
}
}


}


Result - Kết quả:





Write: +Bui Ngoc Son




No comments:

Post a Comment