Example #1
0
 def get(self):
     self.set_header("Content-Type", "image/jpeg")
     image = Image("../image.jpg")
     image.resize(Geometry(100, 100))
     blob = Blob()
     image.write(blob)
     self.write(blob.data)
    def finish_response(self, app_iter):
        if not self.scale:
            self.start_response(self.status, self.headers)
            self.output = app_iter
            return

        CONTENT_LENGTH.delete(self.headers)
        inBuffer = StringIO()
        try:
            for s in app_iter:
                self.logger.debug("Writing %d bytes into image buffer." % len(s))
                inBuffer.write(s)
        finally:
            if hasattr(app_iter, 'close'):
                app_iter.close()

        rawImg = Blob()
        rawImg.data = inBuffer.getvalue()
        inBuffer.close()
        image = Image(rawImg)
        self.logger.debug("Scaling image to %s" % self.scaled_size)
        image.scale(self.scaled_size[0])
        image.write(self.outbuffer)

        content_length = self.outbuffer.length()
        CONTENT_LENGTH.update(self.headers, content_length)
        CACHE_CONTROL.update(self.headers, s_maxage=CACHE_CONTROL.ONE_HOUR)
        self.start_response(self.status, self.headers)
Example #3
0
    def guardar_img(self, widget, string, img):
        filechooser = gtk.FileChooserDialog("Guardar Imagen", None, gtk.FILE_CHOOSER_ACTION_SAVE,
                                            (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_SAVE, gtk.RESPONSE_OK))
        filechooser.set_default_response(gtk.RESPONSE_OK)
        filechooser.set_current_name(img.split("/")[3])
        filter = gtk.FileFilter()
        filter.set_name("Todos los archivos")
        filter.add_pattern("*")
        filechooser.add_filter(filter)
        filter = gtk.FileFilter()
        filter.set_name("Imágenes")
        filter.add_mime_type("image/png")
        filter.add_mime_type("image/jpeg")
        filter.add_mime_type("image/gif")
        filter.add_pattern("*.png")
        filter.add_pattern("*.jpg")
        filter.add_pattern("*.gif")
        filter.add_pattern("*.tif")
        filter.add_pattern("*.xpm")
        filechooser.add_filter(filter)

        respuesta = filechooser.run()

        if respuesta == gtk.RESPONSE_OK:
            try:
                fimg = Image(img)
                fimg.write(filechooser.get_filename())
                filechooser.destroy()
            except:
                pass
        else:
            filechooser.destroy()
Example #4
0
    def _CropGeometry(self, geometry):
        if not self._map_image:
            self._GenerateImage()

        image = Image(self._map_image)
        image.crop(geometry)

        return image
Example #5
0
    def thumbnail(self, infile, outfile, size, quality, no_upscale=False):
        #image = Image(infile)
        #image.resize(size)
        #image.write(outfile)

        quality = str(quality)
        if infile.endswith('.gif') or no_upscale:
            size = size+'>'
        resize = run(['/usr/bin/convert', '-interlace', "Plane", '-quality', quality, '-strip',  '-thumbnail', size, infile, outfile])
        image = Image(outfile)

        return { 'width': image.size().width(), \
                 'height': image.size().height() }
 def manipula_img(self, img_r, nmsuc):
     """Procesa la imagen adquirida en formato xwd y la trasforma en jpg"""
     image_final = self.dir_tmp + nmsuc + ".jpg"
     contador = 0
     if path.exists(image_final):
         contador += 1
         image_final = self.dir_tmp + nmsuc + "_" + str(contador) + ".jpg"
         if path.exists(image_final):
             image_final = self.comprueba_nombre(image_final, nmsuc)
     img = Image(img_r)
     img.scale("1024x768")
     img.write(image_final)
     exe(image_final, nmsuc)
Example #7
0
    def thumb(self, req):
        if self.mime_type.startswith('image') \
                and guess_extension(self.mime_type) in _image_exts:

            file_path = req.cfg.attachments_path + '/' + self.webname()
            img = Image(file_path.encode('utf-8'))

            width, height = req.cfg.attachments_thumb_size.get()
            img.scale(Geometry(width, height))

            thumb_path = req.cfg.attachments_thumb_path + '/' + self.webname()
            if not exists(dirname(thumb_path)):
                makedirs(dirname(thumb_path))
            img.write(thumb_path.encode('utf-8'))
Example #8
0
    def _ps2png(self, filename, relative):
        "Try to converts bands.ps -> bands.png and returns absolute filename"
        try:
            pspath  = self.bandsPS()
            pngpath = os.path.join(self._resultPath.localPath(), PNGBAND)   # Absolute

            # Rotate 90 degrees and convert .ps -> .png
            from PythonMagick import Image
            img     = Image(pspath)
            img.rotate(90)          # For some reason plotband.x rotates image
            img.write(pngpath)      # Write to .png file

            fpngpath = os.path.join(self._resultPath.localPath(relative), PNGBAND) # Format dependent
            return fpngpath         # If success, return path to .png file
        except:
            return None
Example #9
0
def main():
    # os.environ["MAGICK_HOME"] = r"path_to_ImageMagick"

    if len(sys.argv) == 1:
        dirpath = '.'
    else:
        dirpath = sys.argv[1]

    temp_dir = os.path.join(dirpath, '.temp')
    if not os.path.exists(temp_dir):
        os.mkdir(temp_dir)

    for file_name in os.listdir(dirpath):
        if not os.path.isfile(file_name) or not file_name.endswith('.pdf'):
            continue
        print('Converting file {} ...'.format(file_name))
        in_path = os.path.join(dirpath, file_name)
        with open(in_path, 'rb') as handle:
            inputpdf = PdfFileReader(handle)
            for i in xrange(inputpdf.numPages):
                outputpdf = PdfFileWriter()
                outputpdf.addPage(inputpdf.getPage(i))
                new_file_name = file_name.replace('.pdf', '') + '_{}.pdf'.format(i)
                new_in_path = os.path.join(temp_dir, new_file_name)
                with open(new_in_path, 'wb') as handle:
                    outputpdf.write(handle)

                output_file_name = new_file_name.replace('.pdf', '.jpeg')
                output_path = os.path.join(dirpath, output_file_name)
                p = Image()
                p.density('1080')
                p.read(os.path.abspath(new_in_path))
                p.write(os.path.abspath(output_path))
                os.remove(new_in_path)
        os.rmdir(temp_dir)
 def bmp_or_jpg_to_pdf(list_of_file_paths, destination_directory, delete_source=False):
     operation_result = {}
     invalid_file_paths = []
     for files in list_of_file_paths:
         if os.path.exists(files):
             continue
         else:
             invalid_file_paths.append(files)
             list_of_file_paths.remove(files)
     for files in list_of_file_paths:
         image = PyImage()
         image.density("600")
         image.read(files)
         file_name = os.path.basename(files)
         name, ext = os.path.splitext(file_name)
         file_name_at_destination = os.path.join(destination_directory, name + ".pdf")
         image.write(file_name_at_destination)
     if delete_source is True:
         for files in list_of_file_paths:
             os.remove(files)
     if not invalid_file_paths:
         operation_result.update({"code": 0, "invalid_file_paths": "None"})
     else:
         invalid_files = ",".join(list_of_file_paths)
         operation_result.update({"code": 1, "invalid_file_paths": invalid_files})
     return operation_result
