2023-09-30

This commit is contained in:
Gennadiy 2023-12-17 08:50:15 +03:00
parent 77839ad820
commit 6a3de67267
8 changed files with 24 additions and 24 deletions

View file

@ -7,9 +7,9 @@ url: "https://pomodoro5.mircloud.ru"
# подпапка этой сборки для относительных URLs # подпапка этой сборки для относительных URLs
baseurl: "/color" baseurl: "/color"
# ссылка в верхнем левом углу заглавных страниц # ссылка в верхнем левом углу заглавных страниц
homepage_url: "https://gitea.com/pomodoro/5" homepage_url: "https://git.org.ru/pomodoro/5"
# представление ссылки # представление ссылки
homepage_name: "GITEA" homepage_name: "GIT.ORG.RU"
# подпапка альтернативной сборки # подпапка альтернативной сборки
older_tomato_baseurl: "" older_tomato_baseurl: ""
# часовой пояс для формата даты ISO-8601 # часовой пояс для формата даты ISO-8601

View file

@ -7,9 +7,9 @@ url: "https://pomodoro5.mircloud.ru"
# подпапка этой сборки для относительных URLs # подпапка этой сборки для относительных URLs
baseurl: "" baseurl: ""
# ссылка в верхнем левом углу заглавных страниц # ссылка в верхнем левом углу заглавных страниц
homepage_url: "https://gitea.com/pomodoro/5" homepage_url: "https://git.org.ru/pomodoro/5"
# представление ссылки # представление ссылки
homepage_name: "GITEA" homepage_name: "GIT.ORG.RU"
# подпапка альтернативной сборки # подпапка альтернативной сборки
color_tomato_baseurl: "/color" color_tomato_baseurl: "/color"
# часовой пояс для формата даты ISO-8601 # часовой пояс для формата даты ISO-8601

View file

