summaryrefslogtreecommitdiff
path: root/Pb/Grid/__init__.py
blob: 09718bdd2005a52f2c2a1710070f0aefab574cc9 (plain)
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
#!/usr/bin/python2.7
import sys
import re
import os
import simplejson as json
import random
from Config import DEFAULT_FINALFORMAT, DEFAULT_HEIGHT, DEFAULT_WIDTH, WORKING_DIR
from Config import THREEDROTATE, GRID 
import tempfile
from Pb import Pb

_default_line_color = "silver"

class Imgrid(Pb):
    def __init__(self, 
          width=None,
          height=None,
          linethickness=None,
          opacity=None,
          linecolor=None,
          spacing=None,
          vlines=None,
          hlines=None,
          shadow=None,
          bgimage=None,
          bgcolor=None,
          imageinstead=None,
          planebgcolor=None,
          planebgimage=None,
          swing=None,
          tilt=None,
          roll=None,
          zoom=None,
          skycolor=None,
          transition=None,
          trim=None,
          finalformat=DEFAULT_FINALFORMAT,
          username=None
        ):
        super(Imgrid,self).__init__();

        _frame = inspect.currentframe(); 
        _args_vals = inspect.getargvalues(_frame);
        for arg in _args_vals.args:
          if arg == "self":
            continue
          argval = _args_vals.locals.get(arg)
          try:
            if arg in [ 'skycolor', 'bgcolor', 'planebgcolor','linecolor' ]:
              self.params.set_val(arg, argval, value_type="color")
            elif arg == 'opacity':
              self.params.set_val(arg, argval, value_type="float")
            elif arg == 'zoom':
              self.params.set_val(arg, argval, value_type="int")
            elif arg in [ 'bgimage', 'planebgimage', 'imageinstead' ]:
              self.params.set_val(arg, argval, value_type="img_url")
              if self.params.get_mimetype(arg) == 'gif':
                self.params.gif_convert_to_still(arg)
              self.files_created.append(self.params.get_filepath(arg))
            elif arg in ['finalformat', 'username' ] :
              self.params.set_val(arg, argval, value_type="string")
            else:
              self.params.set_val(arg, argval, value_type="bool")
  
          except Exception as e:
            self.log_err(str(e))

        #FIXME these need to be bumped up to the parent class
        self.basename = self._get_filename();
        self.filename = "{}.{}".format(self.basename, self.params.finalformat)
        #final filepath is stored in self.filepath
        self.filepath = os.path.join(WORKING_DIR, self.filename) 



    #makes a canvas file...step 1 (if not bgimage)
    def _make_canvas(self):
        dimensions = "{}x{}".format(
            self.params.width or DEFAULT_WIDTH, 
            self.params.height or DEFAULT_HEIGHT
        )
        if self.params.bgimage:
            return 
        bgcolor = "xc:{}".format(self.params.bgcolor or 'transparent')
        cmd = [ BIN_CONVERT, "-size", dimensions, bgcolor, self.filepath ]
        self._call_cmd(cmd)

    #2nd step-- run grid
    def _grid_command(self):
        cmd = [GRID]
        if self.params.spacing:
            if self.params.vlines:
                width = 2 * int(self.params.width or DEFAULT_WIDTH)
                cmd += ["-s","{},{}".format(self.params.spacing,width)]
            elif self.params.hlines:
                height = 2 * int(self.params.height or DEFAULT_HEIGHT)
                cmd += ["-s", "{},{}".format(height,self.params.spacing)]
            else:
                cmd += ["-s",self.params.spacing]
        cmd += [ "-c", self.params.linecolor or _default_line_color]
        if self.params.linethickness: cmd += ['-t',self.params.linethickness]
        if self.params.opacity: cmd += ['-o',self.params.opacity]
        cmd += [ self.filepath, self.filepath ]
        self._call_cmd(cmd)
    
    def _shadow_cmd(self):
    #convert 1.png \( +clone -background black -shadow 110x1+9+9 \) +swap -background none -layers merge +repage 2.png
        cmd = [
            BIN_CONVERT,
            self.filepath,
            "(","+clone","-background","black","-shadow","100x2+20+10",")",
            "+swap","-background","none","-layers","merge","+repage" ,
            self.filepath
        ]
        self._call_cmd(cmd)
            
    
    def _threed_rotate_cmd (self):
    #3rd step--run 3Drotate
        cmd = [THREEDROTATE]
        if self.params.swing: cmd += ["pan={}".format(self.params.swing)]
        if self.params.tilt: cmd += ["tilt={}".format(self.params.tilt)]
        if self.params.roll: cmd += ["roll={}".format(self.params.roll)]
        if self.params.zoom: 
            cmd += ["zoom={}".format(self.params.zoom)]
        if cmd == [THREEDROTATE]: #if nothing has been added
            return
        if self.params.planebgcolor and not self.params.planebgimage:
            cmd += ["bgcolor={}".format(self.params.planebgcolor)]
        else:
            cmd += ["bgcolor=none"]
        cmd += ["skycolor={}".format(self.params.skycolor or 'none')]
        if self.params.transition: cmd += ["vp={}".format(self.params.transition)]
        cmd += [ self.filepath, self.filepath ]
        self._call_cmd(cmd)


    def _trim_cmd (self):
        cmd = [BIN_CONVERT, self.filepath, "-trim", "+repage", self.filepath]
        self._call_cmd(cmd)
    
    def _prepare_gridimage(self, image):
        if image['mimetype'] != 'png':
            cmd = [BIN_CONVERT, image['path'], self.filepath]
        else:
            cmd = ['cp', image['path'], self.filepath]
        self._call_cmd(cmd)

    
    def _overlay_planebgimage(self):
        cmd = [ 
            BIN_COMPOSITE,
            "-compose", "Dst_Over", "-gravity", "center", 
            self.params.planebgimage["path"], 
            self.filepath,
            self.filepath
        ]
        self._call_cmd(cmd)
             
    def _cleanup(self):
        if not len(self.files_created):
            return
        cmd = ["rm", "-f"] + self.files_created
        self._call_cmd(cmd)
        
    def create(self):
        if self.params.bgimage:
            self._prepare_gridimage(self.params.bgimage)
            self._grid_command()
        elif self.params.imageinstead:
            self._prepare_gridimage(self.params.imageinstead)
        else:
            self._make_canvas()
            self._grid_command()
        if self.params.shadow: self._shadow_cmd()
        self._threed_rotate_cmd()
        if self.params.planebgimage: self._overlay_planebgimage()
        if self.params.trim: self._trim_cmd() 
        self._cleanup()

if __name__ == "__main__":
    g = Imgrid(**{
      'bgimage' : 'http://i.asdf.us/im/1a/imBreak_1424909483_xx_abridged___.gif',
      'planebgimage' : 'http://i.imgur.com/FICZtph.png',
      'tilt' : '30',
      'spacing' : '30',
      'hlines' : 'true',
      'roll' : '30',
      'shadow' : 'true',
      'trim' : 'true'
    })
    g.create()
    print g.commands