summaryrefslogtreecommitdiff
path: root/im/cgi-bin/imdither.cgi
blob: 29837ed07c97f831283f827993bd36860529b7f0 (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
#!/usr/bin/python

import downloader
import time
import re
import cgi
from subprocess import Popen, PIPE, call
from os import stat, path, makedirs
import sys
import sha
BASE_DIR = ""
OTHER_BASE = ""
#BASE_DIR = "/var/www/asdf.us/httpdocs/im/"
#OTHER_BASE = "http://asdf.us/im/"

print "Content-Type: text/html"
print ""
print ""

NAMETAG = "imDither"

MAIN_DIRECTORY = ""
#BIN_CONVERT = "/usr/bin/convert"
#BIN_IDENTIFY = "/usr/bin/identify"
#BIN_COMPOSITE = "/usr/bin/composite"
BIN_CONVERT = "convert"
BIN_IDENTIFY = "identify"
BIN_COMPOSITE = "composite"

NOW = str(int(time.time()))
MAX_LENGTH_BEFORE_ABRIDGED = 30
ABBREVIATION = "xx_abridged__"

###################################
### DEFAULT VALUES HERE
params = {
  "url" : "http://asdf.us/im/10/friedeggstresstoy_1321140711_1322282769_pepper.gif",
  "ditherType" : "1.png",
  "username" : "pepper",
  "formatType" : "png",
}
###################################

form = cgi.FieldStorage()
if form:
  for key, value in form.iteritems():
    formValues[key] = params[key] #CHECKME

class Utils:
  def file_size (self, imgFile):
    return stat(imgFile)[6]

  def imageDimensions(self, thefile):
    ident = Popen([BIN_IDENTIFY, thefile], stdout=PIPE).communicate()[0]
    parts = ident.split(" ")
    return parts[2].split("x")
  
  def hash_dir(self, s):
    """get a random number-letter pair"""
    return sha.new(s).hexdigest()[:2]
  
  def hexdir(self):
    """create a random path name"""
    directoryName = utils.hash_dir(NOW)
    
    dirs = [ 
      BASE_DIR+directoryName+'/',
      OTHER_BASE+directoryName+'/',
    ]
    ###################################
    if not path.exists(directoryName):
      makedirs(directoryName)


    return dirs
  
  def makeOriginalName(self, params, canvas_type="", nametag_part=""):
    if not nametag_part:
      nametag_part = NAMETAG
    if not canvas_type:
      canvastype = params["formatType"]
    filename = '%s_%s_%s.%s' % (nametag_part, NOW, params["username"], canvas_type)
    return filename

  def sanitize (self,string):
    """strip out all non-word characters"""
    return re.sub(r'\W+', '', string)

  def makeNameFromFilename(self, params):
    parts = params["url"].split("?")[0].split('/')
    filename = parts[-1]
    name, extension  = filename.split('.')
    if len(extension) >= 5:
      sys.stdout.write('the file is not an image or any standard format')
      sys.exit()
    if len(name)> MAX_LENGTH_BEFORE_ABRIDGED:
      name = ABBREVIATION
    sanitized = self.sanitize(name)
    thefilename = "%s_%s_%s_%s.%s" % (NAMETAG, NOW, sanitized, params["username"], extension)
    return thefilename

utils = Utils();


class Dither:
  def makeCanvas(self, thefile):
    call([BIN_CONVERT,"-size", self.dimensions[0]+"x"+self.dimensions[1],"canvas:transparent", thefile])
  def makeMask(self, themask, thedither, thebackground):
    """ composite -tile DITHERNAME BACKGROUNDNAME MASKNAME """
    call([BIN_COMPOSITE,"-tile",thedither,thebackground,themask])
   #convert thebg.gif -compose Dst_In null: thefile.gif -matte -layers composite new.gif
    call([BIN_CONVERT,themask,"-compose","Dst_In","null:",self.privatepath+self.mainfile,"-matte","-layers","composite",themask])
  #  os.system("rm "+thebackground)
  def fuseMask(self, themask, theimage):
    call([BIN_COMPOSITE,theimage,"-compose","Pin_Light",themask,theimage])
  #  os.system("rm "+themask)
  def __init__(self, url, thedither, username):
    self.mainfile = utils.makeNameFromFilename(params)
    filepaths = utils.hexdir()
    self.privatepath = filepaths[0]
    self.publicpath = filepaths[1]
    downloader.download(url, self.mainfile, self.privatepath)

    parts = self.mainfile.split('.')
    print parts
    if "gif" in parts[-1]:
      canvastype = "gif"
    else:
      canvastype = "png"
    
    self.canvasfile = "/tmp/"+utils.makeOriginalName(params, canvastype, "canvasfile")
    self.dimensions = utils.imageDimensions(self.privatepath+self.mainfile)
    self.makeCanvas(self.canvasfile)
    self.theMask = "/tmp/"+utils.makeOriginalName(params, canvastype, "maskfile")
    #good up to here
    self.makeMask(self.theMask, thedither, self.canvasfile)
    self.fuseMask(self.theMask, self.privatepath+self.mainfile)
    #self.mainfile = self.mainfile.replace(, do something with s3)
    print self.privatepath+self.mainfile
    print utils.file_size(self.privatepath+self.mainfile)
    print 'width: '+self.dimensions[0]+'px'
    print 'height: '+self.dimensions[1]+'px'

if __name__ == "__main__":
    newImage = Dither(params["url"], params["ditherType"], params["username"])