我已经扫描了我的电脑上的旧电影.我想写一个小程序来将负面图像转换为正的状态.
我知道有几个图像编辑器应用程序,我可以用来实现这种转换,但我正在研究如何操纵像素通过一个小的应用程序自己转换.
有人可以给我一个头开始吗?如果可能,示例代码也将不胜感激.
解决方法
我刚刚写了一个工作示例.给出以下输入图像img.png.
输出将是一个新的图像invert-img.png like
- 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);
以上将给您以下图像