Hi all,

The attached patch restructures Image.fromarray and fixes it for RGBA
images.  I hope this is the right place to post it (if not, I'd
appreciate it if you could point me in the right direction).

Regards
Stéfan
--- /usr/lib/python2.5/site-packages/PIL/Image.py	2006-12-03 14:08:22.000000000 +0200
+++ Image.py	2007-08-28 17:15:01.000000000 +0200
@@ -1824,34 +1824,37 @@
         strides = arr['strides']
     except KeyError:
         strides = None
-    if mode is None:
-        typestr = arr['typestr']
-        if not (typestr[0] == '|' or typestr[0] == _ENDIAN or
-                typestr[1:] not in ['u1', 'b1', 'i4', 'f4']):
-            raise TypeError("cannot handle data-type")
-        typestr = typestr[:2]
-        if typestr == 'i4':
-            mode = 'I'
-        elif typestr == 'f4':
-            mode = 'F'
-        elif typestr == 'b1':
-            mode = '1'
-        elif ndim == 2:
-            mode = 'L'
-        elif ndim == 3:
-            mode = 'RGB'
-        elif ndim == 4:
-            mode = 'RGBA'
+
+    byteorder = arr['typestr'][0]
+    typestr = arr['typestr'][1:]
+    typemap = {'u1':'L',
+               'i4':'I',
+               'b1':'1',
+               'f4':'F'}
+
+    is_colour = (ndim == 3) and (shape[-1] != 1)
+    colour_mode = {3:'RGB',
+                   4:'RGBA'}
+
+    if is_colour:
+        if not typestr == 'u1':
+            raise TypeError("Colour images must be of type uint8.")
+
+        if shape[-1] in colour_mode:
+            mode = colour_mode[shape[-1]]
         else:
-            raise TypeError("Do not understand data.")
-    ndmax = 4
-    bad_dims=0
-    if mode in ['1','L','I','P','F']:
-        ndmax = 2
-    elif mode == 'RGB':
-        ndmax = 3
-    if ndim > ndmax:
-        raise ValueError("Too many dimensions.")
+            raise ValueError("Image has invalid number of colour bands.")
+
+    elif mode is None:
+        if not byteorder in [_ENDIAN,'|']:
+            raise "Cannot handle non-native endian type."
+        if not typestr in typemap:
+            raise TypeError("Cannot handle data-type %s." % typestr)
+
+        mode = typemap[typestr]
+
+    if ndim < 1 or ndim > 3:
+        raise ValueError("Input array has too many dimensions.")
 
     size = shape[:2][::-1]
     if strides is not None:
_______________________________________________
Image-SIG maillist  -  Image-SIG@python.org
http://mail.python.org/mailman/listinfo/image-sig

Reply via email to