Skip to content

Commit

Permalink
Use context manager when opening images [ci skip]
Browse files Browse the repository at this point in the history
  • Loading branch information
radarhere committed Feb 28, 2020
1 parent dd8b0de commit 04f7c75
Show file tree
Hide file tree
Showing 5 changed files with 17 additions and 17 deletions.
3 changes: 2 additions & 1 deletion docs/handbook/tutorial.rst
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,8 @@ Convert files to JPEG
outfile = f + ".jpg"
if infile != outfile:
try:
Image.open(infile).save(outfile)
with Image.open(infile) as im:
im.save(outfile)
except IOError:
print("cannot convert", infile)

Expand Down
12 changes: 6 additions & 6 deletions docs/reference/ImageDraw.rst
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,14 @@ Example: Draw a gray cross over an image
from PIL import Image, ImageDraw
im = Image.open("hopper.jpg")
with Image.open("hopper.jpg") as im:
draw = ImageDraw.Draw(im)
draw.line((0, 0) + im.size, fill=128)
draw.line((0, im.size[1], im.size[0], 0), fill=128)
draw = ImageDraw.Draw(im)
draw.line((0, 0) + im.size, fill=128)
draw.line((0, im.size[1], im.size[0], 0), fill=128)
# write to stdout
im.save(sys.stdout, "PNG")
# write to stdout
im.save(sys.stdout, "PNG")
Concepts
Expand Down
11 changes: 5 additions & 6 deletions docs/reference/ImageSequence.rst
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,11 @@ Extracting frames from an animation
from PIL import Image, ImageSequence
im = Image.open("animation.fli")
index = 1
for frame in ImageSequence.Iterator(im):
frame.save("frame%d.png" % index)
index += 1
with Image.open("animation.fli") as im:
index = 1
for frame in ImageSequence.Iterator(im):
frame.save("frame%d.png" % index)
index += 1
The :py:class:`~PIL.ImageSequence.Iterator` class
-------------------------------------------------
Expand Down
4 changes: 2 additions & 2 deletions docs/reference/PixelAccess.rst
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ changes it.
.. code-block:: python
from PIL import Image
im = Image.open('hopper.jpg')
px = im.load()
with Image.open('hopper.jpg') as im:
px = im.load()
print (px[4,4])
px[4,4] = (0,0,0)
print (px[4,4])
Expand Down
4 changes: 2 additions & 2 deletions docs/reference/PyAccess.rst
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ The following script loads an image, accesses one pixel from it, then changes it
.. code-block:: python
from PIL import Image
im = Image.open('hopper.jpg')
px = im.load()
with Image.open('hopper.jpg') as im:
px = im.load()
print (px[4,4])
px[4,4] = (0,0,0)
print (px[4,4])
Expand Down

0 comments on commit 04f7c75

Please sign in to comment.