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 #2
0
 def generate(self):
     os.chdir(self.path)
     img = Image(self.filename)
     img.sample("128x128")
     name = self.filename.split('.')[0]
     img.write(name + '.ico')
     print(f'>>> 成功写出文件:{self.path + name}.ico')
Example #3
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 #4
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 pdf2bmp(path):

    img = Image()
    f = open(path, "rb")
    opened_pdf = PdfFileReader(f)
    page_num = opened_pdf.getNumPages()

    if page_num == 1:
        img.read(path)
        output_bmp = path.replace(".pdf", ".bmp")
        img.write(output_bmp)

    else:
        for i in range(page_num):
            pdfw = PdfFileWriter()
            pdfw.addPage(opened_pdf.getPage(i))

            output_path = os.path.splitext(path)[0]
            output_pdf = output_path + "_page(" + str(i + 1) + ").pdf"
            with open(output_pdf, "wb") as output:
                pdfw.write(output)

            img.read(output_pdf)
            output_bmp = output_pdf.replace(".pdf", ".bmp")
            img.write(output_bmp)

    f.close()

    return output_bmp, page_num
Example #6
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 #7
0
    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 #8
0
def getimages(request):	
	myfile = PdfFileReader('files.pdf')
	pages = myfile.getNumPages()
	for page in pages:
		im = Image(myfile.getPage(i+1))
		im.write('file_image{}.png'.format(i+1))
	return HttpResponse(json.dumps({"responce code":"100","status": "success" ,"user" : im}), content_type="application/json")
    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 #10
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 #11
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)
Example #12
0
def extractCover(uuid, data):
	"""Extract the cover, resize, and save."""
	f = NamedTemporaryFile(delete=False)
	f.write(data)
	f.close()
	image = Image(f.name)
	image.magick('JPEG') 
	image.sample('256x256')
	image.write('htdocs/images/'+uuid+'.jpg')
	unlink(f.name)
Example #13
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 #14
0
File: utils.py Project: unanono/VCR
def pdf2images(name):
    np = getPdfNumPages(name)
    for p in range(np):
        i = Image()
        i.density('200')
        i.quality(100)
        i.depth(24)
        #i.backgroundColor(
        #i.channel(
        i.read(name + '[' + str(p) + ']')
        i.write(name + str(p) + defaultImageExtension)
Example #15
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 #16
0
def pdf2image(pdf_filepath):
    if not os.path.exists(pdf_filepath):
        return
    '''
    pdf = PdfFileReader(pdf_filepath)
    for page_number in range(pdf.getNumPages()):
        image = Image(pdf.getPage(page_number+1))
        image.write('file_image{}.png'.format(page_number+1))
    pass
    '''
    im = Image(pdf_filepath)
    im.write("file_img%d.png")
Example #17
0
def readPdf_page_by_page(filepath):
    #获取一个pdf对象
    pdf_input = PdfFileReader(open(filepath, 'rb'))
    #获取pdf页数
    page_count = pdf_input.getNumPages()
    #获取pdf第n页的内容
    for n in range(page_count):

        im = Image()
        #im.density("300")
        im.read(filepath + '[' + str(1) + ']')
        im.magick("jpg")
        im.write(filepath + str(n + 1) + ".jpg")
Example #18
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 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 #20
0
def main():
    if len(sys.argv) < 2:
        print('invalid usage!')
        return
    pdf_filename = sys.argv[1]
    pdf = PdfFileReader(file(pdf_filename, "rb"))
    npage = pdf.getNumPages()
    fname = pdf_filename.split('/')[-1]
    tmppath = '/dev/shm/'
    for p in range(npage):
        im = Image()
        im.density('300')
        im.read(pdf_filename + '[' + str(p) + ']')
        im.write(tmppath + fname + '_' + str(p) + out_format)
