Advertisement
iccaka

Java Image ASCII Converter

Nov 3rd, 2019
289
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.93 KB | None | 0 0
  1. import javax.imageio.ImageIO;
  2. import java.awt.*;
  3. import java.awt.image.*;
  4. import java.io.File;
  5. import java.io.IOException;
  6. import java.io.PrintWriter;
  7. import java.util.Objects;
  8.  
  9. class Main {
  10.  
  11.     private final static String DEFAULT_ORIGINAL_IMAGE_PATH = "images/google.png";
  12.     private final static String DEFAULT_ASCII_IMAGE_PATH = "images/copy.txt";
  13.  
  14.     public static void main(String[] args) {
  15.  
  16.         BufferedImage image = null;
  17.         Color color;
  18.         PrintWriter pw = null;
  19.  
  20.         try {
  21.             image = ImageIO.read(new File(DEFAULT_ORIGINAL_IMAGE_PATH));
  22.             pw = new PrintWriter(new File(DEFAULT_ASCII_IMAGE_PATH));
  23.         } catch (IOException | NullPointerException e) {
  24.             System.out.println(e.getMessage());
  25.         }
  26.  
  27.         try {
  28.             for (int i = 0; i < image.getHeight(); i++) {
  29.                 for (int j = 0; j < image.getWidth(); j++) {
  30.                     color = new Color(image.getRGB(j, i));
  31.                     double colorValue = ((double) color.getRed() + (double) color.getBlue() + (double) color.getGreen()) / 3;
  32.                     Objects.requireNonNull(pw).append(getCharRepresentation(colorValue));
  33.                 }
  34.             }
  35.         } catch (NullPointerException npe) {
  36.             System.out.println(npe.getMessage());
  37.         }
  38.     }
  39.  
  40.     private static char getCharRepresentation(double value) {
  41.         if (value >= 230.0) {
  42.             return ' ';
  43.         } else if (value >= 200.0) {
  44.             return '.';
  45.         } else if (value >= 180.0) {
  46.             return '*';
  47.         } else if (value >= 160.0) {
  48.             return ':';
  49.         } else if (value >= 130.0) {
  50.             return 'o';
  51.         } else if (value >= 100.0) {
  52.             return '&';
  53.         } else if (value >= 70.0) {
  54.             return '8';
  55.         } else if (value >= 50.0) {
  56.             return '#';
  57.         } else {
  58.             return '@';
  59.         }
  60.     }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement