/
aizner
/
diplomjava
Обзор
Документация
Войти
/
aizner
/
diplomjava
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
TextGraphicsConverterImpl.java
97 строк
3 KB
aizner
create: TextGraphicsConverterImpl.java
10 фев 2026, 17:15
Верифицирован
10 фев 2026, 17:15
357a5e4
Код
Авторство
О чём код?
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 TextGraphicsConverterImpl implements TextGraphicsConverter { private Integer maxWidth; private Integer maxHeight; private Double maxRatio; private TextColorSchema schema = new DefaultTextColorSchema(); @Override public String convert(String url) throws IOException, BadImageSizeException { BufferedImage img = ImageIO.read(new URL(url)); if (img == null) { throw new IOException("Не удалось прочитать изображение по URL: " + url); } int width = img.getWidth(); int height = img.getHeight(); if (maxRatio != null && maxRatio > 0) { double ratio = (double) Math.max(width, height) / (double) Math.min(width, height); if (ratio > maxRatio) { throw new BadImageSizeException(ratio, maxRatio); } } int newWidth = width; int newHeight = height; double scale = 1.0; if (maxWidth != null && maxWidth > 0 && newWidth > maxWidth) { scale = Math.min(scale, (double) maxWidth / (double) newWidth); } if (maxHeight != null && maxHeight > 0 && newHeight > maxHeight) { scale = Math.min(scale, (double) maxHeight / (double) newHeight); } if (scale < 1.0) { newWidth = Math.max(1, (int) Math.floor(newWidth * scale)); newHeight = Math.max(1, (int) Math.floor(newHeight * scale)); } BufferedImage bwImg = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_BYTE_GRAY); Graphics2D graphics = bwImg.createGraphics(); graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); graphics.drawImage(img, 0, 0, newWidth, newHeight, null); graphics.dispose(); WritableRaster bwRaster = bwImg.getRaster(); StringBuilder sb = new StringBuilder(newHeight * (newWidth * 2 + 1)); int[] pixel = new int[3]; for (int h = 0; h < newHeight; h++) { for (int w = 0; w < newWidth; w++) { int color = bwRaster.getPixel(w, h, pixel)[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 > 0 ? width : null; } @Override public void setMaxHeight(int height) { this.maxHeight = height > 0 ? height : null; } @Override public void setMaxRatio(double maxRatio) { this.maxRatio = maxRatio > 0 ? maxRatio : null; } @Override public void setTextColorSchema(TextColorSchema schema) { if (schema != null) { this.schema = schema; } } }