Created
April 11, 2016 20:59
-
-
Save srsudar/322c9aaa1bbc78de23c0b41d8ca4726b to your computer and use it in GitHub Desktop.
Revisions
-
srsudar created this gist
Apr 11, 2016 .There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,58 @@ # -*- coding: utf-8 -*- """ Scale a PNG by an integer factor, keeping it pixelated. """ import png from sys import argv # We're assuming rgba for for ints per pixel. Looking at the pypng docs there # are other options this might be, but this is all I needed. VAL_PER_PIXEL = 4 # rgba if __name__ == '__main__': # we expect scale_factor, in_file, out_file if len(argv) != 4: raise ValueError('Usage: scale_factor, in_file, out_file') factor = int(argv[1]) in_file = argv[2] out_file = argv[3] reader = png.Reader(in_file) content = reader.asDirect() rows = content[2] # content[2][0] assumes at least one row. There are original_width pixels in # this row, and each pixel has VAL_PER_PIXEL ints for each pixel. original_width = len(content[2][0]) / VAL_PER_PIXEL original_height = len(content[2]) out_width = original_width * factor out_height = original_height * factor all_rows = [] # Iterate over each row. Each pixel is represented by several ints (the # exact number depends on the file and is defined by VAL_PER_PIXEL). Each # pixel must be grown by factor, and each row must then be appended factor # number of times to all_rows. for row in rows: new_row = [] for num_pixel in range(len(row) / VAL_PER_PIXEL): # / 4 for rgba # if a single pixel row was [255, 128, 25, 0], we would want to # expand that times 4. pixel_start = num_pixel * VAL_PER_PIXEL pixel_values = row[pixel_start:pixel_start + VAL_PER_PIXEL] larger_values = list(pixel_values) * factor new_row = new_row + larger_values for i in range(factor): # we've enlarged the row, now add it. all_rows.append(new_row) with open(out_file, 'w') as f: # alpha = True for rgba. This will have to be updated for PNGs without # alpha. w = png.Writer(out_width, out_height, alpha=True) w.write(f, all_rows)