/
Ersh
/
Diplom_netology
Обзор
Документация
Войти
/
Ersh
/
Diplom_netology
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
TextGraphicsConverterImpl.java
107 строк
3 KB
Ersh
upload files
18 ноя 2025, 18:13
18 ноя 2025, 18:13
2a2f69b
Код
Авторство
О чём код?
package ru.netology.graphics.image; import ru.netology.graphics.image.BadImageSizeException; import ru.netology.graphics.image.TextColorSchema; import ru.netology.graphics.image.TextGraphicsConverter; 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 double maxRatio = 0; private int maxWidth = 0; private int maxHeight = 0; private TextColorSchema schema = new TextColorSchemaImpl(); @Override public String convert(String url) throws IOException, BadImageSizeException { BufferedImage img = ImageIO.read(new URL(url)); if (maxRatio > 0) { double ratio = (double) img.getWidth() / img.getHeight(); if (ratio > maxRatio) { throw new BadImageSizeException((double) img.getWidth(), (double) img.getHeight()); } } int originalWidth = img.getWidth(); int originalHeight = img.getHeight(); int newWidth = originalWidth; int newHeight = originalHeight; if (maxWidth > 0 || maxHeight > 0) { double widthScale = 1.0; double heightScale = 1.0; if (maxWidth > 0 && originalWidth > maxWidth) { widthScale = (double) maxWidth / originalWidth; } if (maxHeight > 0 && originalHeight > maxHeight) { heightScale = (double) maxHeight / originalHeight; } double scale = Math.min(widthScale, heightScale); if (scale < 1.0) { newWidth = (int) (originalWidth * scale); newHeight = (int) (originalHeight * 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); graphics.dispose(); WritableRaster bwRaster = bwImg.getRaster(); int[] pixelArray = new int[3]; StringBuilder result = new StringBuilder(); for (int h = 0; h < newHeight; h++) { for (int w = 0; w < newWidth; w++) { int color = bwRaster.getPixel(w, h, pixelArray)[0]; char c = schema.convert(color); result.append(c).append(c); } result.append('\n'); } return result.toString(); } @Override public void setMaxRatio(double maxRatio) { this.maxRatio = maxRatio; } @Override public void setMaxWidth(int maxWidth) { this.maxWidth = maxWidth; } @Override public void setMaxHeight(int maxHeight) { this.maxHeight = maxHeight; } @Override public void setTextColorSchema(TextColorSchema schema) { this.schema = schema; } }