所以我在使用Spring和Thymeleaf,我有一个ASCII生成器,它可以将图像转换成ASCII字符。这些字符是。
.,:ilwW#MW&8%B@$
转换后,我想用Thymeleaf将图像显示在屏幕上。 文本被格式化,变成一个字符串。当我把这个字符串写入一个.txt文件时,我得到了预期的输出,但是当我用Thymeleaf做的时候,我得到的却是另外的东西。我应该在每一行都得到相等数量的字符,但Thymeleaf的情况并非如此,相反我得到了字符,但换行似乎并不工作。我的代码。
import java.io.IOException;
import java.io.InputStream;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import javax.imageio.ImageIO;
import ij.ImagePlus;
import ij.process.ImageProcessor;
public class ImageToAsciiConverter {
public static synchronized String convertImageToAscii(InputStream in) throws IOException {
ImagePlus image = new ImagePlus("Image", ImageIO.read(in));
return new ImageToAsciiConverter().process(image);
}
// Processes the image pixel by pixel and sets appropriate ASCII chars for every
// pixel value. Returns a string containing the ASCII picture.
private String process(ImagePlus image) {
ImageProcessor imageProcessor = image.getProcessor();
imageProcessor.setInterpolate(true);
ImagePlus imp = new ImagePlus("", imageProcessor.resize(300, 300));
int[] size = imp.getDimensions();
int width = size[0], height = size[1];
ImageToAsciiUtil util = new ImageToAsciiUtil();
return IntStream.range(0, width * height)
.parallel()
.map(i -> i % width != 0 ? util.convertToBrightness(imp.getPixel((i % width), (i / width))) : -1)
.mapToObj(i -> i == -1 ? "\n" : util.getAsciiSymbol(i))
.sequential()
.collect(Collectors.joining());
}
/**
* Utility class for converting images to ASCII characters.
*/
private static class ImageToAsciiUtil {
/**
* @param arr the array containing pixel RGB data.
* @return Returns the averaged RGB value. (( R + G + B ) / 3 )
*/
private int convertToBrightness(int[] arr) {
return ((arr[0] + arr[1] + arr[2]) / 3);
}
/**
* @param s the value to be changed
* @param a1 lower range of s.
* @param a2 upper range of s.
* @param b1 new lower range.
* @param b2 new upper range.
* @return Returns s with values ranging from b1 to b2.
*/
private float map(float s, float a1, float a2, float b1, float b2) {
return b1 + (s - a1) * (b2 - b1) / (a2 - a1);
}
/**
* .,:ilwW#MW&8%B@$
*
* @param brightness The pixel brightness that's going to be associated with a
* symbol.
* @return Returns the ASCII symbol associated with the provided brightness.
*/
private String getAsciiSymbol(int brightness) {
String ASCII = " .,:ilwW#MW&8%B@$";
String s = String.valueOf(ASCII.charAt((int) map(brightness, 0, 255, 0, ASCII.length() - 1)));
return s + s + s;
}
}
}
我试过了
<p th:text="${ascii}"></p>
<p th:utext="${ascii}"></p>
我也试过用不同的方法在HTML中添加新行,比如:
<br/>



我也试过编辑CSS。但每行的字符数还是不同。
好了,我想明白了,问题是我使用的字体不是单间距的。我把CSS属性改为:
font-family: monospace;
然后我删除了ASCII选择中的空格字符,因为它没有被渲染,现在它的工作原理和预期一样。