/
SofiMut
/
2dGraphic
Обзор
Документация
Войти
/
SofiMut
/
2dGraphic
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
Converter.java
106 строк
3 KB
Софья Степанова
upload files
23 авг 2025, 08:14
23 авг 2025, 08:14
1a5ea03
Код
Авторство
О чём код?
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 Converter implements TextGraphicsConverter { protected TextColorSchema scheme = new Spectrum(); protected int maxWidth; protected int maxHeight; protected double maxRatio; protected double myImageRatio; @Override public String convert(String url) throws IOException, BadImageSizeException { BufferedImage myImage = ImageIO.read(new URL(url)); int newWidth = myImage.getWidth(); int newHeight = myImage.getHeight(); if (newWidth > this.maxWidth) { double rdc = (double) newWidth / this.maxWidth; newWidth = (int) (newWidth / rdc); newHeight = (int) (newHeight / rdc); } if (newHeight > this.maxHeight) { double rdc = (double) newHeight / this.maxHeight; newHeight = (int) (newHeight / rdc); newWidth = (int) (newWidth / rdc); } double myImageRatio = (double) getRatio(newWidth, newHeight); if (myImageRatio > this.maxRatio || myImageRatio == 0) { throw new BadImageSizeException(myImageRatio, this.maxRatio); } Image scaledImage = myImage.getScaledInstance(newWidth, newHeight, BufferedImage.SCALE_SMOOTH); BufferedImage bwImg = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_BYTE_GRAY); Graphics2D graphics = bwImg.createGraphics(); WritableRaster bwRaster = bwImg.getRaster(); graphics.drawImage(scaledImage, 0, 0, null); 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 = scheme.convert(color); sb.append(c); sb.append(c); } sb.append("\n"); } return sb.toString(); } protected double getRatio(int newWidth, int newHeight) { if (newWidth > newHeight) { myImageRatio = (double) newWidth / newHeight; } else if (newHeight > newWidth) { myImageRatio = (double) newHeight / newWidth; } return myImageRatio; } @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 scheme) { this.scheme = scheme; } }