这个小项目,可以将图片转化为ASCII图案,并且将ASCII图案输出为照片。
修改部分注释,可以进行图片缩略。
注:本项目参照于spring boot的banner
可查阅源代码:org.springframework.boot.SpringApplicationBannerPrinter
public class Image {
private static final String[] PIXEL = new String[]{" ", ".", "*", ":", "o", "&", "8", "#", "%",">"};
public static void main(String[] args) throws IOException {
BufferedImage bufferedImage = getImage("resources/love.jpg");
printImage(bufferedImage);
}
private static void printImage(BufferedImage bufferedImage) throws IOException {
File file = new File("resources/0915.jpg");
int width = bufferedImage.getWidth();
int height = bufferedImage.getHeight();
Graphics graphics = bufferedImage.getGraphics();
for (int y=0;y < height;y++){
for (int x=0;x < width;x++){
int rgb = bufferedImage.getRGB(x,y);
Color color = new Color(rgb);
int red = color.getRed();
int green = color.getGreen();
int blue = color.getBlue();
//计算亮点 ImageBanner类中
//double luminance = 0.2126D * red + 0.7152D * green + 0.0722D * blue;
double luminance = (red+green+blue)/3;
//double index = luminance / (Math.ceil(255 / PIXEL.length) + 0.5);
double index = luminance/28;
//String a = String.valueOf(PIXEL[(int)(Math.floor(index))]);
//StringBuilder builder = new StringBuilder();
System.out.print(PIXEL[(int)(Math.floor(index))]);
graphics.setColor(color);
graphics.drawString(PIXEL[(int)(Math.floor(index))],x,y);
}
System.out.println(" ");
}
ImageIO.write(bufferedImage,"jpg",file);
}
private static BufferedImage getImage(String imagePath) throws IOException {
File file = new File(imagePath);
if (file == null){
System.err.println("文件不存在");
return null;
}
BufferedImage bufferedImage = null;
//BufferedImage bufferedImage1 = null;
bufferedImage = ImageIO.read(file);
/*int srcWidth = bufferedImage.getWidth(null);// 原图片宽度
int srcHeight = bufferedImage.getHeight(null);// 原图片高度
int dstMaxSize = 90;// 目标缩略图的最大宽度/高度,宽度与高度将按比例缩写
int dstWidth = srcWidth;// 缩略图宽度
int dstHeight = srcHeight;// 缩略图高度
float scale = 0;
// 计算缩略图的宽和高
if (srcWidth > dstMaxSize) {
dstWidth = dstMaxSize;
scale = (float)srcWidth / (float)dstMaxSize;
dstHeight = Math.round((float)srcHeight / scale);
}
srcHeight = dstHeight;
if (srcHeight > dstMaxSize) {
dstHeight = dstMaxSize;
scale = (float)srcHeight / (float)dstMaxSize;
dstWidth = Math.round((float)dstWidth / scale);
}
// 生成缩略图
bufferedImage1 = new BufferedImage(dstWidth, dstHeight, BufferedImage.TYPE_INT_RGB);
bufferedImage1.getGraphics().drawImage(bufferedImage, 0, 0, dstWidth, dstHeight, null);*/
return bufferedImage;
}
}
原
生成的照片
(ASCII)