Example #11
0
    def __init__(self, filename, i):
        self.image = Image()
        self.image.density('%d' % DENSITY)
        self.image.read('%s[%d]' % (filename, i))

        temp = tempfile.NamedTemporaryFile(suffix='.png')
        self.image.write(temp.name)
        self.pimage = pygame.image.load(temp.name)
        temp.close()
Example #12
0
def EncodeImg(Ii,pathin,pathout):
	""" fonction qui encode un png en base64 
	Ii : l'element xml ou il faut la brancher
	pathin et pathout les chemins des fichiers """
 	print Ii.attrib
	ext=Ii.attrib['ext']	
	img_name  = Ii.attrib['name']
 	pathF=Ii.attrib['pathF'] +'/'
	
	# si ce n'est pas du png on converti en png
	if (Ii.attrib['ext'] != 'png'):
		im = Image(pathF+ img_name +'.' + ext)
		img_name = img_name + ".png"
		im.write(pathF + img_name)
	else:
            img_name  = Ii.attrib['name']+'.'+ext
      
	img_file = open(	pathF + img_name, "rb") 
	Ii.attrib.update({'name':img_name,'path':'/','encoding':"base64"})
	Ii.text=base64.b64encode(img_file.read())     
    def convert_images_to_tiff(list_of_file_paths, destination_directory, delete_source=False):
        """
        This static method deals with converting images of type .bmp, .jpg, .png to .tiff.
        This method takes parameters they are as follows:
        :param list_of_file_paths: Example: ['C:\Users\gpatil\Desktop\image1.png', 'C:\Users\gpatilSample\image2.png']
        :param destination_directory: The directory where the converted images are to be saved
        :param delete_source: If the delete_source param is set to True then the original files will get erased after
               the conversion is completed
        :return: returns a dictionary containing the invalid file paths passed to the method (if any) and a result_code
                 that has the value 0 or 1 based on the success and failure of the operation
        """
        result_dictionary = {}
        invalid_files_list = []
        for paths in list_of_file_paths:
            if os.path.exists(paths) is False:
                invalid_files_list.append(paths)
                continue
            image_object = Image(paths)
            file_name = os.path.basename(paths)
            name, ext = os.path.splitext(file_name)
            print "Converting Image " + str(file_name) + " to TIFF"
            image_object.write(os.path.join(destination_directory, name + ".tiff"))
            print "Conversion Complete"
        if not invalid_files_list:
            result_dictionary.update({"result_code": 0, "invalid_file_paths": "None"})
        else:
            csv_list_of_invalid_file_paths = ",".join(invalid_files_list)
            result_dictionary.update({"result_code": -1, "invalid_file_paths": csv_list_of_invalid_file_paths})
            print "Following files at paths could not be converted"
            for files in invalid_files_list:
                print files

        if delete_source is True:
            for paths in list_of_file_paths:
                if os.path.exists(paths) is False:
                    invalid_files_list.append(paths)
                    continue
                os.remove(paths)
            print "Legacy files deleted successfully"
        return result_dictionary
 def compress_tiff_files(list_of_file_paths, destination_directory, delete_source=False):
     """
     This method deals with compression of TIFF images. ZipCompression algorithm is used from the PythonMagick
     library.
     :param list_of_file_paths: ['C:\Users\gpatil\Desktop\image1.tiff', 'C:\Users\gpatilSample\image2.tiff']
     :param destination_directory: 'C:\Users\gpatil\Desktop\image1.png'
     :param delete_source: If the delete_source param is set to True then the original files will get
            erased after they are compressed
     :return: returns a dictionary containing the invalid file paths passed to the method (if any) and a result_code
              that has the value 0 or 1 based on the success and failure of the operation
     """
     result_dictionary = {}
     invalid_files_list = []
     for paths in list_of_file_paths:
         if os.path.exists(paths) is False:
             invalid_files_list.append(paths)
             continue
         image_object = Image(paths)
         image_object.compressType(CompressionType.ZipCompression)
         file_name = os.path.basename(paths)
         print "Compressing Image" + str(file_name) + " to TIFF"
         image_object.write(os.path.join(destination_directory, file_name))
         print "Compression Complete"
     if not invalid_files_list:
         result_dictionary.update({"result_code": 0, "invalid_file_paths": "None"})
     else:
         csv_list_of_invalid_file_paths = ",".join(invalid_files_list)
         result_dictionary.update({"result_code": -1, "invalid_file_paths": csv_list_of_invalid_file_paths})
         print "Following files at paths could not be compressed"
         for files in invalid_files_list:
             print files
     if delete_source is True:
         for files in list_of_file_paths:
             if os.path.exists(paths) is False:
                 invalid_files_list.append(paths)
                 continue
             os.remove(files)
             print "Legacy files deleted successfully"
     return result_dictionary
Example #15
0
def rsr2png(rsrfile):
	rsr2pct(rsrfile)
	pictfile = os.path.splitext(rsrfile)[0]+".pct"
	try:
		thumb = Image(str(pictfile))
	except:
		print pictfile
		raise
	thumb.opacity(100)
	thumb.scale(91,91)
	thumb.write(str(os.path.splitext(rsrfile)[0]+".png"))
Example #16
0
    def convert_photo_to_jpeg(photo_path):
        print 'Converting %s to JPEG...' % (photo_path,)
        image = Image(photo_path)
        image.magick("jpeg")
        image.quality(100)
        (_, file_name) = os.path.split(photo_path)
        file_name = convert_local_filename_to_flickr(file_name)
        file_name = os.path.join(tempfile.mkdtemp('.flickrsmartsync'), file_name)
        image.write(file_name)

        print 'Done converting photo!'
        return file_name
