Java – converts a negative image to a positive number

I have scanned my computer for old movies I want to write a small program to convert negative images into positive ones

I know there are several image editor applications that I can use to implement this conversion, but I'm studying how to manipulate pixels to convert themselves through a small application

Can someone give me a head to start? If possible, the sample code will also be appreciated

Solution

I just wrote a working example The following input image img png.

The output will be a new image, convert 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();
        }
    }
}

If you want to create a monochrome image, you can change the calculation of col to the following:

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);

The above will give you the following image

You can adjust mono_ Threshold for a more pleasant output Increasing the number darkens the pixels and vice versa

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>