【java/image】采用直接操作像素的办法对png图片进行反色处理
【需求】
从通达信截取的K线图是黑底白色,需要进行反色处理,再由打印机打印出来。
【代码】
package test240313; import java.awt.image.BufferedImage; import java.io.File; import javax.imageio.ImageIO; /** * 将单张图像进行反色处理 * */ public class ImageTest { 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); // 取图像高宽 int width = img.getWidth(); int height = img.getHeight(); // 遍历每个像素进行反色处理 for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { int rgb = img.getRGB(x, y); int red = 255 - (rgb >> 16) & 0x0ff; int green = 255 - (rgb >> 8) & 0x0ff; int blue = 255 - rgb & 0x0ff; rgb = (red << 16) | (green << 8) | blue; img.setRGB(x, y, rgb); } } // 写入新文件 File outFile = new File("C:\\Users\\ufo\\Desktop\\1.png"); ImageIO.write(img, "png", outFile); } }
【代码2】
package test240314; import java.awt.image.BufferedImage; import java.io.File; import javax.imageio.ImageIO; /** * 将图像反色 * @author ufo * */ public class InversePng2 { public static void main(String[] args) throws Exception{ // 读png文件 File inFile = new File("C:\\Users\\ufo\\Desktop\\2024-03-14_101208.png"); BufferedImage srcImg = ImageIO.read(inFile); // 取原图高宽 int width = srcImg.getWidth(); int height = srcImg.getHeight(); // 创建目标图 BufferedImage dstImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); // 挨个像素进行反色 for(int i=0; i<width; i++){ for(int j=0; j<height; j++){ int rgb = srcImg.getRGB(i, j); dstImg.setRGB(i, j, 0XFFFFFF - rgb); } } // 写入新文件 File outFile = new File("C:\\Users\\ufo\\Desktop\\2.png"); ImageIO.write(dstImg, "png", outFile); } }
【参考网页】
https://www.jianshu.com/p/6b2bbf95aee0
https://blog.51cto.com/u_13488278/3210482?articleABtest=0
END