Example #17
0
    def resize(self, req, width, height):
        file_path = req.cfg.attachments_path + '/' + self.webname()
        if self.mime_type.startswith('image') \
                and guess_extension(self.mime_type) in _image_exts:

            img = Image(file_path.encode('utf-8'))
            img.fileName(
                'image.'+self.file_name.encode('utf-8').split('.')[-1])
            size = img.size()

            blob = Blob()
            if width > size.width() and height > size.height():
                img.write(blob)
            else:
                img.scale(Geometry(width, height))
                img.write(blob)
            return blob.data
        elif guess_extension(self.mime_type) == '.svg':
            with open(file_path.encode('utf-8'), 'rb') as svg:
                return svg.read()
        else:
            req.log_error(self.mime_type)
            return None
Example #18
0
def pdf2jpg(pdf,temp):
    #Generate the path for the jpg file. Need to use a temp directory in case
    #pdf location is read only.
    pdf = str(pdf)
    base = os.path.basename(pdf)
    basefile = os.path.splitext(base)
    jpg = temp + basefile[0] + ".jpg"
    #jpg = str(jpg.replace("\\","\\\\"))
    jpg = str(jpg)
    pdf = str(pdf)
    img = PMImage()
    img.density('300')
    img.depth(24)
    img.read(pdf)
    img.write(jpg)    
    img = Image.open(jpg)
    rgbimg = Image.new("RGBA", img.size)
    rgbimg.paste(img)
    rgbimg.save(jpg)
    return jpg
Example #19
0
def convertMGtoPIL(magickimage):
    'works with grayscale and color'
    img = PMImage(magickimage)  # make copy
    img.depth = 8        #  this takes 0.04 sec. for 640x480 image
    img.magick = "RGB"
    w, h = img.columns(), img.rows()
    blb=Blob()
    img.write(blb)
    data = blb.data
    
    # convert string array to an RGB Pil image
    pilimage = Image.fromstring('RGB', (w, h), data)
    return pilimage
	def process_image_file(self, image_path):
		'''Given an image path it reduces each image in size to new_image_size
		and then transforms it to a 1D list and to an nparray

		Args:
		  image_path (str): path to current image.

		Returns:
		  list of ints (8bit): feature vector if success, None if not.
		'''
		try:
			img = Image.open(image_path)
			img = img.resize(self.new_image_size)
			img = list(img.getdata())
			img = np.array(img)
		except IOError:
			return None
		return img
Example #21
0
class Answers:
    def __init__(self, filename, i):
        self.image = Image()
        self.image.density('%d' % DENSITY)
        self.image.read('%s[%d]' % (filename, i))

        temp = tempfile.NamedTemporaryFile(suffix='.png')
        self.image.write(temp.name)
        self.pimage = pygame.image.load(temp.name)
        temp.close()

    def draw(self, screen, C):
        pygame.draw.rect(screen, (255, 255, 255), (0, 0, W, H), 0)

        scaled = self.pimage
        screen.blit(scaled, (0, 0), (C[0], C[1], C[2] - C[0], C[3] - C[1]))
        pygame.display.flip()
Example #22
0
def pdftojpg(fname):
    reader = PdfFileReader(open(fname, "rb"))
    directory = os.path.basename(fname)
    if not os.path.exists(directory):
        os.makedirs(directory)
    else:
        shutil.rmtree(directory)
        time.sleep(2)
        os.makedirs(directory)
    for page_num in range(reader.getNumPages()):
        writer = PdfFileWriter()
        writer.addPage(reader.getPage(page_num))
        temp = NamedTemporaryFile(prefix=str(page_num), suffix=".pdf", delete=False)
        writer.write(temp)
        temp.close()

        im = Magick_Image()
        im.density("300") # DPI, for better quality
        im.read(temp.name)
        im.write(directory+"/some%d.jpg" % (int(page_num)+1))

        os.remove(temp.name)
    return(directory)
Example #23
0
#Fails 234.py
#Autors: Artis Erglis

from PythonMagick import Image

# Izgatavojam jaunu objektu - bilde
bilde = Image("16x16", "#A96969")

# Izgatavojam mainiigos x un y
x=y=0

for a in range(0,5):
    bilde.pixelColor(a,8,"#4C3AB6")
for a in range(11,16):
    bilde.pixelColor(a,8,"#4C3AB6")
for a in range(6,11):
    bilde.pixelColor(5,a,"#F9F113")
for a in range(6,11):
    bilde.pixelColor(11,a,"#F9F113")
for a in range(5,12):
    bilde.pixelColor(a,6,"#F9F113")
for a in range(5,12):
    bilde.pixelColor(a,11,"#F9F113")

# 3x3 pixels palielina liidz 200x200
bilde.scale("200x200")

# Objektu 'bilde' ieraksta failaa
bilde.write("234.png")
Example #24
0
#!/usr/bin/python
import numpy
from PythonMagick import Image

bilde = Image("400x400","#22aaff")

for j in range(1,400):
  for k in range(1,400):
      if (j**2+k**2>400**2):
        bilde.pixelColor(j, k, "#FFF")

bilde.write("circle.png")
  
Example #25
0
# Fails 239.py
# Autors: Artis Erglis

from PythonMagick import Image

# Izgatavojam jaunu objektu - bilde
bilde=Image("9x9", "#E65555")

# Izgatavojam mainiigos x un y
x=y=0

bilde.pixelColor(2,3,'#55E666' )
bilde.pixelColor(3,2,'#55E666' )
bilde.pixelColor(4,1,'#55E666' )
bilde.pixelColor(5,2,'#55E666' )
bilde.pixelColor(6,3,'#55E666' )
bilde.pixelColor(2,5,'#55E666' )
bilde.pixelColor(3,4,'#55E666' )
bilde.pixelColor(4,3,'#55E666' )
bilde.pixelColor(5,4,'#55E666' )
bilde.pixelColor(6,5,'#55E666' )
for i in range(2,7):
    bilde.pixelColor(i,0,'#55E666')
for i in range(3,6):
    bilde.pixelColor(i,7,'#55E666')
for i in range(2,5):
    bilde.pixelColor(8,i,'#55E666')
for i in range(2,5):
    bilde.pixelColor(0,i,'#55E666')
for i in range(5,7):
    bilde.pixelColor(i/3,i,'#55E666')
Example #26
0
 def _read(self):
     '''Read the image.
     '''
     LOGGER.info("Reading image %s.", self.fname)
     self.img = PMImage(self.fname)
Example #27
0
from PythonMagick import Image
bilde = Image("16x16", "#00FFFF")
x=y=0
for a in range(0,5):
    bilde.pixelColor(a,8,"#FFFF00")
for a in range(11,16):
    bilde.pixelColor(a,8,"#FFFF00")
for a in range(6,11):
    bilde.pixelColor(5,a,"#FF0000")
for a in range(6,11):
    bilde.pixelColor(11,a,"#FF0000")