@ -24,7 +24,7 @@ for captcha we'll use a combination of only capital latin letters and digits.
Rendering special characters in a monospaced font: [Drawing heart in console]({{ '/en/2023/03/08/drawing-heart-in-console.html#text-as-picture-and-picture-as-text' | relative_url }}). Rendering special characters in a monospaced font: [Drawing heart in console]({{ '/en/2023/03/08/drawing-heart-in-console.html#text-as-picture-and-picture-as-text' | relative_url }}).
## Algorithm description {#algorithm-description} {% include heading.html text="Algorithm description" hash="algorithm-description" %}
We prepare an array of symbols consisting of uppercase latin letters and numbers. Then bypass We prepare an array of symbols consisting of uppercase latin letters and numbers. Then bypass
this array and draw each symbol separately we get a picture. Then rotate the pictures this array and draw each symbol separately we get a picture. Then rotate the pictures
@ -40,7 +40,7 @@ The imposition of the next picture on the previous one by 40% of its width is ne
that the symbols are located very close or slightly touch each other it also complicates that the symbols are located very close or slightly touch each other it also complicates
machine text recognition. machine text recognition.
## Font rendering {#font-rendering} {% include heading.html text="Font rendering" hash="font-rendering" %}
When rendering the font, we will use *anti-aliasing*, otherwise the letters will have jagged When rendering the font, we will use *anti-aliasing*, otherwise the letters will have jagged
edges. Set the image with transparency support, color black, font *Comic Sans*. edges. Set the image with transparency support, color black, font *Comic Sans*.
@ -72,7 +72,7 @@ private static BufferedImage stringToImage(String str, Font font) {
} }
``` ```
## Image rotation {#image-rotation} {% include heading.html text="Image rotation" hash="image-rotation" %}
When rotating the image for smoothing, we will use *bilinear interpolation*, otherwise there When rotating the image for smoothing, we will use *bilinear interpolation*, otherwise there
will be a lot of unnecessary artifacts along the image borders. On the way, we recalculate will be a lot of unnecessary artifacts along the image borders. On the way, we recalculate
@ -111,7 +111,7 @@ private static BufferedImage rotateImage(BufferedImage image, double angle) {
} }
``` ```
## Drawing simple captcha {#drawing-simple-captcha} {% include heading.html text="Drawing simple captcha" hash="drawing-simple-captcha" %}
We bypass the array of symbols, draw and rotate each symbol separately, on the way calculate We bypass the array of symbols, draw and rotate each symbol separately, on the way calculate
the dimensions for the common image. Create a common image and after that once again bypass the dimensions for the common image. Create a common image and after that once again bypass
@ -201,7 +201,7 @@ private static String[] getRandomString(int length) {
{% endcapture %} {% endcapture %}
{%- include collapsed_block.html summary="Additional methods" content=collapsed_md -%} {%- include collapsed_block.html summary="Additional methods" content=collapsed_md -%}
## Testing and launching {#testing-n-launching} {% include heading.html text="Testing and launching" hash="testing-n-launching" %}
The algorithm turned out to be universal it can render almost any string and in almost any The algorithm turned out to be universal it can render almost any string and in almost any
font, but with a long list of exceptions, related to unicode symbol ranges and font types. There font, but with a long list of exceptions, related to unicode symbol ranges and font types. There

View file

@ -17,7 +17,7 @@ graph of a circle and graphs of a rhombus and a square inscribed in it.
Graph of a function with filling: [Drawing heart in console]({{ '/en/2023/03/08/drawing-heart-in-console.html' | relative_url }}). Graph of a function with filling: [Drawing heart in console]({{ '/en/2023/03/08/drawing-heart-in-console.html' | relative_url }}).
### Equations of functions {#equations-of-functions} {% include heading.html text="Equations of functions" hash="equations-of-functions" type="3" %}
We will check each point `(x,y)` from the output range of coordinates for belonging to function We will check each point `(x,y)` from the output range of coordinates for belonging to function
graphs and output in accordance with this. We define the parameters of the functions and the graphs and output in accordance with this. We define the parameters of the functions and the
@ -49,7 +49,7 @@ alt="\sqrt{(x-a)^2+(y-b)^2}=r." %}
`c` half a side of a square. `c` half a side of a square.
### Mathematical operations {#mathematical-operations} {% include heading.html text="Mathematical operations" hash="mathematical-operations" type="3" %}
To perform *basic* mathematical operations, Java uses the `FdLibm` library *Freely Distributable To perform *basic* mathematical operations, Java uses the `FdLibm` library *Freely Distributable
Math Library*. Most of the methods are implemented at the platform level to increase performance. Math Library*. Most of the methods are implemented at the platform level to increase performance.
@ -67,7 +67,7 @@ For floating point calculations and rounding of results, we will use the methods
`floor(a)` rounding down the argument `a`. `floor(a)` rounding down the argument `a`.
### Algorithm description {#algorithm-description} {% include heading.html text="Algorithm description" hash="algorithm-description" type="3" %}
We take a range of coordinates on the plane in such a way that the displayed figure completely fits We take a range of coordinates on the plane in such a way that the displayed figure completely fits
in the printing area. We bypass the selected range with two nested `for` loops: first along the `y` in the printing area. We bypass the selected range with two nested `for` loops: first along the `y`

View file

@ -15,7 +15,7 @@ of a text image — let's congratulate women on the eighth of March. Let's draw
function in the form of a heart and, in addition, draw the symbol *heart* in the form of a function in the form of a heart and, in addition, draw the symbol *heart* in the form of a
picture, and output the picture as text console congratulations on the eighth of March. picture, and output the picture as text console congratulations on the eighth of March.
## Heart shaped graph {#heart-shaped-graph} {% include heading.html text="Heart shaped graph" hash="heart-shaped-graph" %}
Let's draw two half-circles and one half-rhombus, filled inside and outside. In the previous example, Let's draw two half-circles and one half-rhombus, filled inside and outside. In the previous example,
we output a [function graph to console]({{ '/en/2023/02/06/function-graph-in-console.html' | relative_url }}) we output a [function graph to console]({{ '/en/2023/02/06/function-graph-in-console.html' | relative_url }})
@ -169,7 +169,7 @@ public static void main(String[] args) {
} }
``` ```
## Text as picture and picture as text {#text-as-picture-and-picture-as-text} {% include heading.html text="Text as picture and picture as text" hash="text-as-picture-and-picture-as-text" %}
In the previous example we [drew a simple captcha]({{ '/en/2023/01/04/drawing-simple-captcha.html' | relative_url }}) In the previous example we [drew a simple captcha]({{ '/en/2023/01/04/drawing-simple-captcha.html' | relative_url }})
we take the font rendering algorithm from it, only this time we draw a binary black-and-white we take the font rendering algorithm from it, only this time we draw a binary black-and-white

