I’m trying to learn python (using python3.2), and right now I’m creating a program designed to scale images:
from PIL import Image
def newSizeChoice():
scale = input('Please enter the scale to be applied to the image: x')
while float(scale) <= 0:
scale = input('Invalid: scale must be positive. Please enter a new scale: x')
return float(scale)
def bestFilter(x):
if x < 1:
filter = 'ANTIALIAS'
elif x == 2:
filter = 'BILINEAR'
elif x == 4:
filter = 'BICUBIC'
else:
filter = 'NEAREST'
return filter
def resize(img, width, height, scale, filter):
width = width * scale
height = height * scale
newimg = img.resize((width, height), Image.filter)
newimg.save('images\\LargeCy.png')
newimg.show()
img = Image.open('images\\cy.png')
pix = img.load()
width, height = img.size
scale = float(newSizeChoice())
filter = bestFilter(scale)
resize(img, width, height, scale, filter)
It’s a little bit of a mess right now, because I’m still working on it, but my problem is that when I set the filter in function ‘bestFilter’, I’m not able to use it to set the filter in function ‘resize’. The error I keep getting:
Traceback (most recent call last):
File "C:\Users\14davidson_a\Desktop\Projects\Exercises\ImageScaling.py", line 33, in <module>
resize(img, width, height, scale, filter)
File "C:\Users\14davidson_a\Desktop\Projects\Exercises\ImageScaling.py", line 23, in resize
newimg = img.resize((width, height), Image.filter)
AttributeError: 'module' object has no attribute 'filter'
Question: Is there a way I can use a string to set the attribute for a module?
You are trying to use
Image.filter, which is not defined on theImagemodule. Perhaps you meant to use thefilterargument of the method instead?You don’t use the
filterargument for anything else in that method.You’ll need to update your
bestFilter()function to return a validImagefilter:You could simplify that function by using a mapping: