最近朋友让我帮他一个忙,就是给他的图片中所有的棕色换成黑色,我深深感觉到了这个任务的艰巨,不会使用PS怎么办呢?已经答应了,怎么办呢?我一定可以的,怎么办呢?

怎么办呢?

怎么办呢?

怎么办呢?

撸代码呗!

对Java了解比较全面的人,都知道Java有个专门针对图片有个BufferedImage这个类,这个类文档中是这么说的。什么?不理解,我就简单说说我的理解吧,其实就是它可以实现的功能主要有读取指定图片并且对固定的像素点做你想要的操作(比如我们今天需要进行像素替换)以及使用Graphics2D进行画图操作(比如可以动态的再后端生成验证码图片)等。

java 像素转换 java修改图片像素_Image


上代码

package test;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

// A79A92
public class PixelReplace {
	public static void getImagePixel(String image) throws Exception {
		File file = new File(image);
		Integer[] rgb = new Integer[3];
		BufferedImage bi = null;
		try {
			bi = ImageIO.read(file);
		} catch (Exception e) {
			e.printStackTrace();
		}
		int width = bi.getWidth();
		int height = bi.getHeight();
		int minx = bi.getMinX();
		int miny = bi.getMinY();
		for (int i = minx; i < width; i++) {
			for (int j = miny; j < height; j++) {
				int pixel = bi.getRGB(i, j); // 下面三行代码将一个数字转换为RGB数字
				rgb[0] = (pixel & 0xff0000) >> 16;
				rgb[1] = (pixel & 0xff00) >> 8;
				rgb[2] = (pixel & 0xff);
				if (rgb[0] == 0xA7 && rgb[1] == 0x9A && rgb[2] == 0x92) {
					bi.setRGB(i, j, 0);// 将此 BufferedImage 中的像素设置为指定的 RGB 值。
				}
			}
		}

		save(bi, "jpg", new File("C:\\Users\\lenovo\\Desktop\\nytest1.jpg"));
	}

	public static void save(BufferedImage image, String type, File file) throws IOException {
		ImageIO.write(image, type, file);
	}

	public static void main(String[] args) {
		String image = "C:\\Users\\lenovo\\Desktop\\nytest.jpg";
		try {
			getImagePixel(image);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

注意:写代码前我使用了一个工具取色器(获取指定焦点的像素值,代码中的A79A92就是需要替换原来的像素值,也就是我说的棕色),网上可以直接搜到,我就不放软件了,长下面这么个样子!

java 像素转换 java修改图片像素_java 像素转换_02


实现起来比较简单,还是得益于Java的功劳,毕竟面向对象的语言,要的就是简单。还有就是我这里只提供一个思路,利用这个类可以做的事很多了,比如图片的灰度化处理,加个简单的滤镜等等,都是可以的。其实现在我们对照片加滤镜,美图,去水印也和这个道理差不多,只不过在进行处理的算法可能是非常复杂的,并且同时还要保证处理过的图片美感依然存在!看个效果图吧(中间的我给反色了,免得朋友看见骂我)!!!总觉得这样骂的我更凶。。。

java 像素转换 java修改图片像素_Image_03