View file

@ -23,7 +23,7 @@ date: 2023.01.03
Отрисовка спецсимволов моноширинным шрифтом: [Рисуем сердечко в консоли]({{ '/ru/2023/03/08/drawing-heart-in-console.html#text-as-picture-and-picture-as-text' | relative_url }}). Отрисовка спецсимволов моноширинным шрифтом: [Рисуем сердечко в консоли]({{ '/ru/2023/03/08/drawing-heart-in-console.html#text-as-picture-and-picture-as-text' | relative_url }}).
## Описание алгоритма {#algorithm-description} {% include heading.html text="Описание алгоритма" hash="algorithm-description" %}
Подготавливаем массив символов, состоящий из заглавных латинских букв и цифр. Затем обходим Подготавливаем массив символов, состоящий из заглавных латинских букв и цифр. Затем обходим
этот массив и отрисовываем каждый символ отдельно получаем картинку. Затем поворачиваем этот массив и отрисовываем каждый символ отдельно получаем картинку. Затем поворачиваем
@ -38,7 +38,7 @@ date: 2023.01.03
Наложение последующей картинки на предыдущую на 40% её ширины нужно, чтобы символы располагались Наложение последующей картинки на предыдущую на 40% её ширины нужно, чтобы символы располагались
очень близко или слегка касались друг друга это также затрудняет машинное распознавание текста. очень близко или слегка касались друг друга это также затрудняет машинное распознавание текста.
## Отрисовка шрифта {#font-rendering} {% include heading.html text="Отрисовка шрифта" hash="font-rendering" %}
При отрисовке шрифта будем использовать сглаживание *anti-aliasing*, иначе буквы будут При отрисовке шрифта будем использовать сглаживание *anti-aliasing*, иначе буквы будут
с зазубренными краями. Устанавливаем изображение с поддержкой прозрачности, цвет чёрный, с зазубренными краями. Устанавливаем изображение с поддержкой прозрачности, цвет чёрный,
@ -71,7 +71,7 @@ private static BufferedImage stringToImage(String str, Font font) {
} }
``` ```
## Поворот изображения {#image-rotation} {% include heading.html text="Поворот изображения" hash="image-rotation" %}
При повороте изображения для сглаживания будем использовать *билинейную интерполяцию*, иначе При повороте изображения для сглаживания будем использовать *билинейную интерполяцию*, иначе
будет много лишних артефактов по границам изображения. По дороге пересчитываем размеры для будет много лишних артефактов по границам изображения. По дороге пересчитываем размеры для
@ -110,7 +110,7 @@ private static BufferedImage rotateImage(BufferedImage image, double angle) {
} }
``` ```
## Рисуем простую капчу {#drawing-simple-captcha} {% include heading.html text="Рисуем простую капчу" hash="drawing-simple-captcha" %}
Обходим массив символов, отрисовываем и поворачиваем каждый символ в отдельности, по дороге Обходим массив символов, отрисовываем и поворачиваем каждый символ в отдельности, по дороге
вычисляем размеры для общего изображения. Создаём общее изображение и после этого ещё раз вычисляем размеры для общего изображения. Создаём общее изображение и после этого ещё раз
@ -200,7 +200,7 @@ private static String[] getRandomString(int length) {
{% endcapture %} {% endcapture %}
{%- include collapsed_block.html summary="Дополнительные методы" content=collapsed_md -%} {%- include collapsed_block.html summary="Дополнительные методы" content=collapsed_md -%}
## Тестирование и запуск {#testing-n-launching} {% include heading.html text="Тестирование и запуск" hash="testing-n-launching" %}
Алгоритм получился универсальный отрисовать можно почти любую строку и почти любым шрифтом, Алгоритм получился универсальный отрисовать можно почти любую строку и почти любым шрифтом,
но с длинным списком исключений, связанных с диапазонами символов юникода и типами шрифтов. но с длинным списком исключений, связанных с диапазонами символов юникода и типами шрифтов.

View file

@ -16,7 +16,7 @@ date: 2023.02.05
График функции с заполнением: [Рисуем сердечко в консоли]({{ '/ru/2023/03/08/drawing-heart-in-console.html' | relative_url }}). График функции с заполнением: [Рисуем сердечко в консоли]({{ '/ru/2023/03/08/drawing-heart-in-console.html' | relative_url }}).
### Уравнения функций {#equations-of-functions} {% include heading.html text="Уравнения функций" hash="equations-of-functions" type="3" %}
Каждую точку `(x,y)` из выводимого диапазона координат будем проверять на принадлежность графикам Каждую точку `(x,y)` из выводимого диапазона координат будем проверять на принадлежность графикам
функций и в соответствии с этим выводить. Параметры функций и выводимый диапазон определим заранее функций и в соответствии с этим выводить. Параметры функций и выводимый диапазон определим заранее
@ -48,7 +48,7 @@ alt="\sqrt{(x-a)^2+(y-b)^2}=r." %}
`c` половина стороны квадрата. `c` половина стороны квадрата.
### Математические операции {#mathematical-operations} {% include heading.html text="Математические операции" hash="mathematical-operations" type="3" %}
Для выполнения *базовых* математических операций в Java используется библиотека `FdLibm` Для выполнения *базовых* математических операций в Java используется библиотека `FdLibm`
*Свободно распространяемая математическая библиотека*. Большинство методов реализовано на уровне *Свободно распространяемая математическая библиотека*. Большинство методов реализовано на уровне
@ -66,7 +66,7 @@ alt="\sqrt{(x-a)^2+(y-b)^2}=r." %}
`floor(a)` округление аргумента `a` в ме́ньшую сторону. `floor(a)` округление аргумента `a` в ме́ньшую сторону.
### Описание алгоритма {#algorithm-description} {% include heading.html text="Описание алгоритма" hash="algorithm-description" type="3" %}
Берём диапазон координат на плоскости таким образом, чтобы выводимая фигура полностью помещалась Берём диапазон координат на плоскости таким образом, чтобы выводимая фигура полностью помещалась
в печатаемой области. Обходим выбранный диапазон двумя вложенными циклами `for`: сначала по оси в печатаемой области. Обходим выбранный диапазон двумя вложенными циклами `for`: сначала по оси

