[Image-SIG] PIL - Opens tga as WbmpImageFile

Zac Burns zac256 at gmail.com
Mon May 18 20:05:54 CEST 2009


On Mon, May 18, 2009 at 9:49 AM, Zac Burns <zac256 at gmail.com> wrote:
> I have a script that is attempting to verify that an image is square.
>
> This is accomplished using PIL.Image.open(filename).size
>
> Within the context that the script is being run it is opening a tga as
> a WbmpImageFile and reporting the size to be (2, 0).
> However, printing repr(filename), copying the filename, and running
> the line with that file from a fresh Python interpreter gives the
> correct results.
>
>
> PIL version is 1.1.6
> Python version is 2.5.1
>
> --
> Zachary Burns
> (407)590-4814
> Aim - Zac256FL
> Production Engineer (Digital Overlord)
> Zindagi Games
>

I locally patched the PIL.Image.open function to fix the bug and made
some other improvements along the way.

I'm not familiar with the PIL patch process and am not sure that the
changes will be accepted by the community so I'll just post the code
here.

Chages:
   1. More informative error message
   2. Optimization: Moved import __builtin__ to top of file. (I'm not
sure why but importing is relatively slow on my machine)
   3. Factored shared code into an inline function
   4. Does preinit and init before trying any plugins
   5. Prefers the extension of the filepath

I presume there were reasons for doing it the other way before, which
is why the patch might not be accepted.

One problem right now is that the "preferredID" is only implemented if
fp is given as a string. I would like "preferredID =
os.path.splitext(filename)[1]" to read like "preferredID =
os.path.splitext(filename or getattr(fp, name))[1]" except that name
might be of the form "<...>" which doesn't play well with
os.path.splitext.

###########################################
def open(fp, mode="r"):
	"Open an image file, without loading the raster data"

	if mode != "r":
		raise ValueError("bad mode")

	if isStringType(fp):
		filename = fp
		fp = __builtin__.open(fp, "rb")
	else:
		filename = ""

	prefix = fp.read(16)

	preinit()
	init()

	def _open(id_):
		factory, accept = OPEN[id_]
		if not accept or accept(prefix):
			fp.seek(0)
			return factory(fp, filename)

	_open_errors = (SyntaxError, IndexError, TypeError)

	# Prefer extension of filename if given.
	preferredID = os.path.splitext(filename)[1]
	if preferredID:
		preferredID = preferredID[1:].upper() # OPEN keys are uppercase without a '.'
		if preferredID in OPEN:
			try:
				return _open(preferredID)
			except _open_errors:
				pass

	# Try each ID in order
	for i in ID:
		try:
			return _open(i)
		except _open_errors:
			pass

	raise IOError("cannot identify image file %s" % repr(filename or fp))
###########################################

--
Zachary Burns
(407)590-4814
Aim - Zac256FL
Production Engineer (Digital Overlord)
Zindagi Games


More information about the Image-SIG mailing list