我要做的是使用指定的参数创建一个png图像,例如:
img = Image(200, 100, Color(0, 0, 255)) h_line(img, 20, Color(255, 0, 0)) c = img.get_pixel(20, 20) c.b = 200 img2 = img.copy() h_line(img, 40, Color(255, 0, 0)) save('file01_01_out.png', img)
这是我到目前为止写的:
import png
class Color(object):
def __init__(self, r, g, b):
self.r = r
self.g = g
self.b = b
def copy(self):
return Color(self.r, self.g, self.b)
class Image(object):
#'''Class must have height and width attributes'''
def __init__(self, width, height, c):
self.width = width
self.height = height
self.c = Color
#'''Initializes the image with width, height and every pixel with copies of c
# c being an object of Color type'''
#
def set_pixel(self, x, y, c):
self.img.put("{" + c +"}", (x, y))
# '''Sets the color in position (x, y) with a copy of object
# c of type Color. If the position (x, y) is beyond the
# object, then it won't do anything'''
def get_pixel(self, x, y):
value = self.img.get(x,y)
if type(value) == type(0):
return [value, value, value]
else:
return None
# '''Returns a copy of the color (Color type) in position
# (x, y). If (x, y) is beyond the picture, it will return
# None'''
def copy(self):
return Image(self.width, self.height, self.c)
def h_line(img, y, c):
for x in range(img.width):
img.set_pixel(x, y, c)
def save(filename, img):
png_img = []
for i in range(img.height):
png_row = []
for j in range(img.width):
c = img.get_pixel(j, i)
png_row.extend([c.r, c.g, c.b])
png_img.append(png_row)
with open(filename, 'wb') as f:
png.Writer(img.width, img.height).write(f, png_img)
问题是该程序不会崩溃,但它不会保存任何东西!我尝试了不同的例子,但结果总是一样的。我做错了什么?
答案 0 :(得分:1)
更新 - 刚刚注意到Py3标签 - 所以答案可能无效 - 但可能有些用途
例如 - 使用PIL - 您可以创建具有特定RGB颜色的200x200图像,然后使用.png
扩展名保存...
>>> from PIL import Image
>>> img = Image.new('RGB', (200, 200), (127, 127, 127))
>>> img.save('/path/to/some/file.png')
给你: