/
times
/
convert
Обзор
Документация
Войти
/
times
/
convert
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
TextGraphicsConverterImpl.java
100 строк
3 KB
times
create: Main.java, GServer.java, TextColorSchema.java, TextGraphicsConverter.java, TextGraphicsConverterImpl.java, BadImageSizeException.java, DefaultTextColorSchema.java
28 апр 2026, 19:49
Верифицирован
28 апр 2026, 19:49
c784040
Код
Авторство
О чём код?
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 { TextColorSchema schema; int maxWidth; int maxHeight; double maxRatio; @Override public String convert(String url) throws IOException, BadImageSizeException { URL imageUrl = new URL(url); BufferedImage img = ImageIO.read(imageUrl); double width = img.getWidth(); double height = img.getHeight(); double size; if (height > width) { size = height / width; } else { size = width / height; } if (maxRatio != 0 && size > maxRatio) { throw new BadImageSizeException(size, maxRatio); } double widthRatio; double heightRatio; double maxResult = 0; if (maxWidth == 0) { widthRatio = 1; } else { widthRatio = width / maxWidth; } if (maxHeight == 0) { heightRatio = 1; } else { heightRatio = height / maxHeight; } if (widthRatio > heightRatio) { maxResult = widthRatio; } else { maxResult = heightRatio; } double newWidth; double newHeight; newWidth = width / maxResult; newHeight = height / maxResult; newWidth = (int) newWidth; newHeight = (int) newHeight; BufferedImage blackAndWhite = new BufferedImage((int) newWidth, (int) newHeight, BufferedImage.TYPE_BYTE_GRAY); Graphics2D graphics = blackAndWhite.createGraphics(); graphics.drawImage(img, 0, 0, (int) newWidth, (int) newHeight, null); WritableRaster pixel = blackAndWhite.getRaster(); int[] pixels = new int[1]; StringBuilder builder = new StringBuilder(); if (schema == null) { schema = new DefaultTextColorSchema(); } for (int h = 0; h < (int) newHeight; h++) { for (int w = 0; w < (int) newWidth; w++) { pixel.getPixel(w, h, pixels); char result = schema.convert(pixels[0]); builder.append(result); } builder.append("\n"); } return builder.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; } }