Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add an openImage function that can open PIL images and download from http #77

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
5 changes: 3 additions & 2 deletions cmu_graphics/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@
round,
dcos,
dsin,
openImage,
onSteps,
onKeyHolds,
onKeyPresses,
Expand Down Expand Up @@ -142,7 +143,7 @@
)

__all__ = TRANSLATED_GLOBALS['keys']
__all__.extend(['setLanguage', 'cmu_graphics', 'runApp', 'runAppWithScreens', 'setActiveScreen', 'getImageSize', 'dcos', 'dsin'])
__all__.extend(['setLanguage', 'cmu_graphics', 'runApp', 'runAppWithScreens', 'setActiveScreen', 'getImageSize', 'dcos', 'dsin', 'openImage'])
__all__.extend(['drawArc', 'ArcShape', 'drawCircle', 'CircleShape', 'drawImage', 'ImageShape', 'drawLabel', 'LabelShape', 'drawLine', 'LineShape', 'drawOval', 'OvalShape', 'drawPolygon', 'PolygonShape', 'drawRect', 'RectShape', 'drawRegularPolygon', 'RegularPolygonShape', 'drawStar', 'StarShape'])

g = globals()
Expand All @@ -160,4 +161,4 @@
globals()[trans_name] = en_name == 'True'
__all__.append(trans_name)

__all__ = list(set(__all__))
__all__ = list(set(__all__))
27 changes: 27 additions & 0 deletions cmu_graphics/cmu_graphics.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

from cmu_graphics.shape_logic import TRANSLATED_KEY_NAMES, _ShapeMetaclass
from cmu_graphics import shape_logic
from PIL import Image as PILImage

class Signal():
def __init__(self):
Expand Down Expand Up @@ -45,6 +46,32 @@ def dsin(angle):
def dcos(angle):
return math.cos(math.radians(angle))

def openImage(fileName):
if not isinstance(fileName, str):
callSpec = '{className}.{attr}'.format(className=t('Image'), attr=t('url'))
err = t(
'{{error}}: {{callSpec}} should be {{typeName}} (but {{value}} is of type {{valueType}})',
{'error': t('TypeError'), 'callSpec': callSpec, 'typeName': 'string', 'value': repr(fileName), 'valueType': type(fileName).__name__}
)
raise Exception(err)
if (fileName.startswith('http')):
# reference is a url
for i in range(10):
try:
response = webrequest.get(fileName)
return PILImage.open(response)
except:
if i < 9:
continue
else:
raise(t('Failed to open image'))
break
elif hasattr(__main__, '__file__'): # running with a file
main_directory = os.path.abspath(__main__.__file__) + '/../'
else: # running in a REPL
main_directory = os.getcwd() + '/'
return PILImage.open(main_directory + fileName)

def setLanguage(language):
sli.setLanguage(language)

Expand Down
12 changes: 6 additions & 6 deletions cmu_graphics/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,13 +142,13 @@ def edgesIntersect(edges1, edges2):
active_edges2 = set()

# Here we're looping over a list of all line segments' start and ends points,
# which is sorted by the points' x values.
#
# which is sorted by the points' x values.
#
# We're keeping track of which line segments are "active" as we go
# (which line segments intersect with the line x=x for the current x value).
#
#
# When we encounter a new line segment, we see if it intersects with any
# active line segments in the other shape.
# active line segments in the other shape.
for (_, events) in sorted(x_to_events.items(), key=lambda item: item[0]):
for shape, event_type, edge1 in events:
my_active_edges, other_active_edges = (active_edges1, active_edges2) if shape == 1 else (active_edges2, active_edges1)
Expand Down Expand Up @@ -279,7 +279,7 @@ def getArcPoints(cx, cy, width, height, startAngle = None, sweepAngle = None, si
n = rounded(6 + 18 * sizeForN / 50)
n = math.ceil(n / 4) * 4
denominator = n if sweepAngle == 360 else n - 1
startAngle = toRadians(startAngle) if isMvc else toRadians(90 - startAngle)
startAngle = toRadians(startAngle) if isMvc else toRadians(90 - startAngle)
sweepAngle = toRadians(sweepAngle)
multiplyFactor = 1 if isMvc else -1;
for i in range(n):
Expand Down Expand Up @@ -360,4 +360,4 @@ def convertLabelValue(value):
def min_or_inf(L):
if len(L) == 0:
return math.inf
return min(L)
return min(L)
2 changes: 2 additions & 0 deletions tests/image_gen/openImage_util_func.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Image(CMUImage(openImage('image_gen/sample.jpg')), 0,0, width=400, height=400)
Image(CMUImage(openImage('https://academy.cs.cmu.edu/static/media/project_10.472f439f.jpg')), 0,0)
Binary file added tests/image_gen/openImage_util_func/correct_1.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.