/
akupan2012
/
kursova
Обзор
Документация
Войти
/
akupan2012
/
kursova
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
TextGraphicsConverterImpl.java
69 строк
2 KB
akupan2012
upload files
19 янв 2026, 15:48
Верифицирован
19 янв 2026, 15:48
0a0929a
Код
Авторство
О чём код?
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; import java.nio.Buffer; 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(ratio, maxRatio); } } int newWidht = img.getWidth(); int newHeight = img.getHeight(); if (maxWidth > 0 && newWidht > maxWidth){ double scale = (double) maxHeight/newHeight; newHeight = maxHeight; newWidht = (int) (newWidht * scale); } Image scaledImage = img.getScaledInstance(newWidht, newHeight, BufferedImage.SCALE_SMOOTH); BufferedImage bwImg = new BufferedImage(newWidht,newHeight,BufferedImage.TYPE_BYTE_GRAY); Graphics2D graphics= bwImg.createGraphics(); graphics.drawImage(scaledImage, 0, 0, null); graphics.dispose(); WritableRaster raster = bwImg.getRaster(); StringBuilder result = new StringBuilder(); for (int h = 0; h < newHeight; h++){ for (int w = 0; w < newWidht; w++){ int color = raster.getPixel(w, h, new int [3])[0]; char c = schema.convert(color); result.append(c).append(c); } result.append("\n"); } return result.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){ if (schema != null){ this.schema = schema; } } }