-
Notifications
You must be signed in to change notification settings - Fork 7
/
gimpVbrBrush.py
227 lines (206 loc) · 7.11 KB
/
gimpVbrBrush.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
#!/usr/bin/env
# -*- coding: utf-8 -*-
"""
Pure python implementation of the gimp vbr brush format
"""
from typing import Optional,Union,BinaryIO
class GimpVbrBrush:
"""
Pure python implementation of the gimp vbr brush format
See:
https://gitlab.gnome.org/GNOME/gimp/blob/master/devel-docs/vbr.txt
Format:
name: GimpVbrBrush
description: Gimp brush
guid: {45129576-6728-4967-8888-6b9082862ca6}
parentNames: Image
#mimeTypes: application/jpeg
filenamePatterns: *.vbr
"""
MAGIC_NUMBER=(0,'GIMP-VBR')
BRUSH_SHAPES=["circle","square","diamond"]
def __init__(self,filename: Optional[Union[str,BinaryIO]]=None) -> None:
self.version:float=1.0
self.name:str=''
self.spacing:float=0
self.radius:float=50
self.hardness:float=1
self.aspectRatio:float=1
self.angle:float=0
self.brushShape:Union[str,None]=None # one of the strings in self.BRUSH_SHAPES
self.spikes:Union[float,None]=None
self.filename:Union[str,None]=None
if filename is not None:
self.load(filename)
def load(self,filename: Union[str,BinaryIO]) -> None:
"""
load a gimp file
:param filename: can be a file name or a file-like object
"""
if hasattr(filename,'read'):
self.filename=filename.name
data=filename.read()
else:
self.filename=filename
f=open(filename,'r')
data=f.read()
f.close()
self._decode_(data)
@property
def image(self):
"""
this parametric brush converted to a useable PIL image
"""
raise NotImplementedError() # TODO:
def _decode_(self,data: Union[str,bytes],index: int=0) -> None:
"""
decode a byte buffer
:param data: data buffer to decode
:param index: index within the buffer to start at
"""
if isinstance(data,bytes):
data=data.decode('utf-8')
data=[s.strip() for s in data.split('\n')]
if data[0]!="GIMP-VBR":
raise Exception('File format error. Magic value mismatch.')
self.version=float(data[1])
if self.version==1.0:
self.name=data[2] # max len 255 bytes
self.spacing=float(data[3])
self.radius=float(data[4])
self.hardness=float(data[5])
self.aspectRatio=float(data[6])
self.angle=float(data[7])
elif self.version==1.5:
self.name=data[2] # max len 255 bytes
self.brushShape=data[3] # one of the strings in self.BRUSH_SHAPES
self.spacing=float(data[4])
self.radius=float(data[5])
self.spikes=float(data[6])
self.hardness=float(data[7])
self.aspectRatio=float(data[8])
self.angle=float(data[9])
else:
raise Exception('Unknown version '+str(self.version))
def toBytes(self) -> bytes:
"""
encode to a raw data stream
"""
data=[]
data.append("GIMP-VBR")
data.append(str(self.version))
if self.version==1.0:
data.append(str(self.name))
data.append(str(self.spacing))
data.append(str(self.radius))
data.append(str(self.hardness))
data.append(str(self.aspectRatio))
data.append(str(self.angle))
elif self.version==1.5:
data.append(str(self.name))
data.append(str(self.brushShape))
data.append(str(self.spacing))
data.append(str(self.radius))
data.append(str(self.spikes))
data.append(str(self.hardness))
data.append(str(self.aspectRatio))
data.append(str(self.angle))
return ('\n'.join(data)+'\n').encode('utf-8')
def save(self,toFilename: Union[None,str,BinaryIO]=None,
toExtension: Union[str,None]=None) -> None:
"""
save this gimp image to a file
"""
asImage=False
if toFilename is None:
if self.filename is None:
self.filename='Untitled.vbr'
toFilename=self.filename
else:
self.filename=toFilename
if toExtension is None:
if toFilename is not None:
toExtension=toFilename.rsplit('.',1)
if len(toExtension)>1:
toExtension=toExtension[-1]
else:
toExtension=None
if toExtension is not None and toExtension!='vbr':
asImage=True
if asImage:
self.image.save(toFilename)
else:
if not hasattr(toFilename,'write'):
f=open(toFilename,'wb')
f.write(self.toBytes())
def __repr__(self,indent=''):
"""
Get a textual representation of this object
"""
ret=[]
if self.filename is not None:
ret.append('Filename: '+self.filename)
ret.append('Name: '+str(self.name))
ret.append('Version: '+str(self.version))
ret.append('Spacing: '+str(self.spacing))
ret.append('Radius: '+str(self.radius))
ret.append('Hardness: '+str(self.hardness))
ret.append('Aspect ratio: '+str(self.aspectRatio))
ret.append('Angle: '+str(self.angle))
ret.append('Brush Shape: '+str(self.brushShape))
ret.append('Spikes: '+str(self.spikes))
return '\n'.join(ret)
def __eq__(self,other: 'GimpVbrBrush') -> bool:
"""
perform a comparison
"""
if other.name!=self.name:
return False
if other.version!=self.version:
return False
if other.spacing!=self.spacing:
return False
if other.radius!=self.radius:
return False
if other.hardness!=self.hardness:
return False
if other.aspectRatio!=self.aspectRatio:
return False
if other.angle!=self.angle:
return False
if other.brushShape!=self.brushShape:
return False
if other.spikes!=self.spikes:
return False
return True
def cmdline(args):
"""
Run the command line
:param args: command line arguments (WITHOUT the filename)
"""
printhelp=False
if not args:
printhelp=True
else:
g=None
for arg in args:
if arg.startswith('-'):
arg=[a.strip() for a in arg.split('=',1)]
if arg[0] in ['-h','--help']:
printhelp=True
elif arg[0]=='--dump':
print(g)
else:
print('ERR: unknown argument "'+arg[0]+'"')
else:
g=GimpVbrBrush(arg)
if printhelp:
print('Usage:')
print(' gimpVbrBrush.py file.xcf [options]')
print('Options:')
print(' -h, --help ............ this help screen')
print(' --dump ................ dump info about this file')
print(' --register ............ register this extension')
if __name__=='__main__':
import sys
cmdline(sys.argv[1:])