Example #21
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 #22
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 #23
0
def conver_pdf():
    try:
        pdf = "/temp/view_book/amin_amino_axit_protein_bai_tap.pdf"
        from pyPdf import PdfFileReader
        from PythonMagick import Image
        myfile = PdfFileReader(open(pdf, 'rb'))
        pages = count_pages(pdf)
        print(pages)
        for i in range(0, pages):
            im = Image(myfile.getPage(i))
            im.write('/home/view_book/file_image{}.png'.format(i))
    except Exception as ex:
        print(str(ex) + " on line: " + str(sys.exc_traceback.tb_lineno))
        return dict(error=str(ex) + " on line: " +
                    str(sys.exc_traceback.tb_lineno))
Example #24
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 #25
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 #26
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 #27
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
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 #29
0
def pdf2img(input_pdf, postfix='.png', **kwargs):
    # print os.path.exists(input_pdf)
    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)
    if 'out_path' in kwargs:
        output_jpg = kwargs['out_path']
    else:
        output_jpg = input_pdf + postfix
    if os.path.exists(output_jpg):
        os.remove(output_jpg)
    output_img.write(output_jpg)
Example #30
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())     
Example #31
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
def pad_image_to_x480(file):
    from PythonMagick import Image, CompositeOperator
    fname = file.split(".")[0]
    ext = file.split(".")[-1]
    outfile = os.path.join(destdir, fname + "_" + "l" + ".jpg")

    ## Make BG layer
    bgimg = Image('400x480', 'white')

    ## Open Primary image 
    img = Image(file)
    img.backgroundColor("white")
    img.sample('350x432')

    # Composite + Save Primary over bg, padding primary with white of bg
    type = img.type
    img.composite(bgimg, 0, 0, CompositeOperator.DstOverCompositeOp)
    img.magick('JPG')
    img.type = type
    img.quality(100)
    img.write(outfile)
    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 #35
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 #36
0
def pdf_to_image():
    for pdf in [
            pdf_file for pdf_file in os.listdir(pdf_dir)
            if pdf_file.endswith(".pdf")
    ]:
        input_pdf = pdf_dir + "\\" + pdf + "[1]"
        img = Image()
        img.density('300')
        print input_pdf
        img.read(input_pdf)

        size = "%sx%s" % (img.columns(), img.rows())

        output_img = Image(size, bg_colour)
        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", ".jpg")
        output_img.write(output_jpg)
Example #37
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)
def convert(args):

    dirname = getcwd()
    ifilename = path.join(
        dirname, args.ifile) if not path.isabs(args.ifile) else args.ifile
    ofilename = path.join(
        dirname, args.ofile) if not path.isabs(args.ofile) else args.ofile
    ofilename_n_ext = path.splitext(ofilename)[0]

    reader = PdfFileReader(open(ifilename, "rb"))
    for page_num in xrange(reader.getNumPages()):
        writer = PdfFileWriter()
        writer.addPage(reader.getPage(page_num))
        with open(path.join(dirname, 'temp.pdf'), 'wb') as temp:
            writer.write(temp)

        im = Image()
        im.density("300")  # DPI, for better quality
        im.backgroundColor('white')
        im.fillColor('white')
        im.read(path.join(dirname, 'temp.pdf'))
        im.write("%s_%d.jpg" % (ofilename_n_ext, page_num))

        remove(path.join(dirname, 'temp.pdf'))
Example #39
0
from PythonMagick import Image
photo = Image("9x9", "#0404B4")
x = y = 0
photo.pixelColor(2, 3, '#04B404')
photo.pixelColor(3, 2, '#04B404')
photo.pixelColor(4, 1, '#04B404')
photo.pixelColor(5, 2, '#04B404')
photo.pixelColor(6, 3, '#04B404')
photo.pixelColor(2, 5, '#04B404')
photo.pixelColor(3, 4, '#04B404')
photo.pixelColor(4, 3, '#04B404')
photo.pixelColor(5, 4, '#04B404')
photo.pixelColor(6, 5, '#04B404')
for i in range(2, 7):
    photo.pixelColor(i, 0, '#04B404')
for i in range(3, 6):
    photo.pixelColor(i, 7, '#04B404')
