java – 将负像转换为正数

前端之家收集整理的这篇文章主要介绍了java – 将负像转换为正数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我已经扫描了我的电脑上的旧电影.我想写一个小程序来将负面图像转换为正的状态.

我知道有几个图像编辑器应用程序,我可以用来实现这种转换,但我正在研究如何操纵像素通过一个小的应用程序自己转换.

有人可以给我一个头开始吗?如果可能,示例代码也将不胜感激.

解决方法

我刚刚写了一个工作示例.给出以下输入图像img.png.

输出将是一个新的图像invert-img.png like

  1. import java.awt.*;
  2. import java.awt.image.BufferedImage;
  3. import java.io.File;
  4. import java.io.IOException;
  5. import javax.imageio.ImageIO;
  6.  
  7. class Convert
  8. {
  9. public static void main(String[] args)
  10. {
  11. invertImage("img.png");
  12. }
  13.  
  14. public static void invertImage(String imageName) {
  15. BufferedImage inputFile = null;
  16. try {
  17. inputFile = ImageIO.read(new File(imageName));
  18. } catch (IOException e) {
  19. e.printStackTrace();
  20. }
  21.  
  22. for (int x = 0; x < inputFile.getWidth(); x++) {
  23. for (int y = 0; y < inputFile.getHeight(); y++) {
  24. int rgba = inputFile.getRGB(x,y);
  25. Color col = new Color(rgba,true);
  26. col = new Color(255 - col.getRed(),255 - col.getGreen(),255 - col.getBlue());
  27. inputFile.setRGB(x,y,col.getRGB());
  28. }
  29. }
  30.  
  31. try {
  32. File outputFile = new File("invert-"+imageName);
  33. ImageIO.write(inputFile,"png",outputFile);
  34. } catch (IOException e) {
  35. e.printStackTrace();
  36. }
  37. }
  38. }

如果要创建单色图像,可以将col的计算改为如下:

  1. int MONO_THRESHOLD = 368;
  2. if (col.getRed() + col.getGreen() + col.getBlue() > MONO_THRESHOLD)
  3. col = new Color(255,255,255);
  4. else
  5. col = new Color(0,0);

以上将给您以下图像

您可以调整MONO_THRESHOLD以获得更令人愉快的输出.增加数字会使像素变暗,反之亦然.

猜你在找的Java相关文章