/
digit
/
java-diplom-converter
Обзор
Документация
Войти
/
digit
/
java-diplom-converter
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
Converter.java
114 строк
4 KB
digit
Create: Main.java, Schema.java, Converter.java, Update: README.md
01 авг 2026, 20:02
Верифицирован
01 авг 2026, 20:02
0553e63
Код
Авторство
О чём код?
package ru.netology.graphics.image; import java.io.IOException; import java.awt.image.BufferedImage; import javax.imageio.ImageIO; import java.net.URI; import java.awt.Image; import java.awt.Graphics2D; import java.awt.image.WritableRaster; //import java.io.File; public class Converter implements TextGraphicsConverter { private TextColorSchema schema; private Double maxRatio; private Integer maxWidth; private Integer maxHeight; public Converter() { this.schema = new Schema(); } public Converter(TextColorSchema schema) { this.setTextColorSchema(schema); } @Override public String convert(String url) throws IOException, BadImageSizeException { // картинка из интернета BufferedImage img = ImageIO.read(URI.create(url).toURL()); // throws IOException // параметры текущей картинки (ширина и высота должны быть больше нуля) int imgWidth = img.getWidth(); int imgHeight = img.getHeight(); double aspectRatio = (double) imgWidth / imgHeight; // проверка соотношения (если задано максимальное) if (maxRatio != null) { if (Double.compare(aspectRatio, maxRatio) > 0) { // ratio > maxRatio ? throw new BadImageSizeException(aspectRatio, maxRatio); } } // новые размеры // если максимум 100x100, то: // 500x100 -> 100x20 (resizeRatio = 0.2) // 100x500 -> 20x100 (resizeRatio = 0.2) int newWidth = imgWidth; int newHeight = imgHeight; if (maxWidth != null && maxHeight != null) { // заданы ли размеры if (imgWidth > maxWidth || imgHeight > maxHeight) { // превышают ли стороны максимум double wMaxRatio = (double) maxWidth / imgWidth; double hMaxRatio = (double) maxHeight / imgHeight; double resizeRatio = Math.min(wMaxRatio, hMaxRatio); newWidth = (int) (newWidth * resizeRatio); newHeight = (int) (newHeight * resizeRatio); } } // новые пропорции 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); graphics.dispose(); // тестовое сохранение // ImageIO.write(bwImg, "png", new File("test.png")); // создание растера 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) { if (width > 0) { this.maxWidth = width; } } @Override public void setMaxHeight(int height) { if (height > 0) { this.maxHeight = height; } } @Override public void setMaxRatio(double maxRatio) { if (maxRatio > 0.0) { this.maxRatio = maxRatio; } } @Override public void setTextColorSchema(TextColorSchema schema) { if (schema != null) { this.schema = schema; } } }