for i in range(2, 5):
    photo.pixelColor(8, i, '#04B404')
for i in range(2, 5):
    photo.pixelColor(0, i, '#04B404')
for i in range(5, 7):
    photo.pixelColor(i / 3, i, '#04B404')
photo.pixelColor(1, 1, '#04B404')
photo.pixelColor(7, 1, '#04B404')
photo.pixelColor(7, 5, '#04B404')
photo.pixelColor(6, 6, '#04B404')

photo.scale("200x200")
photo.write("239.png")
Example #40
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 #41
0
API_KEY='??'
SECRET_KEY='??'
path_wk=r'pdfkit安装位置设置'
pdfkit_config=pdfkit.configuration(wkhtmltopdf=path_wk)
pdfkit_options={'encoding':'UTF-8',}

os.chdir(path)
pdf_input=PdfFileReader(open(pdfname, 'rb'))
page_count=pdf_input.getNumPages()
page_range=range(page_count)

for page_num in page_range:
	im=Image()
	im.density(DPI)
	im.read(pdfname + '[' + str(page_num) +']')
	im.write(str(page_num)+ '.jpg')

client=AipOcr(APP_ID, API_KEY, SECRET_KEY)
def get_file_content(filePath):
	with open(filePath, 'rb') as fp:
		return fp.read()

options={}
options["language_type"]="CHN_ENG"
options["detect_direction"]="false"
options["detect_language"]="false"
options["probability"]="false"
allteststr=[]
for page_num in page_range:
	image=get_file_content(r'%s\%s.jpg' % (path, page_num))
	testjson=client.basicGenral(image, options)
Example #42
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 #43
0
from PythonMagick import Image

bilde = Image("16x16", "#00FF33")
x = y = 0
for a in range(0, 7):
    bilde.pixelColor(a, 8, "#FFFF66")
for a in range(9, 16):
    bilde.pixelColor(a, 8, "#FFFF66")
for a in range(6, 11):
    bilde.pixelColor(9, a, "#000066")
for a in range(6, 11):
    bilde.pixelColor(7, a, "#000066")
