代码如下:
package com.baidu.demo019;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.*;
public class App extends JFrame {
private static final long serialVersionUID = 1L;
public App() {
this.setSize(500, 500);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Box box = Box.createVerticalBox();
this.add(box);
// 源图像路径
String imageFile = "images/demo019.bmp";
// 源图像
BufferedImage image1 = getImage(imageFile);
JLabel label1 = new JLabel(new ImageIcon(image1));
JPanel panel1 = new JPanel(new BorderLayout());
panel1.add(label1);
box.add(panel1);
// 转换后的图像
Image image2 = translateImage(image1);
JLabel label2 = new JLabel(new ImageIcon(image2));
JPanel panel2 = new JPanel(new BorderLayout());
panel2.add(label2);
box.add(panel2);
}
BufferedImage getImage(String imageFile) {
BufferedImage image = null;
try {
image = ImageIO.read(new File(imageFile));
} catch (IOException e) {
e.printStackTrace();
}
return image;
}
// 转换图像 黑底白字转换为白底黑字,白色设置为透明色
private Image translateImage(BufferedImage image) {
int width = image.getWidth();
int height = image.getHeight();
BufferedImage target = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
int val = image.getRGB(i, j);
int red = (val >> 16) & 0xff;
int green = (val >> 8) & 0xff;
int blue = val & 0xff;
red = 255 - red;
green = 255 - green;
blue = 255 - blue;
int alpha = 0xff;
if ((red + green + blue) / 3 >= 0xff) {
alpha = 0x00;
}
int pixel = (alpha << 24) | (red << 16) | (green << 8) | (blue);
target.setRGB(i, j, pixel);
}
}
return target;
}
public static void main(String[] args) {
new App().setVisible(true);
}
}
运行结果: