Python 使用类创建png图像
我尝试使用指定的参数创建png图像,如: 这是我到目前为止写的:Python 使用类创建png图像,python,image,python-3.x,png,Python,Image,Python 3.x,Png,我尝试使用指定的参数创建png图像,如: 这是我到目前为止写的: 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):
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)
问题是程序不会崩溃,但不会保存任何东西!我尝试了不同的例子,但结果总是一样的。我做错了什么?更新-刚刚注意到Py3标签-因此答案可能无效-但可能有一些用途 例如-使用-您可以创建具有特定RGB颜色的200x200图像,然后使用
.png
扩展名保存它
>>> from PIL import Image
>>> img = Image.new('RGB', (200, 200), (127, 127, 127))
>>> img.save('/path/to/some/file.png')
给你:
如果有人可以使用它(它不是独立的,也不是其他人可以运行的),我会感到惊讶-许多代码似乎缺失或只是没有正确缩进-例如:
self.img
到底是什么?(如果我理解正确的话,这只是使用PIL的几行代码…)谢谢,但不幸的是,我真的需要使用PNG库:(
>>> from PIL import Image
>>> img = Image.new('RGB', (200, 200), (127, 127, 127))
>>> img.save('/path/to/some/file.png')