bilde.scale("200x200")
bilde.write("237.png")
Example #44
0
def upload():
    if request.method == 'POST':
        file = request.files['file']
        name = os.path.splitext(file.filename)[0]
        extension = os.path.splitext(file.filename)[1]
        f_name = name + extension
        if extension == ".pdf":
            file.save(os.path.join(basedir,UPLOAD_FOLDER , f_name))
            filepath = os.path.join('./upload', f_name)
            os.makedirs(os.path.join("./images", name))
            filepath1 = os.path.join('./images', name)
            reader = PdfFileReader(open(filepath, "rb"))
            for page_num in xrange(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 = Image()
                im.density("300")  # DPI, for better quality
                im.read(temp.name)
                im.write("images/%s/ %d.jpg" % (str(name), page_num))
                os.remove(temp.name)
            os.remove(filepath)
            dirs = os.listdir(filepath1)
            dict = {}
            i = 0
            dict["file_name"] = f_name
            for file in dirs:
                filepath2 = os.path.join(filepath1, file)
                with io.open(filepath2, 'rb') as image_file:
                    content= base64.b64encode(image_file.read())
                    payload = {
                        "requests": [
                            {
                                "image": {
                                    "content": content
                                },
                                "features": [
                                    {
                                        "type": "TEXT_DETECTION"
                                    }
                                ]
                            }
                        ]
                    }
                r = requests.post(url, data=json.dumps(payload))
                r = json.loads(r.text)
                r=r['responses'][0]['textAnnotations'][0]['description']
                key = "page_no-" + str(file)
                dict[key] = r
            shutil.rmtree(filepath1)
            return json.dumps(dict)
        elif extension == '.png' or extension == '.jpg' or extension == '.jpeg':
            dict = {}
            dict["file_name"] = f_name
            file.save(os.path.join(basedir, UPLOAD_FOLDER, f_name))
            filepath = os.path.join('./upload', f_name)
            with io.open(filepath, 'rb') as image_file:
                content = base64.b64encode(image_file.read())
                payload = {
                    "requests": [
                        {
                            "image": {
                                "content": content
                            },
                            "features": [
                                {
                                    "type": "TEXT_DETECTION"
                                }
                            ]
                        }
                    ]
                }
            r = requests.post(url, data=json.dumps(payload))
            r=json.loads(r.text)
            r=r['responses'][0]['textAnnotations'][0]['description']
            dict["text"] = r
            os.remove(filepath)
            return json.dumps(dict)
        else:
            return json.dumps({'file format is wrong': f_name})

    return json.dumps({'file proess completed': f_name})
Example #45
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 #46
0
import os
import ghostscript
from PyPDF2 import PdfFileReader, PdfFileWriter
from tempfile import NamedTemporaryFile
from PythonMagick import Image

reader = PdfFileReader(open('C:\\Users\\user\\Desktop\\fp\\1.pdf', "rb"))
for page_num in xrange(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.density("3000")
    #im.read(tempname)
    im.write("some_%d.jpg" % (page_num))

    os.remove(tempname)

reader.close()
Example #47
0
#Fails 231.py
#Autors Reinis Prockans

from PythonMagick import Image

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

#Izgatavojam mainigos x un y
x = y = 0

#Uzstada objekta 'bilde' x,y pixela krasu
bilde.pixelColor(x, y, "#eeff22")

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

#Objektu 'bilde' ieraksta faila
bilde.write("231.png")
Example #48
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')
bilde.pixelColor(1,1, '#55E666')
bilde.pixelColor(7,1, '#55E666')
bilde.pixelColor(7,5, '#55E666')
bilde.pixelColor(6,6, '#55E666')

# 9x9 pixles palielina lidz 200x200
bilde.scale("200x200")

# Objektu 'bilde' ieraksta failaa
bilde.write("239.png")
    def tiff_to_pdf(list_of_file_paths, destination_directory):
        """
        This method converts individual TIFF image files to PDF.
        :param list_of_file_paths: This argument is the list of absolute file paths for example
        ['C:/User/Documents/Images/Image1.tiff', 'C:/User/Documents/Images/Image2.tiff' ]
        :param destination_directory: Pass in the absolute path to the directory you want the
        converted files to be saved to.
        :return: This method returns a dictionary giving information about the success or failure
        of the operation and also gives the list of files that failed the conversion..
        """
        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)

        if not os.path.exists(os.path.join(os.getcwd(), "temp_dir")):
            os.mkdir(os.path.join(os.getcwd(), "temp_dir"))

        path_to_temp = os.path.join(os.getcwd(), "temp_dir")

        for image in list_of_file_paths:
            temp_file_list = []
            img = Image.open(image)
            tif_file_full_name = os.path.basename(image)
            tif_file_name, tif_file_ext = os.path.splitext(tif_file_full_name)
            for i in range(100):
                try:
                    img.seek(i)
                    temp_file_list.append(os.path.join(path_to_temp, 'page' + str(i + 1) + ".tif"))
                    img.save(os.path.join(path_to_temp, 'page' + str(i + 1) + ".tif"))
                except EOFError:
                    break

            png_temp_array = []
            for tif_img in temp_file_list:
                img_png = Image.open(tif_img)
                file_name = os.path.basename(tif_img)
                name, ext = os.path.splitext(file_name)
                file_name_at_destination = os.path.join(path_to_temp, name + ".png")
                png_temp_array.append(file_name_at_destination)
                img_png.save(file_name_at_destination)
                os.remove(tif_img)

            pdf_temp_array = []
            for png_img in png_temp_array:
                image = PyImage()
                image.density("600")
                image.read(png_img)
                png_file_name = os.path.basename(png_img)
                png_name, png_ext = os.path.splitext(png_file_name)
                file_name_at_destination = os.path.join(path_to_temp, png_name + ".pdf")
                pdf_temp_array.append(file_name_at_destination)
                image.write(file_name_at_destination)
                os.remove(png_img)

            if pdf_temp_array.__len__() > 1:
                ImageOpr.merge_pdf(pdf_temp_array, destination_directory, tif_file_name, delete_source=False)
                for pdfs in pdf_temp_array:
                    os.remove(pdfs)
            else:
                os.rename(pdf_temp_array[0], os.path.join(path_to_temp, tif_file_name + ".pdf"))
                destination_directory_file_name = os.path.join(destination_directory, tif_file_name + ".pdf")
                shutil.move(os.path.join(path_to_temp, tif_file_name + ".pdf"), destination_directory_file_name)

        shutil.rmtree(path_to_temp, ignore_errors=True)

        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 #50
0
def pngtoico(filename):  #png转ico
    from PythonMagick import Image  # https://www.lfd.uci.edu/~gohlke/pythonlibs/#pythonmagick
    img = Image(filename)
    # 这里要设置一下尺寸,不然会报ico尺寸异常错误
    img.sample('128x128')
    img.write(filename.split('.')[0] + '.ico')
Example #51
0
import struct
from PIL import Image
im = Image.open('picture.jpeg')
pix = im.load()
print im.size
width = im.size[0]
print width
height = im.size[1]
print height
from PythonMagick import Image as Im
bilde = Im(('%dx%d' % (width, height)), '#12ff21')
print bilde.size
print pix[0, 0]
for x in range(width):
    for y in range(height):
        if pix[x, y][1] > 40 and pix[x, y][2] > 60 and pix[x, y][0] > 20:
            pix[x, y] = ((pix[x, y][2]), (pix[x, y][0]), (pix[x, y][1]))
        else:
            pix[x, y] = (0, 0, 0)
        bilde.pixelColor(
            x, y, ("#%s" % (struct.pack('BBB', *pix[x, y][:3]).encode('hex'))))
bilde.write('filtrs4.jpeg')
Example #52
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 #53
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 #54
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")
bilde.pixelColor(2, 17, "#eeff22")
bilde.pixelColor(3, 18, "#eeff22")
bilde.pixelColor(4, 19, "#eeff22")
bilde.pixelColor(5, 20, "#eeff22")

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

#Objektu 'bilde' ieraksta faila
bilde.write("232.png")
Example #55
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 #56
0
from PythonMagick import Image
from datetime import datetime

start_time = datetime.now()

pdf_dir = "/run/media/gru/Storage/Thesis-Latex/figures/vis-results"
bg_colour = "#ffffff"

for root, _, pdfs in os.walk(pdf_dir):
    for pdf in pdfs:
        if '.pdf' in pdf:
            input_pdf = os.path.join(root, pdf)
            print(input_pdf)
            img = Image()
            # img.density('300')
            img.read(input_pdf)

            size = "%sx%s" % (img.columns(), img.rows())

            output_img = Image(size, bg_colour)
            output_img.type = img.type
            output_img.composite(
                img, 0, 0, PythonMagick.CompositeOperator.SrcOverCompositeOp)
            output_img.resize(str(800))
            output_img.magick('PNG')
            output_img.quality(75)

            output_jpg = input_pdf.replace(".pdf", ".png")
            output_img.write(output_jpg)

print(datetime.now() - start_time)
Example #57
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 #58
0
from PythonMagick import Image
bilde = Image("16x16", "#FFFF00")
x = y = 0
for a in range(0, 5):
    bilde.pixelColor(8, a, "#FFFF00")
for a in range(11, 16):
    bilde.pixelColor(8, a, "#FFFF00")
for a in range(6, 10):
    bilde.pixelColor(a, 5, "#00FFFF")
for a in range(6, 10):
    bilde.pixelColor(a, 11, "#00FFFF")
for a in range(5, 12):
    bilde.pixelColor(6, a, "#00FFFF")
for a in range(5, 12):
    bilde.pixelColor(10, a, "#00FFFF")
bilde.scale("200x200")
bilde.write("235.png")