Last active
December 18, 2018 16:30
-
-
Save dmitmel/e029844e284c3aee2963cd0c5e2ee6f4 to your computer and use it in GitHub Desktop.
turtle-image.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Copyright 2018 Dmytro Meleshko | |
# | |
# Licensed under the Apache License, Version 2.0 (the "License"); | |
# you may not use this file except in compliance with the License. | |
# You may obtain a copy of the License at | |
# | |
# http://www.apache.org/licenses/LICENSE-2.0 | |
# | |
# Unless required by applicable law or agreed to in writing, software | |
# distributed under the License is distributed on an "AS IS" BASIS, | |
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
# See the License for the specific language governing permissions and | |
# limitations under the License. | |
# Этот скрипт рисует картинки с использованием черепашьей графики. Работает и на | |
# 2-ой и на 3-ей версии Python, но требует библиотеку Pillow. | |
import turtle | |
from PIL import Image | |
IMAGE_FILE = "mona-lisa.jpg" # путь к абсолютно любой картинке | |
# загружаем картинку | |
original_image = Image.open(IMAGE_FILE) | |
original_width, original_height = original_image.size | |
# изменяем размер изображения с сохранением соотношения сторон | |
width = 100 # это значение можно менять, но 100 работает лучше всего | |
height = int(original_height * float(width) / original_width) | |
image = original_image.resize((width, height), Image.ANTIALIAS) | |
pixels = list(image.getdata()) | |
# настраиваем черепашку | |
turtle.title(__file__) | |
turtle.delay(0) # выключаем задержки между действиями | |
turtle.speed(0) # максимальная скорость | |
# полностью прячем черепашку | |
turtle.hideturtle() | |
turtle.penup() | |
# по умолчанию модуль turtle использует значения от 0.0 до 1.0 включительно для | |
# значений цветов, так что это надо поменять на байтовый диапазон (от 1 до 255 | |
# включительно), который использует Pillow | |
turtle.colormode(255) | |
# отключить автоматическое обновление экрана, так как это очень сильно замедляет | |
# отрисовку целой картинки | |
turtle.tracer(False) | |
# размер кружков, которые будут использоваться как пиксели изображения | |
PIXEL_SIZE = 3 | |
# Рисуем картинку | |
for y in range(height): | |
for x in range(width): | |
pixel = pixels[y * width + x] | |
turtle.goto( | |
PIXEL_SIZE * (x - float(width) / 2.0), | |
PIXEL_SIZE * (float(height) / 2.0 - y), | |
) | |
turtle.dot(PIXEL_SIZE, pixel) | |
# обновляем экран после отрисовки рядка из пикселей | |
turtle.update() | |
# картинка нарисована, можно включить автообновление экрана | |
turtle.tracer(True) | |
turtle.done() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment