forked from tweecode/twine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
images.py
65 lines (58 loc) · 2.05 KB
/
images.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
"""
A module for handling base64 encoded images and other assets.
"""
import sys, cStringIO, wx, re
def AddURIPrefix(text, mimeType):
""" Adds the Data URI MIME prefix to the base64 data"""
# SVG MIME-type is the same for both images and fonts
mimeType = mimeType.lower()
if mimeType in 'gif|jpg|jpeg|png|webp|svg':
mimeGroup = "image/"
elif mimeType == 'woff':
mimeGroup = "application/font-"
elif mimeType in 'ttf|otf':
mimeGroup = "application/x-font-"
else:
mimeGroup = "application/octet-stream"
# Correct certain MIME types
if mimeType == "jpg":
mimeType == "jpeg"
elif mimeType == "svg":
mimeType += "+xml"
return "data:" + mimeGroup + mimeType + ";base64," + text
def RemoveURIPrefix(text):
"""Removes the Data URI part of the base64 data"""
index = text.find(';base64,')
return text[index+8:] if index else text
def Base64ToBitmap(text):
"""Converts the base64 data URI back into a bitmap"""
try:
# Remove data URI prefix and MIME type
text = RemoveURIPrefix(text)
# Convert to bitmap
imgData = text.decode('base64')
stream = cStringIO.StringIO(imgData)
return wx.BitmapFromImage(wx.ImageFromStream(stream))
except:
pass
def BitmapToBase64PNG(bmp):
img = bmp.ConvertToImage()
# "PngZL" in wxPython 2.9 is equivalent to wx.IMAGE_OPTION_PNG_COMPRESSION_LEVEL in wxPython Phoenix
img.SetOptionInt("PngZL", 9)
stream = cStringIO.StringIO()
try:
img.SaveStream(stream, wx.BITMAP_TYPE_PNG)
return "data:image/png;base64," + stream.getvalue().encode('base64')
except:
pass
def GetImageType(text):
"""Returns the part of the Data URI's MIME type that refers to the type of the image."""
# By using (\w+), "svg+xml" becomes "svg"
search = re.search(r"data:image/(\w+)", text)
if (search):
return "." + search.group(1)
#Fallback
search = re.search(r"application:x-(\w+)", text)
if (search):
return "." + search.group(1)
return ""