View file

@ -14,7 +14,7 @@ date: 2023.03.08
и в дополнение нарисуем символ *сердечко* в форме картинки, а картинку выведем текстом и в дополнение нарисуем символ *сердечко* в форме картинки, а картинку выведем текстом
консольное поздравление с восьмым марта. консольное поздравление с восьмым марта.
## График в форме сердечка {#heart-shaped-graph} {% include heading.html text="График в форме сердечка" hash="heart-shaped-graph" %}
Нарисуем два полукруга и один полуромб, заполненные внутри и снаружи. В предыдущем примере мы выводили Нарисуем два полукруга и один полуромб, заполненные внутри и снаружи. В предыдущем примере мы выводили
[график функции в консоль]({{ '/ru/2023/02/05/function-graph-in-console.html' | relative_url }}) [график функции в консоль]({{ '/ru/2023/02/05/function-graph-in-console.html' | relative_url }})
@ -165,7 +165,7 @@ public static void main(String[] args) {
} }
``` ```
## Текст картинкой и картинка текстом {#text-as-picture-and-picture-as-text} {% include heading.html text="Текст картинкой и картинка текстом" hash="text-as-picture-and-picture-as-text" %}
В предыдущем примере мы [рисовали простую капчу]({{ '/ru/2023/01/03/drawing-simple-captcha.html' | relative_url }}) В предыдущем примере мы [рисовали простую капчу]({{ '/ru/2023/01/03/drawing-simple-captcha.html' | relative_url }})
алгоритм отрисовки шрифта возьмём из него, только на этот раз нарисуем бинарное чёрно-белое алгоритм отрисовки шрифта возьмём из него, только на этот раз нарисуем бинарное чёрно-белое