Use context manager when opening images [ci skip]

This commit is contained in:
Andrew Murray 2020-02-29 10:29:44 +11:00
parent dd8b0de666
commit 04f7c75466
5 changed files with 17 additions and 17 deletions

View File

@ -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)

View File

@ -20,7 +20,7 @@ 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)

View File

@ -14,8 +14,7 @@ Extracting frames from an animation
from PIL import Image, ImageSequence
im = Image.open("animation.fli")
with Image.open("animation.fli") as im:
index = 1
for frame in ImageSequence.Iterator(im):
frame.save("frame%d.png" % index)

View File

@ -17,7 +17,7 @@ changes it.
.. code-block:: python
from PIL import Image
im = Image.open('hopper.jpg')
with Image.open('hopper.jpg') as im:
px = im.load()
print (px[4,4])
px[4,4] = (0,0,0)

View File

@ -18,7 +18,7 @@ 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')
with Image.open('hopper.jpg') as im:
px = im.load()
print (px[4,4])
px[4,4] = (0,0,0)