【java/image】使用梯度表的方式对图像进行反色处理
【需求】
从通达信截取的K线图是黑底白色,需要进行反色处理,再由打印机打印出来。
【代码】
package test240313; import java.awt.image.BufferedImage; import java.awt.image.ByteLookupTable; import java.awt.image.LookupOp; import java.io.File; import javax.imageio.ImageIO; /** * 将单张图像进行反色处理 * */ public class ImageTest2 { public static void main(String[] args) throws Exception { // 读png文件 File inFile = new File("C:\\Users\\ufo\\Desktop\\2024-03-13_210728.png"); BufferedImage img = ImageIO.read(inFile); BufferedImage inversedImg = inverseColor(img); // 写入新文件 File outFile = new File("C:\\Users\\ufo\\Desktop\\2.png"); ImageIO.write(inversedImg, "png", outFile); } /** * 返回反色处理后的新图像 * @param image * @return */ public static BufferedImage inverseColor(BufferedImage image) { byte reverse[] = new byte[256]; for (int j = 0; j < 256; j++) { reverse[j] = (byte) (255 - j); } ByteLookupTable blut = new ByteLookupTable(0, reverse); BufferedImage bimg = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB); LookupOp lop = new LookupOp(blut, null); lop.filter(image, bimg); return bimg; } }
【参考资料】
https://www.jianshu.com/p/6b2bbf95aee0
END