for a in range(5,12):
    bilde.pixelColor(a,6,"#FF0000")
for a in range(5,12):
    bilde.pixelColor(a,11,"#FF0000")
bilde.scale("200x200")
bilde.write("234.png")
Example #28
0
from PythonMagick import Image
photo=Image("9x9", "#E65C00")
x=y=0
for i in range(1,7):
    photo.pixelColor(4,i,'#0404B4')
for i in range(3,6):
    photo.pixelColor(i,2,'#0404B4')
for i in range(2,7):
    photo.pixelColor(i,3,'#0404B4')
for i in range(2,7):
    photo.pixelColor(i,0,'#0404B4')
for i in range(3,6):
    photo.pixelColor(i,7,'#0404B4')
for i in range(2,5):
    photo.pixelColor(8,i,'#0404B4')
for i in range(2,5):
    photo.pixelColor(0,i,'#0404B4')
for i in range(5,7):
    photo.pixelColor(i/3,i,'#0404B4')
photo.pixelColor(1,1, '#0404B4')
photo.pixelColor(7,1, '#0404B4')
photo.pixelColor(7,5, '#0404B4')
photo.pixelColor(6,6, '#0404B4')

photo.scale("200x200")
photo.write("238.png")
Example #29
0
import os

from PyPDF4 import PdfFileReader, PdfFileWriter
from tempfile import NamedTemporaryFile
from PythonMagick import Image

reader = PdfFileReader(open("D:/data/pdf-scan/普通生物学(清晰PDF版).pdf", "rb"))
for page_num in range(reader.getNumPages()):
    writer = PdfFileWriter()
    writer.addPage(reader.getPage(page_num))
    temp = NamedTemporaryFile(prefix=str(page_num), suffix=".pdf", delete=False)
    writer.write(temp)
    print(temp.name)
    tempname = temp.name
    temp.close()
    im = Image(tempname)
    im.quality(100)  # 0-100 full compression
    # 不保持比例
    #im.sample('298x412!')
    # 保持比例
    im.sample('1788x2526')
    #im.density("3000") # DPI, for better quality
    # im.read(tempname)
    im.write("D:/data/pdf-scan/temp-pdf/{}.jpeg".format(page_num))

    os.remove(tempname)
Example #30
0
def to_imagemagick(img, bits=16):
    '''Convert numpy array to Imagemagick format.

    :param img: image to convert
    :type img: Numpy ndarray
    :rtype: PythonMagick.Image
    '''

    if not isinstance(img, PMImage):

        img = _scale(img, bits=bits)

        LOGGER.debug("Converting from Numpy to ImageMagick.")
        out_img = PMImage()
        if img.dtype == np.uint8:
            out_img.depth(8)
        else:
            out_img.depth(16)

        shape = img.shape
        # Convert also B&W images to 3-channel arrays
        if len(shape) == 2:
            tmp = np.empty((shape[0], shape[1], 3), dtype=img.dtype)
            tmp[:, :, 0] = img
            tmp[:, :, 1] = img
            tmp[:, :, 2] = img
            img = tmp
        out_img.magick('RGB')
        out_img.size(str(shape[1])+'x'+str(shape[0]))
        blob = Blob()
        blob.data = img.tostring()

        out_img.read(blob)
        out_img.magick('PNG')

        return out_img
    return img
Example #31
0
from PythonMagick import Image
photo = Image("9x9", "#E65C00")
x = y = 0
for i in range(1, 7):
    photo.pixelColor(4, i, '#0404B4')
for i in range(3, 6):
    photo.pixelColor(i, 2, '#0404B4')
for i in range(2, 7):
    photo.pixelColor(i, 3, '#0404B4')
for i in range(2, 7):
    photo.pixelColor(i, 0, '#0404B4')
for i in range(3, 6):
    photo.pixelColor(i, 7, '#0404B4')
for i in range(2, 5):
    photo.pixelColor(8, i, '#0404B4')
for i in range(2, 5):
    photo.pixelColor(0, i, '#0404B4')
for i in range(5, 7):
    photo.pixelColor(i / 3, i, '#0404B4')
photo.pixelColor(1, 1, '#0404B4')
photo.pixelColor(7, 1, '#0404B4')
photo.pixelColor(7, 5, '#0404B4')
photo.pixelColor(6, 6, '#0404B4')

photo.scale("200x200")
photo.write("238.png")
def walk_menu(entry):
    if isinstance(entry, xdg.Menu.Menu) and entry.Show is True:
        map(walk_menu, entry.getEntries())
    elif isinstance(entry, xdg.Menu.MenuEntry) and entry.Show is True:
        # byte 1 signals another entry
        conn.sendall('\x01')
        img_path = icon_attr(entry.DesktopEntry).encode('utf-8')
        if img_path and os.path.isfile(img_path):
            try:
                # Create an empty image and set the background color to
                # transparent. This is important to have transparent background
                # when converting from SVG
                img = Image()
                img.backgroundColor(Color(0, 0, 0, 0xffff))
                img.read(img_path)
                # scale the image to 48x48 pixels
                img.scale(Geometry(48, 48))
                # ensure the image is converted to ICO
                img.magick('ICO')
                b = Blob()
                img.write(b)
                # icon length plus data
                conn.sendall(struct.pack('i', len(b.data)))
                conn.sendall(b.data)
            except Exception:
                conn.sendall(struct.pack('i', 0))
        else:
            conn.sendall(struct.pack('i', 0))

        name = entry.DesktopEntry.getName()
        # name length plus data
        conn.sendall(struct.pack('i', len(name)))
        conn.sendall(name)

        command = re.sub(' -caption "%c"| -caption %c',
                ' -caption "%s"' % name, entry.DesktopEntry.getExec())
        command = re.sub(' [^ ]*%[fFuUdDnNickvm]', '', command)
        if entry.DesktopEntry.getTerminal():
                command = 'xterm -title "%s" -e %s' % (name, command)

        # command length plus data
        conn.sendall(struct.pack('i', len(command)))
        conn.sendall(command)
Example #33
0
#Fails 231.py
#Autors Reinis Prockans

from PythonMagick import Image

#Izgatavojam jaunu objektu - bilde
#Objekta izmers 3x3 pixels
bilde = Image("32x32", "#22aaff")

#Izgatavojam mainigos x un y
x = y = 0

