package fancy.jf.unsorted;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class ColorAlternation {
public static void main(String args[]) throws IOException, InterruptedException {
// get some sample data
final BufferedImage sample = ImageIO.read(ColorAlternation.class.getResource("/pic.png"));
// setup our buffered work image
final BufferedImage work = new BufferedImage(sample.getWidth(), sample.getHeight(), BufferedImage.TYPE_INT_ARGB);
final Graphics2D g = work.createGraphics();
g.drawImage(sample, 0, 0, null);
g.dispose();
// setup color src and dst
final Color srcColor = new Color(0, 0, 0, 0);
final Color dstColor = new Color(255, 255, 0, 255);
final int src = (srcColor.getAlpha() << 24) | (srcColor.getRed() << 16) | (srcColor.getGreen() << 8) | (srcColor.getBlue() << 0);
final int dst = (dstColor.getAlpha() << 24) | (dstColor.getRed() << 16) | (dstColor.getGreen() << 8) | (dstColor.getBlue() << 0);
// setup threads
final int maxThreads = 4;
final Thread[] threads = new Thread[maxThreads];
final long timeThreads = System.currentTimeMillis();
// several times because it is so fast
for (int j = 0; j < 1000; j++) {
final int[] pixels = ((DataBufferInt) work.getRaster().getDataBuffer()).getData();
for (int i = 0; i < maxThreads; i++) {
final int thread = i;
threads[i] = new Thread(new Runnable() {
public void run() {
for (int i = thread; i < pixels.length; i += maxThreads) {
// replace pixel
if (pixels[i] == src) pixels[i] = dst;
}
}
});
threads[i].start();
}
// wait for all threads
for (int i = 0; i < maxThreads; i++) {
threads[i].join();
}
}
System.out.println((System.currentTimeMillis() - timeThreads) / 1000.0);
// show image
final JFrame frame = new JFrame();
final JLabel label = new JLabel(new ImageIcon(work));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(label);
frame.pack();
frame.setVisible(true);
}
}