/
Rustam1977
/
MAIN
Обзор
Документация
Войти
/
Rustam1977
/
MAIN
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
java
TextGraphicsConverter.java
79 строк
3 KB
Rustam1977
upload files
27 сен 2025, 16:20
27 сен 2025, 16:20
eacb2c6
Код
Авторство
О чём код?
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 Converter implements TextGraphicsConverter { private double maxRatio = 0; private int maxWidth = 0; private int maxHeight = 0; private TextColorSchema schema = new Schema(); @Override public String convert(String url) throws IOException, BadImageSizeException { BufferedImage img = ImageIO.read(new URL(url)); // Проверка соотношения сторон double ratio = (double) img.getWidth() / img.getHeight(); if (maxRatio > 0 && ratio > maxRatio) { throw new BadImageSizeException(ratio, maxRatio); } // Масштабирование изображения int newWidth = img.getWidth(); int newHeight = img.getHeight(); if (maxWidth > 0 || maxHeight > 0) { double widthRatio = maxWidth > 0 ? (double) maxWidth / newWidth : 1.0; double heightRatio = maxHeight > 0 ? (double) maxHeight / newHeight : 1.0; double scale = Math.min(widthRatio, heightRatio); if (scale < 1) { newWidth = (int) (newWidth * scale); newHeight = (int) (newHeight * scale); } } 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); WritableRaster bwRaster = bwImg.getRaster(); StringBuilder sb = new StringBuilder(); 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); sb.append(c).append(c); // Дублируем символ } 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; } }