#Uzstada objekta 'bilde' x,y pixela krasu
bilde.pixelColor(1, 13, "#eeff22")
bilde.pixelColor(1, 14, "#eeff22")
bilde.pixelColor(1, 15, "#eeff22")
bilde.pixelColor(1, 16, "#eeff22")
bilde.pixelColor(1, 17, "#eeff22")
bilde.pixelColor(1, 18, "#eeff22")
bilde.pixelColor(1, 19, "#eeff22")
bilde.pixelColor(1, 20, "#eeff22")
bilde.pixelColor(2, 13, "#eeff22")
bilde.pixelColor(3, 13, "#eeff22")
bilde.pixelColor(4, 13, "#eeff22")
bilde.pixelColor(5, 13, "#eeff22")
bilde.pixelColor(5, 14, "#eeff22")
bilde.pixelColor(5, 15, "#eeff22")
bilde.pixelColor(5, 16, "#eeff22")
bilde.pixelColor(4, 16, "#eeff22")
bilde.pixelColor(3, 16, "#eeff22")
bilde.pixelColor(2, 16, "#eeff22")
Example #34
0
def pdf2img(input_pdf, postfix='.png'):
    img = Image(input_pdf)
    img.density('300')
    size = "%sx%s" % (img.columns(), img.rows())
    output_img = Image(size, bgcolor)
    output_img.type = img.type
    output_img.composite(img, 0, 0,
                         PythonMagick.CompositeOperator.SrcOverCompositeOp)
    output_img.resize(str(img.rows()))
    output_img.magick('JPG')
    output_img.quality(75)
    output_jpg = input_pdf.replace(".pdf", postfix)
    if os.path.exists(output_jpg):
        os.remove(output_jpg)
    output_img.write(output_jpg)
Example #35
0
    def handle(self, *args, **options):
        routes = glob(options['input'] + '/routes-*.json')
        routes = sorted(
            routes, lambda x, y: cmp(
                stat(path.abspath(x))[8],
                stat(path.abspath(y))[8]))

        segment = 0
        img = None
        for route in routes:
            self.stdout.write('Opening route "%s"\n' % route)
            rfile = open(route, 'r')
            fc = json.load(rfile)
            rfile.close()

            if segment == 0:
                self.stdout.write('Creating image file.\n')
                img = Image('1280x720', 'white')
                img.draw(DrawableStrokeColor('black'))
                img.draw(DrawableStrokeOpacity(0.01))
                img.draw(DrawableStrokeWidth(1.0))

            for i, feature in enumerate(fc['features']):
                coords = feature['geometry']['coordinates']
                coords = map(lambda x: self.proj(x), coords)
                for start, end in zip(coords[0:-1], coords[1:]):
                    img.draw(DrawableLine(start[0], start[1], end[0], end[1]))

            segment += 1

            if segment == options['number']:
                self.stdout.write('Writing image file "%s.png".\n' % route)
                img.write(route + '.png')
                segment = 0
