/
dm_kv
/
hw
Обзор
Документация
Войти
/
dm_kv
/
hw
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
GraphicsConverter.java
89 строк
3 KB
dm_kv
upload files
25 янв 2026, 19:09
Верифицирован
25 янв 2026, 19:09
1af81fd
Код
Авторство
О чём код?
package ru.netology.graphics.image; import javax.imageio.ImageIO; import javax.print.DocFlavor; import java.awt.*; import java.awt.image.BufferedImage; import java.awt.image.WritableRaster; import java.io.IOException; import java.net.URL; import java.util.Arrays; public class GraphicsConverter implements TextGraphicsConverter { int width = 10000; int height = 10000; double maxRatio = 100000; double ratio; TextColorSchema schema = new ColorSchema(); public void setMaxWidth(int width) { this.width = width; } public void setMaxHeight(int height) { this.height = height; } public void setMaxRatio(double maxRatio) { this.maxRatio = maxRatio; } public void setTextColorSchema(TextColorSchema schema) { this.schema = schema; } public String convert(String url) throws IOException, BadImageSizeException { // Вот так просто мы скачаем картинку из интернета :) BufferedImage img = ImageIO.read(new URL(url)); if (img.getWidth() > img.getHeight()) { double ratio = img.getWidth() * 1.0/img.getHeight(); } else { double ratio = img.getHeight() * 1.0/img.getWidth(); } if (ratio > maxRatio) { throw new BadImageSizeException(ratio, maxRatio); } int newWidth = img.getWidth(); int newHeight = img.getHeight(); if (img.getWidth() > width || img.getHeight() > height) { double x = width * 1.0/img.getWidth(); double y = height * 1.0/img.getHeight(); if (x < y) { newWidth = (int)(x * img.getWidth() * 1.0); newHeight = (int)(x * img.getHeight() * 1.0); } else { newWidth = (int)(y * img.getWidth() * 1.0); newHeight = (int)(y * img.getHeight() * 1.0); } } else { newWidth = img.getWidth(); newHeight = img.getHeight(); } 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); WritableRaster bwRaster = bwImg.getRaster(); char[][] pictureResult = new char[newWidth][newHeight]; for (int i = 0; i < newWidth; i++) { for (int j = 0; j < newHeight; j++) { int color = bwRaster.getPixel(i, j, new int[3])[0]; pictureResult[i][j] = schema.convert(color); } } StringBuilder sb = new StringBuilder(); for (int i = 0; i < pictureResult[0].length; i++) { for (int j = 0; j < pictureResult.length; j++) { sb.append(pictureResult[j][i]); sb.append(pictureResult[j][i]); } sb.append("\n"); } String s = sb.toString(); return s; } }