Ответ 1
Я только что написал рабочий пример. Учитывая следующее входное изображение img.png
.
Выход будет новым изображением invert-img.png
как
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
class Convert
{
public static void main(String[] args)
{
invertImage("img.png");
}
public static void invertImage(String imageName) {
BufferedImage inputFile = null;
try {
inputFile = ImageIO.read(new File(imageName));
} catch (IOException e) {
e.printStackTrace();
}
for (int x = 0; x < inputFile.getWidth(); x++) {
for (int y = 0; y < inputFile.getHeight(); y++) {
int rgba = inputFile.getRGB(x, y);
Color col = new Color(rgba, true);
col = new Color(255 - col.getRed(),
255 - col.getGreen(),
255 - col.getBlue());
inputFile.setRGB(x, y, col.getRGB());
}
}
try {
File outputFile = new File("invert-"+imageName);
ImageIO.write(inputFile, "png", outputFile);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Если вы хотите создать монохромное изображение, вы можете изменить расчет col
примерно так:
int MONO_THRESHOLD = 368;
if (col.getRed() + col.getGreen() + col.getBlue() > MONO_THRESHOLD)
col = new Color(255, 255, 255);
else
col = new Color(0, 0, 0);
Вышеупомянутое предоставит вам следующее изображение
Вы можете настроить MONO_THRESHOLD
, чтобы получить более приятный вывод. Увеличение числа сделает пиксель темнее и наоборот.