Skip to content

Instantly share code, notes, and snippets.

@mdouchin
Last active April 17, 2019 12:45
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mdouchin/d66191ccfadd74cff3f0 to your computer and use it in GitHub Desktop.
Save mdouchin/d66191ccfadd74cff3f0 to your computer and use it in GitHub Desktop.
QGIS python code to use images as point symbols
"""
Use this method to use images stored in a layer field as path
Ex: show_picture( "picture_path_fieldname" )
Path can be absolute or relative to the project
/!\ Project must be saved before use
author: Michaël Douchin, 3liz
inspired by Nathan Woodrow example : http://nathanw.net/2016/02/04/live-svgs/
"""
import re, tempfile, os, base64
from qgis.core import QgsProject
@qgsfunction(args='auto', group='Custom')
def show_picture(picture, feature, parent):
# SVG content template
svg = """
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg><g>
<image xlink:href="data:image/jpeg;base64,{0}" height="256" width="320" />
</g></svg>
"""
# Build svg file path
tempDir = tempfile.gettempdir()
name = u"%s" % feature.id()
name+= re.sub(r'\W+', '', picture)
tPath = os.path.join(
tempDir,
"%s.svg" % name
)
# Return SVG path if already created before
if os.path.exists( tPath ):
return tPath.replace("\\", "/")
# Get the project folder
p = QgsProject.instance()
projectDir, projectName = os.path.split(os.path.abspath('%s' % p.fileName()))
# Get picture absolute path
if os.path.exists( picture):
picturePath = picture
else:
picturePath = os.path.normpath(
os.path.join(projectDir, picture)
)
# Build svg file
if os.path.exists( picturePath ):
with open(picturePath, "rb") as imageFile:
data = base64.b64encode(imageFile.read())
newsvg = svg.format(data).replace('\n','')
else:
newsvg = svg.format('').replace('\n','')
# Add content to svg file
with open(tPath, 'w') as f:
f.write(newsvg)
# Return SVG path
return tPath.replace("\\", "/")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment