Я пробовал использовать графический интерфейс для буферизованного изображения, но у него нет встроенного способа обработки символов новой строки, и мне кажется, что справиться с этим форматированием самостоятельно не так просто. Есть ли простой способ сделать это? Вот фрагмент незаконченного метода compressBrightness() просто преобразует значения RGB в оттенки серого и сжимает до диапазона в 70 значений, поскольку именно такое количество символов у меня есть для преобразования.
введите здесь описание изображения
Код: Выделить всё
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.Raster;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.Buffer;
import java.util.Scanner;
public class ImageToASCII {
//all ASCII characters sorted by their relative amount of white/blackspace taken up
private static final char[] gradient = {'$','@','B','%','8','&','W','M','#','*','o','a','h','k',
'b','d','p','q','w','m','Z','O','0','Q','L','C','J','U','Y','X',
'z','c','v','u','n','x','r','j','f','t','/','\\','|','(',')','1','{',
'}','[',']','?','-','_','+','~','','i','!','l','I',';',':',',',
'"','^','\'','`','.', ' '
};
private static final boolean DEBUG = true;
//default method will read from a console input
private static BufferedImage getImage(){
System.out.println("Please input an image filepath: ");
Scanner consoleInput = new Scanner(System.in);
String filepath = consoleInput.nextLine();
BufferedImage image = getImage(filepath);
return image;
}
//overloaded method which allows direct input of filepath
private static BufferedImage getImage(String filepath){
BufferedImage image = null;
try{
image = ImageIO.read(new File(filepath));
}
catch(IOException ignored){
}
return image;
}
//overloaded method which allows direct input of an image url
private static BufferedImage getImage(URL imageURL){
BufferedImage image = null;
try{
image = ImageIO.read(imageURL);
}
catch(IOException ignored){
}
return image;
}
//grayscales an image, then compresses brightness into range of 70, which is how many ascii chars we are using
private static int[] CompressBrightness(BufferedImage image){
int[] pixelVals = new int[image.getWidth()*image.getHeight()];
image.getRGB(0,0,image.getWidth(),image.getHeight(), pixelVals, 0,image.getWidth());
for(int i = 0; i < pixelVals.length; i++){
int pixel = pixelVals[i];
//in hex, a pixel is stored as AARRGGBB
//>> operator ensures we drop the end of the byte so we only get the 2 int values that matter
int blue = pixel &0xff;
int green = pixel >> 8 & 0xff;
int red = pixel >> 16 & 0xff;
int alpha = pixel >> 24 & 0xff;
/*
generally agreed upon brightness formula is
sqrt(0.299*R^2 + 0.587 *G^2 + 0.114*B^2)
https://alienryderflex.com/hsp.html
*/
int brightness = (int) Math.sqrt(
((0.299 * Math.pow(red,2)) +
(0.587 * Math.pow(green,2)) +
(0.114 * Math.pow(blue,2)))
);
//compresses brightness into a range of 70, which is the amount of ascii chars we are using
//3.64 is the divisor, aka 255/70
brightness = (int) (brightness / 3.64);
if(brightness > 70){brightness = 70;}
pixelVals[i] = (alpha
Подробнее здесь: [url]https://stackoverflow.com/questions/79830290/rendering-text-to-an-image-in-java[/url]