Welcome to mirror list, hosted at ThFree Co, Russian Federation.

git.blender.org/blender.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorCampbell Barton <ideasman42@gmail.com>2006-02-01 13:31:49 +0300
committerCampbell Barton <ideasman42@gmail.com>2006-02-01 13:31:49 +0300
commitc8ff92d965e9469b1a5c3ce1eadfb7d1ffcfc6dc (patch)
tree221b776f929cc6aa14a731bdb8a7fefc9e01f54d /release
parentbee859fe1759ad6b83b99a29adea7fa114f5e53e (diff)
Added a function for importers to use, comprehensive image loader takes an imagepath and a file path- and imports the image, if it exists it uses the one alredy loaded or does a realy good job of finding the right image case insensitite if the normal path is not found. looks in all the logical places for the image- If teh image isnt found then a new dummy image is returned.
The nice thing about this is you can request an image and you know youll get an image back- without doing your own error handeling.
Diffstat (limited to 'release')
-rw-r--r--release/scripts/bpymodules/BPyImage.py256
1 files changed, 256 insertions, 0 deletions
diff --git a/release/scripts/bpymodules/BPyImage.py b/release/scripts/bpymodules/BPyImage.py
new file mode 100644
index 00000000000..d6fb38c575d
--- /dev/null
+++ b/release/scripts/bpymodules/BPyImage.py
@@ -0,0 +1,256 @@
+# --------------------------------------------------------------------------
+# BPyImage.py version 0.1
+# --------------------------------------------------------------------------
+# helper functions to be used by other scripts
+# --------------------------------------------------------------------------
+# ***** BEGIN GPL LICENSE BLOCK *****
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software Foundation,
+# Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+#
+# ***** END GPL LICENCE BLOCK *****
+# --------------------------------------------------------------------------
+
+#===========================================================================#
+# Comprehensive image loader, will search and find the image #
+# Will return a blender image or a new image if the image is missing #
+#===========================================================================#
+import Blender
+from Blender import sys
+try:
+ import os
+except:
+ os=None
+
+#==============================================#
+# Return directory, where the file is #
+#==============================================#
+def stripFile(path):
+ lastSlash = max(path.rfind('\\'), path.rfind('/'))
+ if lastSlash != -1:
+ path = path[:lastSlash]
+ return '%s%s' % (path, sys.sep)
+
+#==============================================#
+# Strips the slashes from the back of a string #
+#==============================================#
+def stripPath(path):
+ return path.split('/')[-1].split('\\')[-1]
+
+#====================================================#
+# Strips the prefix off the name before writing #
+#====================================================#
+def stripExt(name): # name is a string
+ index = name.rfind('.')
+ if index != -1:
+ return name[ : index ]
+ else:
+ return name
+
+def getExt(name):
+ index = name.rfind('.')
+ if index != -1:
+ return name[index+1:]
+ return name
+
+#====================================================#
+# Adds a slash to the end of a path if its not there #
+#====================================================#
+def addSlash(path):
+ if path.endswith('\\') or path.endswith('/'):
+ return path
+ return path + sys.sep
+
+def comprehensiveImageLoad(imagePath, filePath, VERBOSE=False):
+
+ # When we have the file load it with this. try/except niceness.
+ def imageLoad(path):
+ try:
+ img = Blender.Image.Load(path)
+ if VERBOSE: print '\t\tImage loaded "%s"' % path
+ return img
+ except:
+ if VERBOSE: print '\t\tImage failed loading "%s", mabe its not a format blender can read.' % (path)
+ return Blender.Image.New(stripPath(path),1,1,24) #blank image
+
+ # Image formats blender can read
+ IMAGE_EXT = ['jpg', 'jpeg', 'png', 'tga', 'bmp', 'rgb', 'sgi', 'bw', 'iff', 'lbm', # Blender Internal
+ 'gif', 'psd', 'tif', 'tiff', 'pct', 'pict', 'pntg', 'qtif'] # Quacktime, worth a try.
+
+ imageFileName = stripPath(imagePath) # image path only
+ imageFileName_lower = imageFileName.lower() # image path only
+
+ if VERBOSE: print '\tSearchingExisting Images for "%s"' % imagePath
+ for i in Blender.Image.Get():
+ if stripPath(i.filename.lower()) == imageFileName_lower:
+ if VERBOSE: print '\t\tUsing existing image.'
+ return i
+
+
+ if VERBOSE: print '\tAttempting to load "%s"' % imagePath
+ if sys.exists(imagePath):
+ if VERBOSE: print '\t\tFile found where expected.'
+ return imageLoad(imagePath)
+
+
+
+ imageFileName_noext = stripExt(imageFileName) # With no extension.
+ imageFileName_noext_lower = stripExt(imageFileName_lower) # With no extension.
+ imageFilePath = stripFile(imagePath)
+
+ # Remove relative path from image path
+ if imageFilePath.startswith('./') or imageFilePath.startswith('.\\'):
+ imageFilePath = imageFilePath[2:]
+
+
+ # Attempt to load from obj path.
+ tmpPath = stripFile(filePath) + stripFile(imageFilePath)
+ if sys.exists(tmpPath):
+ if VERBOSE: print '\t\tFile found in obj dir.'
+ return imageLoad(imagePath)
+
+
+ # os needed if we go any further.
+ if os == None:
+ return imageLoad(imagePath) # Will jus treturn a placeholder.
+
+
+ # We have os.
+ # GATHER PATHS.
+ paths = {} # Store possible paths we may use, dict for no doubles.
+ tmpPath = addSlash(sys.expandpath('//')) # Blenders path
+ if sys.exists(tmpPath):
+ if VERBOSE: print '\t\tSearching in %s' % tmpPath
+ paths[tmpPath] = [os.listdir(tmpPath)] # Orig name for loading
+ paths[tmpPath].append([f.lower() for f in paths[tmpPath][0]]) # Lower case list.
+ paths[tmpPath].append([stripExt(f) for f in paths[tmpPath][1]]) # Lower case no ext
+
+ tmpPath = imageFilePath
+ if sys.exists(tmpPath):
+ if VERBOSE: print '\t\tSearching in %s' % tmpPath
+ paths[tmpPath] = [os.listdir(tmpPath)] # Orig name for loading
+ paths[tmpPath].append([f.lower() for f in paths[tmpPath][0]]) # Lower case list.
+ paths[tmpPath].append([stripExt(f) for f in paths[tmpPath][1]]) # Lower case no ext
+
+ tmpPath = stripFile(filePath)
+ if sys.exists(tmpPath):
+ if VERBOSE: print '\t\tSearching in %s' % tmpPath
+ paths[tmpPath] = [os.listdir(tmpPath)] # Orig name for loading
+ paths[tmpPath].append([f.lower() for f in paths[tmpPath][0]]) # Lower case list.
+ paths[tmpPath].append([stripExt(f) for f in paths[tmpPath][1]]) # Lower case no ext
+
+ tmpPath = addSlash(Blender.Get('texturesdir'))
+ if tmpPath and sys.exists(tmpPath):
+ if VERBOSE: print '\t\tSearching in %s' % tmpPath
+ paths[tmpPath] = [os.listdir(tmpPath)] # Orig name for loading
+ paths[tmpPath].append([f.lower() for f in paths[tmpPath][0]]) # Lower case list.
+ paths[tmpPath].append([stripExt(f) for f in paths[tmpPath][1]]) # Lower case no ext
+
+ # Add path if relative image patrh was given.
+ for k in paths.iterkeys():
+ tmpPath = k + imageFilePath
+ if sys.exists(tmpPath):
+ paths[tmpPath] = [os.listdir(tmpPath)] # Orig name for loading
+ paths[tmpPath].append([f.lower() for f in paths[tmpPath][0]]) # Lower case list.
+ paths[tmpPath].append([stripExt(f) for f in paths[tmpPath][1]]) # Lower case no ext
+ # DONE
+
+
+ #
+ for path, files in paths.iteritems():
+
+ if sys.exists(path + imageFileName):
+ return imageLoad(path + imageFileName)
+
+ # If the files not there then well do a case insensitive seek.
+ filesOrigCase = files[0]
+ filesLower = files[1]
+ filesLowerNoExt = files[2]
+
+ # We are going to try in index the file directly, if its not there just keep on
+ index = None
+ try:
+ # Is it just a case mismatch?
+ index = filesLower.index(imageFileName_lower)
+ except:
+ try:
+ # Have the extensions changed?
+ index = filesLowerNoExt.index(imageFileName_noext_lower)
+
+ ext = getExt( filesLower[index] ) # Get the extension of the file that matches all but ext.
+
+ # Check that the ext is useable eg- not a 3ds file :)
+ if ext.lower() not in IMAGE_EXT:
+ index = None
+
+ except:
+ index = None
+
+ if index != None:
+ tmpPath = path + filesOrigCase[index]
+ img = imageLoad( tmpPath )
+ if img != None:
+ if VERBOSE: print '\t\tImage Found "%s"' % tmpPath
+ return img
+
+
+ # IMAGE NOT FOUND IN ANY OF THE DIRS!, DO A RECURSIVE SEARCH.
+ if VERBOSE: print '\t\tImage Not Found in any of the dirs, doing a recusrive search'
+ for path in paths.iterkeys():
+ # Were not going to use files
+
+
+ #------------------
+ # finds the file starting at the root.
+ # def findImage(findRoot, imagePath):
+ #W---------------
+
+ # ROOT, DIRS, FILES
+ pathWalk = os.walk(path)
+ pathList = [True]
+
+ matchList = [] # Store a list of (match, size), choose the biggest.
+ while True:
+ try:
+ pathList = pathWalk.next()
+ except:
+ break
+
+ for file in pathList[2]:
+ file_lower = file.lower()
+ # FOUND A MATCH
+ if (file_lower == imageFileName_lower) or\
+ (stripExt(file_lower) == imageFileName_noext_lower and getExt(file_lower) in IMAGE_EXT):
+ name = pathList[0] + sys.sep + file
+ size = os.path.getsize(name)
+ if VERBOSE: print '\t\t\tfound:', name
+ matchList.append( (name, size) )
+
+ if matchList:
+ # Sort by file size
+ matchList.sort(lambda A, B: cmp(B[1], A[1]) )
+
+ if VERBOSE: print '\t\tFound "%s"' % matchList[0][0]
+
+ # Loop through all we have found
+ img = None
+ for match in matchList:
+ img = imageLoad(match[0]) # 0 - first, 0 - pathname
+ if img != None:
+ break
+ return img
+
+ # No go.
+ if VERBOSE: print '\t\tImage Not Found "%s"' % imagePath
+ return imageLoad(imagePath) # Will jus treturn a placeholder. \ No newline at end of file