Example #36
0
class Image(object):
    '''Class for handling images.

    :param img: array holding image data
    :type img: ndarray or None
    :param fname: image filename
    :type fname: str or None
    :param enhancements: image processing applied to the image
    :type enhancements: dictionary or None
    :param nprocs: number or parallel processes
    :type nprocs: int
    '''

    def __init__(self, img=None, fname=None, enhancements=None,
                 nprocs=1):
        self.img = img
        self.fname = fname
        self._nprocs = nprocs

        self._pool = None

        if fname is not None:
            self._read()
        if enhancements:
            LOGGER.info("Preprocessing image.")
            self.enhance(enhancements)
        self.shape = None
        self._to_numpy()

    def __add__(self, img):
        self._to_numpy()
        if isinstance(img, Image):
            img.to_numpy()
            return Image(img=self.img+img.img, nprocs=self._nprocs)
        else:
            # Assume a numpy array or scalar
            return Image(img=self.img+img, nprocs=self._nprocs)

    def __radd__(self, img):
        return self.__add__(img)

    def __sub__(self, img):
        self._to_numpy()
        if isinstance(img, Image):
            img.to_numpy()
            return Image(img=self.img-img.img, nprocs=self._nprocs)
        else:
            # Assume a numpy array or scalar
            return Image(img=self.img-img, nprocs=self._nprocs)

    def __rsub__(self, img):
        return self.__sub__(img)

    def __isub__(self, img):
        self.img = self.__sub__(img)

    def __mul__(self, img):
        self._to_numpy()
        if isinstance(img, Image):
            img.to_numpy()
            return Image(img=self.img*img.img, nprocs=self._nprocs)
        else:
            # Assume a numpy array or scalar
            return Image(img=self.img*img, nprocs=self._nprocs)

    def __rmul__(self, img):
        return self.__mul__(img)

    def __div__(self, img):
        self._to_numpy()
        if isinstance(img, Image):
            self._to_numpy()
            img.to_numpy()
            return Image(img=self.img/img.img, nprocs=self._nprocs)
        else:
            # Assume a numpy array or scalar
            return Image(img=self.img/img, nprocs=self._nprocs)

    def __abs__(self):
        self._to_numpy()
        return Image(img=np.abs(self.img), nprocs=self._nprocs)

    def __lt__(self, img):
        self._to_numpy()
        if isinstance(img, Image):
            img.to_numpy()
            img = img.img
        return self.img < img

    def __le__(self, img):
        self._to_numpy()
        if isinstance(img, Image):
            img.to_numpy()
            img = img.img
        return self.img <= img

    def __gt__(self, img):
        self._to_numpy()
        if isinstance(img, Image):
            img.to_numpy()
            img = img.img
        return self.img > img

    def __ge__(self, img):
        self._to_numpy()
        if isinstance(img, Image):
            img.to_numpy()
            img = img.img
        return self.img >= img

    def __eq__(self, img):
        self._to_numpy()
        if isinstance(img, Image):
            img.to_numpy()
            img = img.img
        return self.img == img

    def __getitem__(self, idx):
        self._to_numpy()
        return self.img[idx]

    def __setitem__(self, idx, val):
        self._to_numpy()
        self.img[idx] = val

    def _read(self):
        '''Read the image.
        '''
        LOGGER.info("Reading image %s.", self.fname)
        self.img = PMImage(self.fname)

    def set_dtype(self, dtype):
        '''Set image data dtype.

        :param dtype: Convert to this Numpy dtype
        :type dtype: Numpy dtype
        '''
        self._to_numpy()
        LOGGER.debug('Changing dtype from %s to %s.',
                     self.img.dtype, str(dtype))
        self.img = self.img.astype(dtype)

    def to_numpy(self):
        '''Convert from PMImage to Numpy ndarray.
        '''
        self._to_numpy()

    def _to_numpy(self):
        '''Convert from PMImage to numpy.
        '''
        if isinstance(self.img, PMImage):
            self.img = to_numpy(self.img)
            self.shape = self.img.shape

    def _to_imagemagick(self, bits=16):
        '''Convert from numpy to PMImage.
        '''
        self.img = to_imagemagick(self.img, bits=bits)

    def save(self, fname, bits=16, enhancements=None):
        '''Save the image data.

        :param fname: output filename
        :type fname: str
        :param bits: output bit-depth
        :type bits: int
        :param enhancements: image processing applied to the image before saving
        :type enhancements: dictionary or None
        '''

        if enhancements:
            LOGGER.info("Postprocessing output image.")
            self.enhance(enhancements)
        self._to_imagemagick(bits=bits)
        LOGGER.info("Saving %s.", fname)
        self.img.write(fname)

    def min(self):
        '''Return the minimum value in the image.

        :rtype: float
        '''
        self._to_numpy()
        return np.min(self.img)

    def max(self):
        '''Return the maximum value in the image.

        :rtype: float
        '''
        self._to_numpy()
        return np.max(self.img)

    def luminance(self):
        '''Return luminance (channel average) as Numpy ndarray.

        :rtype: Numpy ndarray
        '''
        self._to_numpy()
        if len(self.img.shape) == 3:
            return Image(img=np.mean(self.img, 2), nprocs=self._nprocs)
        else:
            return Image(img=self.img, nprocs=self._nprocs)

    def enhance(self, enhancements):
        '''Enhance the image with the given function(s) and argument(s).

        :param enhancements: image processing methods
        :type enhancements: dictionary

        Available image processing methods:

        * ``br``: Blue - Red

          * possible calls:

            * ``{'br': None}``
            * ``{'br': float}``

          * optional arguments:

            * ``float``: multiplier for blue channel [``mean(red/green)``]

        * ``gr``: Green - Red

          * possible calls:

            * ``{'gr': None}``
            * ``{'gr': float}``

          * optional arguments:

            * ``float``: multiplier for red channel [``mean(green/red)``]

        * ``bg``: Blue - Green

          * possible calls:

            * ``{'bg': None}``
            * ``{'bg': float}``

          * optional arguments:

            * ``float``: multiplier for blue channel [``mean(blue/green)``]

        * ``emboss``: emboss image using *ImageMagick*

          * possible calls:

            * ``{'emboss': None}``
            * ``{'emboss': float}``
            * ``{'emboss': [float, float]}``

          * optional arguments:

            * ``float``: light source azimuth in degrees [``90``]
            * ``float``: light source elevation in degrees [``45``]

        * ``gamma``: gamma correction

          * possible calls:

            * ``{'gamma': float}``

          * required arguments:

            * ``float``: gamma value

        * ``gradient``: remove image gradient

          * possible calls:

            * ``{'gradient': None}``
            * ``{'gradient': float}``

          * optional arguments:

            * ``float`` (blur radius) [``min(image dimensions)/20``]

        * ``rgb_sub``: Subtract luminance from each color channel

          * possible calls:

            ``{'rgb_sub': None}``

        * ``rgb_mix``: Subtract luminance from each color channel and mix it
          back to the original image

          * possible calls:

            ``{'rgb_mix': None}``
            ``{'rgb_mix': float}``

          * optional arguments:

            * ``float``: mixing ratio [``0.7``]

        * ``stretch``: linear histogram stretch

          * possible calls:

            * ``{'stretch': None}``
            * ``{'stretch': float}``
            * ``{'stretch': [float, float]}``

          * optional arguments:

            * ``float``: low cut threshold [``0.01``]
            * ``float``: high cut threshold [``1 - <low cut threshold>``]

        * ``usm``: unsharp mask using *ImageMagick*

          * possible calls:

            * ``{'usm': [float, float]}``
            * ``{'usm': [float, float, float]}``
            * ``{'usm': [float, float, float, float]}``

          * required arguments:

            * ``float``: radius
            * ``float``: amount

          * optional arguments:

            * ``float``: standard deviation of the gaussian [``sqrt(radius)``]
            * ``float``: threshold [``0``]

        '''

        functions = {'usm': self._usm,
                     'emboss': self._emboss,
                     'blur': self._blur,
                     'gamma': self._gamma,
                     'br': self._blue_red_subtract,
                     'gr': self._green_red_subtract,
                     'bg': self._blue_green_subtract,
                     'rgb_sub': self._rgb_subtract,
                     'rgb_mix': self._rgb_mix,
                     'gradient': self._remove_gradient,
                     'stretch': self._stretch}

        for key in enhancements:
            LOGGER.info("Apply \"%s\".", key)
            func = functions[key]
            func(enhancements[key])

    def _channel_difference(self, chan1, chan2, multiplier=None):
        '''Calculate channel difference: chan1 * multiplier - chan2.
        '''
        self._to_numpy()
        chan1 = self.img[:, :, chan1].copy()
        chan2 = self.img[:, :, chan2].copy()
        if multiplier is None:
            idxs = np.logical_and(np.logical_and(1.5*chan1 < chan2,
                                                 2.5*chan1 > chan2),
                                  chan1 > 0)
            if np.all(np.invert(idxs)):
                multiplier = 2
            else:
                multiplier = np.mean(chan2[idxs]/chan1[idxs])
        else:
            if isinstance(multiplier, list):
                multiplier = multiplier[0]
        LOGGER.debug("Multiplier: %.3lf", multiplier)
        self.img = multiplier * chan1 - chan2


    def _blue_red_subtract(self, args):
        '''Subtract red channel from the blue channel after scaling
        the blue channel using the supplied multiplier.
        '''
        LOGGER.debug("Calculating channel difference, Blue - Red.")
        self._channel_difference(2, 0, multiplier=args)

    def _green_red_subtract(self, args):
        '''Subtract red channel from the green channel after scaling
        the green channel using the supplied multiplier.
        '''
        LOGGER.debug("Calculating channel difference, Green - Red.")
        self._channel_difference(1, 0, multiplier=args)

    def _blue_green_subtract(self, args):
        '''Subtract green channel from the blue channel after scaling
        the green channel using the supplied multiplier.
        '''
        LOGGER.debug("Calculating channel difference, Blue - Green.")
        self._channel_difference(2, 1, multiplier=args)

    def _rgb_subtract(self, args):
        '''Subtract mean(r,g,b) from all the channels.
        '''
        LOGGER.debug("Subtracting luminance from color channels.")
        del args
        self._to_numpy()
        luminance = self.luminance().img
        for i in range(3):
            self.img[:, :, i] -= luminance
        self.img -= self.img.min()


    def _rgb_mix(self, args):
        '''Subtract mean(r,g,b) from all the channels, and blend it
        back to the original image.

        :param args: mixing factor [0.7]
        :type args: float
        '''

        if args is None:
            args = 0.7
        else:
            args = args[0]

        LOGGER.debug("Mixing factor: %.2lf", args)
        self._to_numpy()
        img = Image(img=self.img.copy(), nprocs=self._nprocs)
        img.enhance({'rgb_sub': None})

        self.img *= (1-args)
        self.img += args * img.img


    def _stretch(self, args):
        '''Apply a linear stretch to the image.
        '''

        self._to_numpy()
        self.img -= self.img.min()

        if args is None:
            args = []
        if not isinstance(args, list):
            args = [args]
        if len(args) == 0:
            args.append(0.01)
        if len(args) == 1:
            args.append(1-args[0])

        LOGGER.debug("low cut: %.0f %%, high cut: %.0f %%",
                     100*args[0], 100*args[1])

        hist_num_points = 2**16 - 1

        # Use luminance
        if len(self.img.shape) == 3:
            lumin = np.mean(self.img, 2)
        else:
            lumin = self.img.copy()

        # histogram
        hist, _ = np.histogram(lumin.flatten(), hist_num_points,
                               normed=True)
        # cumulative distribution function
        cdf = hist.cumsum()
        # normalize to image maximum
        cdf = self.img.max() * cdf / cdf[-1]

        # find lower end truncation point
        start = 0
        csum = 0
        while csum < cdf[-1]*args[0]:
            csum = cdf[start]
            start += 1
        # higher end truncation point
        end = cdf.size - 1
        csum = cdf[-1]
        while csum > cdf[-1]*args[1]:
            csum = cdf[end]
            end -= 1

        LOGGER.debug("Truncation points: %d and %d", start, end)

        # calculate the corresponding data values
        start_val = start * self.img.max() / hist_num_points
        end_val = end * self.img.max() / hist_num_points

        # truncate
        self.img[self.img < start_val] = start_val
        self.img[self.img > end_val] = end_val


    def _remove_gradient(self, args):
        '''Calculate the gradient from the image, subtract from the
        original, scale back to full bit depth and return the result.
        '''
        self._to_numpy()

        args = {'method': {'blur': args}}

        gradient = self._calculate_gradient(args)
        self.img -= gradient.img

        if self.img.min() < 0:
            self.img -= self.img.min()


    def _calculate_gradient(self, args):
        '''Calculate gradient from the image using the given method.
        :param method: name of the method for calculating the gradient
        '''
        methods = {'blur': self._gradient_blur,
                   'random': self._gradient_random_points,
                   'grid': self._gradient_grid_points}
        # 'user': self._gradient_get_user_points,
        # 'mask': self._gradient_mask_points,
        # 'all': self._gradient_all_points

        LOGGER.debug("Calculating gradient.")
        try:
            func = methods[args['method'].keys()[0]]
        except TypeError:
            LOGGER.error("Method \"%s\" not available, using method \"blur\"",
                         args['method'].keys()[0])
            args = {}
            args['method'] = {'blur': None}
            func = methods['blur']
        result = func(args['method'])
        shape = self.img.shape

        if args['method'].keys()[0] in ['blur']:
            return result

        x_pts, y_pts = result
        if len(shape) == 2:
            return Image(img=self._gradient_fit_surface(x_pts, y_pts,
                                                        order=args['order']),
                         nprocs=self._nprocs)
        else:
            gradient = np.empty(shape)
            for i in range(shape[2]):
                gradient[:, :, i] = \
                    self._gradient_fit_surface(x_pts, y_pts,
                                               order=args['order'],
                                               chan=i)
            return Image(img=gradient, nprocs=self._nprocs)

    def _gradient_blur(self, args):
        '''Blur the image to get the approximation of the background
        gradient.
        '''
        gradient = Image(img=self.img.copy(), nprocs=self._nprocs)
        gradient.enhance(args)

        return gradient

    def _gradient_random_points(self, args):
        '''Automatically extract background points for gradient estimation.
        '''
        shape = self.img.shape
        y_pts = np.random.randint(shape[0], size=(args['points'],))
        x_pts = np.random.randint(shape[1], size=(args['points'],))

        return (x_pts, y_pts)

    def _gradient_grid_points(self, args):
        '''Get uniform sampling of image locations.
        '''
        shape = self.img.shape
        y_locs = np.arange(0, shape[0], args['points'])
        x_locs = np.arange(0, shape[1], args['points'])
        x_mat, y_mat = np.meshgrid(x_locs, y_locs, indexing='ij')

        return (x_mat.ravel(), y_mat.ravel())

    def _gradient_fit_surface(self, x_pts, y_pts, order=2, chan=None):
        '''Fit a surface to the given channel.
        '''
        shape = self.img.shape
        x_locs, y_locs = np.meshgrid(np.arange(shape[0]),
                                     np.arange(shape[1]))
        if chan is not None:
            poly = polyfit2d(x_pts, y_pts, self.img[y_pts, x_pts, chan].ravel(),
                             order=order)
            return polyval2d(x_locs, y_locs, poly)
        else:
            poly = polyfit2d(x_pts, y_pts, self.img[y_pts, x_pts].ravel(),
                             order=order)
            return polyval2d(x_locs, y_locs, poly).T


    def _rotate(self, *args):
        '''Rotate image.
        '''
        # use scipy.ndimage.interpolation.rotate()
        del args
        LOGGER.error("Image rotation not implemented.")

    def _usm(self, args):
        '''Use unsharp mask to enhance the image contrast.  Uses ImageMagick.
        '''

        self._to_imagemagick()
        if len(args) == 2:
            args.append(np.sqrt(args[0]))
        if len(args) == 3:
            args.append(0)
        LOGGER.debug("Radius: %.0lf, amount: %.1lf, "
                     "sigma: %.1lf, threshold: %.0lf.", args[0], args[1],
                     args[2], args[3])
        self.img.unsharpmask(*args)

    def _emboss(self, args):
        '''Emboss filter the image. Actually uses shade() from
        ImageMagick.
        '''

        if args is None:
            args = []
        if len(args) == 0:
            args.append(90)
        if len(args) == 1:
            args.append(10)
        LOGGER.debug("Azimuth: %.1lf, elevation: %.1lf.", args[0], args[1])
        self._to_imagemagick()
        self.img.shade(*args)

    def _blur_im(self, args):
        '''Blur the image using ImageMagick.
        '''
        self._to_imagemagick()
        # args['radius'], args['weight'])
        self.img.blur(*args)

    def _blur(self, args):
        '''Blur the image using 1D convolution for each column and
        row. Data borders are padded with mean of the border area
        before convolution to reduce the edge effects.
        '''
        self._to_numpy()

        shape = self.img.shape
        if args is None:
            radius = int(np.min(shape[:2])/20.)
            sigma = radius/3.
        else:
            radius = args[0]
            if len(args) > 1:
                sigma = args[1]
            else:
                sigma = radius/3.

        def form_blur_data(data, radius):
            '''Form vectors for blur.
            '''
            vect = np.zeros(2*radius+data.size-1, dtype=data.dtype)
            vect[:radius] = np.mean(data[:radius])
            vect[radius:radius+data.size] = data
            vect[-radius:] = np.mean(data[-radius:])

            return vect

        def gaussian_kernel(radius, sigma):
            ''' Generate a gaussian convolution kernel.

            'param radius: kernel radius in pixels
            'type radius: int
            'param sigma': standard deviation of the gaussian in pixels
            'type sigma: float
            '''

            sigma2 = sigma**2

            half_kernel = map(lambda x: 1/(2 * np.pi * sigma2) * \
                                  np.exp(-x**2 / (2 * sigma2)),
                              range(radius+1))
            kernel = np.zeros(2*radius+1)
            kernel[radius:] = half_kernel
            kernel[:radius+1] = half_kernel[::-1]
            kernel /= np.sum(kernel)

            return kernel

        kernel = gaussian_kernel(radius, sigma)

        LOGGER.debug("Blur radius is %.0lf pixels and sigma is %.3lf.",
                     radius, sigma)
        LOGGER.debug("Using %d threads.", self._nprocs)

        if self._nprocs > 1:
            self._pool = Pool(self._nprocs)

        for i in range(shape[-1]):
            # rows
            data = []
            for j in range(shape[0]):
                data.append([kernel, form_blur_data(self.img[j, :, i],
                                                    radius)])
            if self._nprocs > 1:
                result = self._pool.map(_blur_worker, data)
            else:
                result = map(_blur_worker, data)

            # compile result data
            for j in range(shape[0]):
                self.img[j, :, i] = result[j][2*radius:2*radius+shape[1]]

            data = []
            # columns
            for j in range(shape[1]):
                data.append([kernel, form_blur_data(self.img[:, j, i],
                                                    radius)])
            if self._nprocs > 1:
                result = self._pool.map(_blur_worker, data)
            else:
                result = map(_blur_worker, data)

            # compile result data
            for j in range(shape[1]):
                self.img[:, j, i] = result[j][2*radius:2*radius+shape[0]]

        self.img -= np.min(self.img)


    def _gamma(self, args):
        '''Apply gamma correction to the image.
        '''
        if args is None:
            return
        if not isinstance(args, list):
            args = [args]
        self._to_numpy()
        LOGGER.debug("Apply gamma correction, gamma: %.2lf.", args[0])
        self.img /= self.img.max()
        self.img **= args[0]
