Last active
February 13, 2016 09:53
-
-
Save mipsparc/14dcfe65411e663ae218 to your computer and use it in GitHub Desktop.
Make a mosaic art randomly with your favorite colour. (Only work on Python3)
This file contains hidden or 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
| #coding:utf-8 | |
| outname = 'out.png' | |
| import struct | |
| import binascii | |
| import zlib | |
| from math import ceil | |
| import codecs | |
| import random | |
| from functools import reduce | |
| size_x = 15 | |
| size_y = 15 | |
| pixcel = 25 | |
| colour = input('base colour: ') | |
| #allow +-3 | |
| #must be even | |
| random_range = 100 | |
| #colour decode | |
| colour_rgb = [int(colour[i*2:i*2+2], 16) for i in range(3)] | |
| #変更量 | |
| def changerate(ratio): | |
| new_ratio = ratio + random.randint(0, random_range)-int(random_range/2) | |
| if new_ratio >= 255: | |
| return 255 | |
| elif new_ratio <= 0: | |
| return 0 | |
| else: | |
| return new_ratio | |
| def twodigits_hex(num): | |
| hexized = hex(num)[2:] | |
| if len(hexized)==1: | |
| return '0'+hexized | |
| return hexized | |
| def newrgb(): | |
| return [twodigits_hex(ratio) for ratio in map(changerate, colour_rgb)] | |
| #Random | |
| IMAGE = reduce(lambda x,y:x+y ,[[''.join([''.join(newrgb())*pixcel for j in range(size_x)])]*pixcel for k in range(size_y)]) | |
| def crcMaker(data): | |
| return binascii.crc32(data) | |
| def chunkMaker(name, chunkData): | |
| CRC = crcMaker(name + chunkData) | |
| body_len = len(chunkData) | |
| chunk = struct.pack('> I 4s {}s I'.format(body_len), | |
| body_len, name, chunkData, CRC) | |
| return chunk | |
| def hexize(data): | |
| return codecs.decode(data,'hex') | |
| data = bytes() | |
| #header | |
| data += bytes((0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A)) | |
| #IHDR | |
| width = len(IMAGE[0])//6 | |
| height = len(IMAGE) | |
| depth = 8 | |
| colourType = 2 | |
| compress = 0 | |
| filterType = 0 | |
| adam7 = False | |
| chunkData = struct.pack('> I I B B B B ?', | |
| width, height, depth, colourType, compress, filterType, adam7) | |
| data += chunkMaker(b'IHDR', chunkData) | |
| #IDAT | |
| filteredImage = bytes() | |
| filterMode = b'\x00' | |
| inputLine = b''.join([filterMode+hexize(l) for l in IMAGE]) | |
| chunkData = zlib.compress(inputLine) | |
| data += chunkMaker(b'IDAT', chunkData) | |
| #IEND | |
| data += chunkMaker(b'IEND', b'') | |
| with open(outname, 'wb') as f: | |
| f.write(data) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment