Close excusively opened images

This commit is contained in:
Andrew Murray 2020-02-18 20:49:05 +11:00
parent 8ec548d163
commit dd8b0de666
8 changed files with 41 additions and 30 deletions

View File

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

View File

@ -370,7 +370,7 @@ if __name__ == "__main__":
for size in imf.info["sizes"]:
imf.size = size
imf.save("out-%s-%s-%s.png" % size)
im = Image.open(sys.argv[1])
with Image.open(sys.argv[1]) as im:
im.save("out.png")
if sys.platform == "windows":
os.startfile("out.png")

View File

@ -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)
@ -81,11 +84,14 @@ class ImageFont:
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):

View File

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

View File

@ -203,4 +203,5 @@ if __name__ == "__main__":
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:]))

View File

@ -158,7 +158,7 @@ class IptcImageFile(ImageFile.ImageFile):
o.close()
try:
_im = Image.open(outfile)
with Image.open(outfile) as _im:
_im.load()
self.im = _im.im
finally:

View File

@ -448,7 +448,7 @@ class JpegImageFile(ImageFile.ImageFile):
raise ValueError("Invalid Filename")
try:
_im = Image.open(path)
with Image.open(path) as _im:
_im.load()
self.im = _im.im
finally:

View File

@ -304,7 +304,7 @@ if __name__ == "__main__":
print("input image must be in Spider format")
sys.exit()
im = Image.open(filename)
with Image.open(filename) as im:
print("image: " + str(im))
print("format: " + str(im.format))
print("size: " + str(im.size))