Skip to content

Commit

Permalink
Merge pull request #4435 from radarhere/close_images
Browse files Browse the repository at this point in the history
Close exclusively opened images
  • Loading branch information
hugovk committed Mar 5, 2020
2 parents da4667c + 04f7c75 commit 0f7ed2d
Show file tree
Hide file tree
Showing 13 changed files with 60 additions and 49 deletions.
3 changes: 2 additions & 1 deletion docs/handbook/tutorial.rst
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
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
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
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
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
8 changes: 5 additions & 3 deletions src/PIL/EpsImagePlugin.py
Expand Up @@ -141,8 +141,8 @@ def Ghostscript(tile, size, fp, scale=1):
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
subprocess.check_call(command, startupinfo=startupinfo)
im = Image.open(outfile)
im.load()
out_im = Image.open(outfile)
out_im.load()
finally:
try:
os.unlink(outfile)
Expand All @@ -151,7 +151,9 @@ def Ghostscript(tile, size, fp, scale=1):
except OSError:
pass

return im.im.copy()
im = out_im.im.copy()
out_im.close()
return im


class PSFile:
Expand Down
4 changes: 2 additions & 2 deletions src/PIL/IcnsImagePlugin.py
Expand Up @@ -370,7 +370,7 @@ def _save(im, fp, filename):
for size in imf.info["sizes"]:
imf.size = size
imf.save("out-%s-%s-%s.png" % size)
im = Image.open(sys.argv[1])
im.save("out.png")
with Image.open(sys.argv[1]) as im:
im.save("out.png")
if sys.platform == "windows":
os.startfile("out.png")
8 changes: 7 additions & 1 deletion src/PIL/ImageFont.py
Expand Up @@ -71,7 +71,10 @@ class ImageFont:
def _load_pilfont(self, filename):

with open(filename, "rb") as fp:
image = None
for ext in (".png", ".gif", ".pbm"):
if image:
image.close()
try:
fullname = os.path.splitext(filename)[0] + ext
image = Image.open(fullname)
Expand All @@ -81,11 +84,14 @@ def _load_pilfont(self, filename):
if image and image.mode in ("1", "L"):
break
else:
if image:
image.close()
raise OSError("cannot find glyph data file")

self.file = fullname

return self._load_pilfont_data(fp, image)
self._load_pilfont_data(fp, image)
image.close()

def _load_pilfont_data(self, file, image):

Expand Down
4 changes: 3 additions & 1 deletion src/PIL/ImageGrab.py
Expand Up @@ -35,7 +35,9 @@ def grab(bbox=None, include_layered_windows=False, all_screens=False):
im.load()
os.unlink(filepath)
if bbox:
im = im.crop(bbox)
im_cropped = im.crop(bbox)
im.close()
return im_cropped
else:
offset, size, data = Image.core.grabscreen(include_layered_windows, all_screens)
im = Image.frombytes(
Expand Down
3 changes: 2 additions & 1 deletion src/PIL/ImageShow.py
Expand Up @@ -203,4 +203,5 @@ def get_command_ex(self, file, title=None, **options):
print("Syntax: python ImageShow.py imagefile [title]")
sys.exit()

print(show(Image.open(sys.argv[1]), *sys.argv[2:]))
with Image.open(sys.argv[1]) as im:
print(show(im, *sys.argv[2:]))
6 changes: 3 additions & 3 deletions src/PIL/IptcImagePlugin.py
Expand Up @@ -158,9 +158,9 @@ def load(self):
o.close()

try:
_im = Image.open(outfile)
_im.load()
self.im = _im.im
with Image.open(outfile) as _im:
_im.load()
self.im = _im.im
finally:
try:
os.unlink(outfile)
Expand Down
6 changes: 3 additions & 3 deletions src/PIL/JpegImagePlugin.py
Expand Up @@ -448,9 +448,9 @@ def load_djpeg(self):
raise ValueError("Invalid Filename")

try:
_im = Image.open(path)
_im.load()
self.im = _im.im
with Image.open(path) as _im:
_im.load()
self.im = _im.im
finally:
try:
os.unlink(path)
Expand Down
36 changes: 18 additions & 18 deletions src/PIL/SpiderImagePlugin.py
Expand Up @@ -304,21 +304,21 @@ def _save_spider(im, fp, filename):
print("input image must be in Spider format")
sys.exit()

im = Image.open(filename)
print("image: " + str(im))
print("format: " + str(im.format))
print("size: " + str(im.size))
print("mode: " + str(im.mode))
print("max, min: ", end=" ")
print(im.getextrema())

if len(sys.argv) > 2:
outfile = sys.argv[2]

# perform some image operation
im = im.transpose(Image.FLIP_LEFT_RIGHT)
print(
"saving a flipped version of %s as %s "
% (os.path.basename(filename), outfile)
)
im.save(outfile, SpiderImageFile.format)
with Image.open(filename) as im:
print("image: " + str(im))
print("format: " + str(im.format))
print("size: " + str(im.size))
print("mode: " + str(im.mode))
print("max, min: ", end=" ")
print(im.getextrema())

if len(sys.argv) > 2:
outfile = sys.argv[2]

# perform some image operation
im = im.transpose(Image.FLIP_LEFT_RIGHT)
print(
"saving a flipped version of %s as %s "
% (os.path.basename(filename), outfile)
)
im.save(outfile, SpiderImageFile.format)

0 comments on commit 0f7ed2d

Please sign in to comment.