/
msigin77
/
Course1_2
Обзор
Документация
Войти
/
msigin77
/
Course1_2
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
NewTextGraphicsConverter.java
97 строк
3 KB
msigin77
Исправленная работа
08 фев 2026, 10:52
Верифицирован
08 фев 2026, 10:52
93f60b6
Код
Авторство
О чём код?
package ru.netology.graphics.image; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.awt.image.WritableRaster; import java.io.IOException; import java.net.URL; public class NewTextGraphicsConverter implements TextGraphicsConverter { private int maxWidth; private int maxHeight; private double maxRatio; private TextColorSchema schema; @Override public String convert(String url) throws IOException, BadImageSizeException { BufferedImage img = ImageIO.read(new URL(url)); int width = img.getWidth(); int height = img.getHeight(); double ratio = (double) width / height; if (ratio > maxRatio) { throw new BadImageSizeException(ratio, maxRatio); } int newWidth; int newHeight; // Если ширина больше ограничения по ширине if (width > maxWidth) { newWidth = maxWidth; newHeight = (int) Math.round(newWidth / ratio); // Если высота превышает ограничение по высоте if (height > maxHeight) { newHeight = maxHeight; newWidth = (int) Math.round(newHeight * ratio); } } else { // Если высота больше ограничения по высоте newHeight = maxHeight; newWidth = (int) Math.round(newHeight * ratio); } Image scaledImage = img.getScaledInstance(newWidth, newHeight, BufferedImage.SCALE_SMOOTH); BufferedImage bwImg = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_BYTE_GRAY); Graphics2D graphics = bwImg.createGraphics(); graphics.drawImage(scaledImage, 0, 0, null); //ImageIO.write(imageObject, "png", new File("out.png")); WritableRaster bwRaster = bwImg.getRaster(); char[][] asciiArt = new char[newHeight][newWidth]; for (int h = 0; h < newHeight; h++) { for (int w = 0; w < newWidth; w++) { int color = bwRaster.getPixel(w, h, new int[3])[0]; char c = schema.convert(color); asciiArt[h][w] = c; } } StringBuilder sb = new StringBuilder(); for (int h = 0; h < asciiArt.length; h++) { for (int w = 0; w < asciiArt[h].length; w++) { sb.append(asciiArt[h][w]); sb.append(" "); } if (h < asciiArt.length - 1) { sb.append("\n"); } } return sb.toString(); } @Override public void setMaxWidth(int width) { this.maxWidth = width; } @Override public void setMaxHeight(int height) { this.maxHeight = height; } @Override public void setMaxRatio(double maxRatio) { this.maxRatio = maxRatio; } @Override public void setTextColorSchema(TextColorSchema schema) { this.schema = schema; } }