Example #37
0
# Fails: 231.py
# Autors: Artis Erglis

from PythonMagick import Image

# Izgatavojam jaunu objektu - bilde
# Objekta izmeers 3x3 pixels
bilde = Image ( "3x3", "#22aaff" )

# Izgatavojam mainiigos x un y
x = y = 0

# Uzstaada objekta 'bolde' x,y pixela kraasu
bilde.pixelColor ( x,y, "#eeff22")

# 3x3 pixels palielina lidz 200x200
bilde.scale ( "200x200" )

# Objektu 'bilde' ieraksata failaa
bilde.write ( "231.png" )
Example #38
0
File: pix.py Project: artosx/xarab
#!/usr/bin/python
#programma uzziimee failaa 'burts_A.png' burtu 'A'

import numpy
from PythonMagick import Image

m = numpy.matrix([ \
[0,0,1,0,0], \
[0,1,0,1,0], \
[1,0,0,0,1], \
[1,0,0,0,1], \
[1,1,1,1,1], \
[1,0,0,0,1], \
[1,0,0,0,1], \
])
bilde = Image("5x7","#22aaff")

for i in range (0,5):
 for j in range (0,7):
  if(m[j,i]=1):
   bilde.pixelColor(i,j,"#FFF")
bilde.scale("200x200")
bilde.write("burts_A.png")
  
