import java.awt.*;
import java.awt.image.*;
import javax.swing.*;
public class ReflectImageBuilder {
public static enum Mode {
LINEAR, EXP
}
public static Image createReflectImage(Image img) {
return createReflectImage(img, Mode.LINEAR);
}
public static Image createReflectImage(Image img, Mode mode) {
// 从图片中提取像素数据
int w = img.getWidth(null);
int h = img.getHeight(null);
int[] pixels = new int[w * h];
PixelGrabber pg = new PixelGrabber(img, 0, 0, w, h, pixels, 0, w);
try {
pg.grabPixels();
} catch (Exception ex) {
}
for (int y = 0; y < h; ++y) {
float p = (float) (y) / h; // 每一行的透明度0~255
if (mode == Mode.EXP) {
p *= p;
}
int a = (int) (p * 255);
for (int x = 0; x < w; ++x) {
int rgb = pixels[y * w + x] & 0xFFFFFF;
pixels[y * w + x] = (a << 24) | rgb;
}
}
// 翻转图像
for (int y = 0; y < h / 2; ++y) {
for (int x = 0; x < w; ++x) {
int temp = pixels[y * w + x];
pixels[y * w + x] = pixels[(h - 1 - y) * w + x];
pixels[(h - 1 - y) * w + x] = temp;
}
}
// 使用像素数据创建镜面图像
MemoryImageSource source = new MemoryImageSource(w, h, pixels, 0, w);
Image reflectImg = Toolkit.getDefaultToolkit().createImage(source);
pixels = null;
return reflectImg;
}
public static void main(String[] args) {
String imgName = "a.jpg";
if (args.length == 1) {
imgName = args[0];
}
Image srcImage = new ImageIcon(imgName).getImage();
Image reflectImage = ReflectImageBuilder.createReflectImage(srcImage, ReflectImageBuilder.Mode.EXP);
JPanel panel = new ImagePanel(srcImage, reflectImage);
JFrame frame = new JFrame();
frame.getContentPane().add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 800);
frame.setVisible(true);
}
}
class ImagePanel extends JPanel {
private Image srcImg;
private Image reflectImg;
public ImagePanel(Image srcImg, Image reflectImg) {
this.srcImg = srcImg;
this.reflectImg = reflectImg;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(srcImg, 0, 0, this);
g2d.drawImage(reflectImg, 0, srcImg.getHeight(null), this);
}
}