Example #39
0
from PythonMagick import Image
bilde= Image("8x8","#33FFCC")
x=y=0
for i in range(0,4):
    bilde.pixelColor(i,1, "#993300")
for i in range(0,4):
    bilde.pixelColor(i,7, "#993300")
for i in range (2,4):
    bilde.pixelColor(i,3,"#993300")
for i in range (2,4):
    bilde.pixelColor(i,5,"#993300")
bilde.pixelColor(4,2, "#993300")
bilde.pixelColor(4,4, "#993300")
bilde.pixelColor(4,6, "#993300")
bilde.scale("200x200")
bilde.write("236.png")
Example #40
0
def modify_images(application_path):
    output_dirs = [
        path.join(application_path, "..", "512"),
        path.join(application_path, "..", "150")
    ]
    count_files = 0
    override = None

    FileUtilities.create_needed_folder(output_dirs)

    print()
    print(
        "\t--------------------------------------------------------------------"
    )
    print()
    print("\tErstelle die Bilder in der Größe \"512px\":")
    print()

    for filename in listdir(application_path):
        if not filename.endswith(".jpg"):
            continue

        if path.isfile(path.join(output_dirs[0], filename)):
            if override is None:
                override = TerminalUtilities.query_yes_no(
                    "\tSollen die bereits vorhandenen Bilder überschrieben werden?",
                    False)

            if not override:
                continue

        try:
            img = Image(path.join(application_path, filename))
            # noinspection PyArgumentList
            img.strip()
            # noinspection PyArgumentList
            img.trim()
            img.quality(80)
            img.resize("512x512>")
            img.write(path.join(output_dirs[0], filename))
        except RuntimeError as error:
            TerminalUtilities.error_handler(str(error), "RuntimeError")

        print("\t" + filename + "\t erfolgreich erstellt.")

        count_files += 1

    print()
    print("\tInsgesamt wurden " + str(count_files) +
          " Bilder in der Größe \"512px\" erzeugt.")
    print()
    print(
        "\t--------------------------------------------------------------------"
    )
    print()
    print("\tErstelle die Bilder in der Größe \"150px\":")
    print()

    count_files = 0

    for filename in listdir(output_dirs[0]):
        if not filename.endswith(".jpg"):
            continue

        if (not override) and (path.isfile(path.join(output_dirs[1],
                                                     filename))):
            continue

        img = Image(path.join(output_dirs[0], filename))
        img.resize("150x150>")
        img.write(path.join(output_dirs[1], filename))

        print("\t" + filename + "\t erfolgreich erstellt.")

        count_files += 1

    print()
    print("\tInsgesamt wurden " + str(count_files) +
          " Bilder in der Größe \"150px\" erzeugt.")