Example #1
0
    def playpdf(self, ds):
        """
        split pdf file
        :param ds: (int) set ds = 1024 ~= 1MB output under my test
        :return: splited PNG image file
        """
        pdf = PyPDF2.PdfFileReader(file(self.i_file, "rb"))

        pages = pdf.getNumPages()
        print(
            'Totally get ***{0:^4}*** pages from "{1.i_file}", playpdf start......'
            .format(pages, self))
        try:
            for i in range(pages):
                image = PythonMagick.Image()

                image.density(str(ds))  # 设置 文件大小
                image.read(self.i_file + '[' + str(i) + ']')
                image.magick("PNG")
                image.write(self.o_dire + str(i + 1) + ".png")
                print("{0:>5}     page OK......".format(i + 1))
        except Exception as e:
            print(str(e))
import PythonMagick
image = PythonMagick.Image("radiona.png")
print image.fileName()
print image.magick()
print image.size().width()
print image.size().height()
Example #3
0
#build image attributes
image = ET.Element('image')
stack = ET.SubElement(image, 'stack')
oraxml = image.attrib
oraxml['w'] = str(outimagewidth)
oraxml['h'] = str(outimageheight)

#parse layers
imgc = 0
for path in reversed(map):
    tagtype = path.tag
    imgc = imgc + 1
    if tagtype == 'layer':
        #create canvas image
        canvas = Magick.Image(Magick.Geometry(outimagewidth, outimageheight),
                              "transparent")
        canvas.magick('PNG')
        gidarray = getTMXlayerData(path)
        for y in range(0, height):
            for x in range(0, width):
                Gid = x + (width * y)
                Tid = int(gidarray[Gid])
                if Tid != 0:
                    TidX = (Tid * tilewidth %
                            tilesetimgwidth) - tilewidth  #why need's -32?
                    TidY = ((Tid / (tilesetimgwidth / tilewidth)) *
                            tileheight % tilesetimgheight)
                    PosX = x * tilewidth
                    PosY = y * tileheight
                    tsi = Magick.Image(Magick.Blob(tilesetimageraw))
                    tsi.crop(Magick.Geometry(tilewidth, tileheight, TidX,
Example #4
0
#!/usr/bin/python
#

import PythonMagick
from PyPDF2 import PdfFileWriter, PdfFileReader

fileName = "BrewPi-HERMS-drawing"
input = PdfFileReader(file(fileName + ".pdf", "rb"))
output = PdfFileWriter()

numPages = input.getNumPages()
print "document has %s pages." % numPages

# pythonmagic gave me errors. Direct shell commands worked instead.
from subprocess import check_output
for i in range(numPages):
    print "processing page ", i
    cmd = "convert -density 300 -flatten BrewPi-HERMS-drawing.pdf[" + str(i) + "] png/" + fileName + "-%02d.png"
    print check_output(cmd, shell=True)
exit()

# Pythonmagic implementation below, didn't work for me
img = PythonMagick.Image()
img.density("300")

for i in range(numPages):
    print "processing page ", i
    # img.read(fileName + ".pdf[" + str(i) + "]") # read in at 300 dpi
    img.read('BrewPi-HERMS-drawing.pdf[0]') # read in at 300 dpi
    img.write(fileName + str(i) + ".png")
Example #5
0
# !/usr/bin/python
# -*- coding: utf-8 -*-
"""
author      : 蛙鳜鸡鹳狸猿
create_time : 2016年 11月 01日 星期二 17:38:06 CST
program     : *_* script of manipulating pdf *_*
"""
import os
import sys
import PyPDF2
import PythonMagick
import ghostscript
from tempfile import NamedTemporaryFile

# reader = PyPDF2.PdfFileReader(open("申报表详情10014417000004730680.pdf", 'rb'))
pdffilename = "申报表详情10014417000004730680.pdf"
pdf_im = PyPDF2.PdfFileReader(open(pdffilename, "rb"))

print(1)
npage = pdf_im.getNumPages()
print('Converting %d pages.' % npage)
for p in range(npage):
    im = PythonMagick.Image()
    im.density('50')
    im.read(pdffilename + '[' + str(p) + ']')
    im.write('file_out-' + str(p) + '.png')
    # print pdffilename + '[' + str(p) +']','file_out-' + str(p)+ '.png'
Example #6
0
import PythonMagick
import sys
image = PythonMagick.Image(sys.stdin)
print image.fileName()
print image.magick()
print image.size().width()
print image.size().height()
Example #7
0
import PythonMagick
import os

path = os.getcwd()
filename = input("2.png")
filepath = path + '//' + filename

img = PythonMagick.Image(filepath)
img.sample('128x128')

newpath = path + '//ico.ico'
img.write(newpath)
Example #8
0
import PythonMagick
import tkinter
img = PythonMagick.Image('/eclipse-workspace/pictures/LOGO.jpg')
img.sample('128x128')
img.write('/eclipse-workspace/pictures/LOGO.ico')
win = tkinter.Tk()
win.title("")
win.geometry('250x250')
win.iconbitmap('/eclipse-workspace/pictures/LOGO.ico')
win.mainloop()
Example #9
0
    def convert_files(self):

        file_directory = (unicode(self.path_entry.text()))
        file_count = 0

        # converts a single image file
        if os.path.isfile(
                file_directory) and self.single_file_radio_button.isChecked():

            split_path = os.path.split(file_directory)[0]
            #print split_path

            file_name = os.path.split(file_directory)[1]
            #print file_name

            if os.path.isfile(file_directory) and file_name.lower().endswith(
                    self.types):
                file_location = str(os.path.join(split_path, str(file_name)))
                image = PythonMagick.Image(file_location)
                # This code reduce the size for larger files if need be
                '''	
				if image.size().width() >= 1024 and image.size().height() >= 1024:#1024 originally 		
					w, h = image.size().width(), image.size().height()
					image.resize("{}x{}".format(w/2, h/2))
													
					print 'File is large' #divide by 4 or 3
				'''
                converted_image_name = 'image_' + str(file_count + 1) + str(
                    self.filetypes.currentText())

                image.write("{}".format(
                    str(os.path.join(split_path, converted_image_name))))

        # converts image files in directory (Test pdf conversion)
        elif os.path.isdir(
                file_directory) and self.multi_file_radio_button.isChecked():

            length_of_valid_filetypes = len([
                file for file in os.listdir(file_directory)
                if file.lower().endswith(self.types)
            ])
            self.create_ouput_dir()

            if length_of_valid_filetypes <= 0:
                self.progress_bar.setMaximum(1)
            else:
                self.progress_bar.setMaximum(length_of_valid_filetypes)

            for file in os.listdir(file_directory):

                if file.lower().endswith(self.types):
                    file_location = str(os.path.join(file_directory,
                                                     str(file)))

                    image = PythonMagick.Image(file_location)
                    # This code reduce the size for larger files if need be
                    '''
					if image.size().width() >= 1024 and image.size().height() >= 1024:#1024 originally 
						w, h = image.size().width(), image.size().height()
						image.resize("{}x{}".format(w/2, h/2))							
						print 'File is large' #divide by 4 or 3
					'''
                    converted_image_name = 'image_' + str(
                        file_count + 1) + str(self.filetypes.currentText())

                    image.write("{}".format(
                        str(
                            os.path.join(self.saved_output_path,
                                         converted_image_name))))

                    file_count = file_count + 1

                    self.progress_bar.setValue(file_count)
                    QCoreApplication.processEvents()
Example #10
0
def trying():
    ##files = glob.glob('.static/OUT/*')
    ##print files
    ##for f in files:
    ##	os.remove(f)
    gname = app.vars

    if os.path.exists('./static/zips/' + app.vars + '.zip'):
        with zipfile.ZipFile("./static/zips/" + app.vars + ".zip",
                             "r") as zip_ref:
            zip_ref.extractall("./static/OUT/")
        filelink = "/static/zips/" + app.vars + ".zip"
        pnglist = glob.glob('./static/OUT/*km.png')
        object_list = get_csv()
        script, div = plot_levels()
        return render_template('trying.html',
                               splicing=get_splice(gname),
                               object_list=object_list,
                               filelink=filelink,
                               pnglist=pnglist,
                               gname=gname,
                               script=script,
                               div=div)

    command = 'Rscript'
    path2script = './static/TCGAkm.r'
    args = [app.vars]
    cmd = [command, path2script] + args
    x = subprocess.check_output(cmd, universal_newlines=True)

    img = PythonMagick.Image()
    img.density("300")
    pdflist = glob.glob('./static/OUT/*.pdf')
    pnglist = []
    for item in pdflist:
        img.read(item)
        newf = item[:-3] + 'png'
        img.write(newf)
        pnglist.append(newf)

    path2script = './static/expr_med.r'
    cmd2 = [command, path2script]
    y = subprocess.check_output(cmd2, universal_newlines=True)

    path2script = './static/mutations.r'
    args = [app.vars]
    cmd3 = [command, path2script] + args
    z = subprocess.check_output(cmd3, universal_newlines=True)

    shutil.make_archive("./static/zips/" + app.vars, 'zip', "./static/OUT/")
    filelink = "/static/zips/" + app.vars + ".zip"

    object_list = get_csv()
    script, div = plot_levels()

    return render_template('trying.html',
                           splicing=get_splice(gname),
                           object_list=object_list,
                           filelink=filelink,
                           pnglist=pnglist,
                           gname=gname,
                           script=script,
                           div=div)
Example #11
0
tooth_id = 0

for i in range(n):
    imagePath = "{}.jpg".format(i)
    print 'working for {}'.format(imagePath)
    
    print 'reading image'
    image = cv2.imread(imagePath)
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

    print 'detecting face'
    faces = faceCascade.detectMultiScale(
        gray,
        scaleFactor=1.4,
        minNeighbors=5,
        minSize=(30, 30)
        #flags = cv2.CV_HAAR_SCALE_IMAGE
    )

    print("Found {0} faces!".format(len(faces)))

    print 'cropping faces'
    for (x, y, w, h) in faces:
        image = PythonMagick.Image(imagePath)

        image.crop(PythonMagick.Geometry(int(w), int(h/2), int(x), int(y+ h/2))) # w, h, x, y

        image.write('{}.tooth.jpg'.format(tooth_id))
        tooth_id += 1

Example #12
0
# -*- coding: cp936 -*-

import os
import PythonMagick
import ghostscript
from PythonMagick import Image

         
pdf_dir = 'C:\\Users\\user\\Desktop\\fp' 
bg_colour = "#ffffff"

for pdf in [pdf_file for pdf_file in os.listdir(pdf_dir) if pdf_file.endswith(".pdf")]:

    input_pdf = pdf_dir + "\\" + pdf
    img = PythonMagick.Image(input_pdf)
    img.density('300')


    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(100)


    output_jpg = input_pdf.replace(".pdf", ".jpg")
    output_img.write(output_jpg)
Example #13
0
import PythonMagick
import pyPdf
filename = 'sheetmusic.pdf'
print file(filename).name
pdf_im = pyPdf.PdfFileReader(file(filename, "rb"))
npage = pdf_im.getNumPages()
for p in range(npage):
    im = PythonMagick.Image(filename + '[' + str(p) + ']')
    im.write('file_out-' + str(p) + '.png')
Example #14
0
# import PythonMagick
#
#
# img = PythonMagick.Image()
# img.density("300")
# img.read("thes.pdf") # read in at 300 dpi
# img.write("thes.png")

import PythonMagick
img = PythonMagick.Image("thes.pdf")
img.density("300")  # too late, already read as 72 dpi when image instantiated
img.write("thes.svg")
Example #15
0
argp.add_argument('-p', '--crop', help='crop to 220x298', action='store_true')
argp.add_argument('-n',
                  '--noise',
                  help='add Guassian noise',
                  action='store_true')

args = argp.parse_args()

dirin = args.indir
jpgfiles = [f for f in os.listdir(dirin) if f.endswith('.jpg')]

if os.path.exists(args.outdir) == False:
    os.mkdir(args.outdir)
outdir = args.outdir + "/"
for jpg in jpgfiles:
    img = Magick.Image(dirin.rstrip('/') + "/" + jpg)
    pre_suff = jpg.split(".")

    if args.flipflop == True:
        img.flip()
        img.write(outdir + pre_suff[0] + "_FLIPPED." + pre_suff[1])
        img.flop()
        img.write(outdir + pre_suff[0] + "_FLIPPED_FLOPPED." + pre_suff[1])
        img.flip()
        img.write(outdir + pre_suff[0] + "_FLOPPED." + pre_suff[1])
        img.flop()

    if args.rotate:
        img.rotate(args.rotate)
        img.crop(Magick.Geometry(220, 298, 0, 0))
        img.sample(str(220) + "x" + str(298) + "!")
Example #16
0
def process_user_image_files(emailaddr):
    pagewidth = 800
    pageheight = 600
    logging.debug("cur_path %s" % (os.path.realpath('.'),) )
    odpfile = 'frieda_%s_%s.odp' % (emailaddr, time.strftime('%b_%d_%Y_%I%M%P'))
    ppt_content = []

    file_list = []
    for wroot, wsubdir, wfiles in os.walk('.'):
        wfiles = sort_files_by_time(wfiles, wroot)
        wsubdir = sort_files_by_time(wsubdir, wroot)
        cnt = 0
        for f in wfiles:
            cnt += 1
            file_list.append(os.path.join(wroot, f))
        if cnt != 0:
            wroot2 = '/' if len(wroot) < 2 else wroot[1:]
            ppt_content.append((wroot2, cnt))

    logging.debug('file_list: %r' % file_list)
    doc = OpenDocumentPresentation()
    pagelayout = PageLayout(name="MyLayout")
    pagelayout.addElement(PageLayoutProperties(backgroundcolor="#000000", margin="0pt", pagewidth="%dpt" %pagewidth,
                                               pageheight="%dpt" % pageheight, printorientation="landscape"))
    doc.automaticstyles.addElement(pagelayout)
    photostyle = Style(name="RadTeaching-photo", family="presentation")
    doc.styles.addElement(photostyle)
    dstyle = Style(name="d", family="drawing-page")
    dstyle.addElement(GraphicProperties(fillcolor="#000000"))
    dstyle.addElement(DrawingPageProperties(fill=True,
                                            fillcolor="#000000"))
    doc.automaticstyles.addElement(dstyle)


    masterpage = MasterPage(name="RadTeaching", pagelayoutname=pagelayout)
    doc.masterstyles.addElement(masterpage)
    images_added = 0
    # os.chdir(subdir)
    for picture in file_list:
        try:
            pictdata = open(picture).read()
            logging.debug("Adding %s" % (picture))
        except:
            logging.debug("Skipping %s" % (picture))
            continue
        ct,w,h = getImageInfoFileName(picture)
        if ct == 'not image':
            if picture[-4:] == '.dcm':
                png_picture = picture.replace('.dcm','.png')
                logging.debug("Converting %s to %s" % (picture, png_picture) )
                run_command(""" dcmj2pnm +on +Wi 1 %s %s """ % (picture, png_picture))
                picture = png_picture
                ct,w,h = getImageInfoFileName(picture)

        if ct not in ("jpeg", "jpg", "tiff", "png", "bmp", "gif", "tif"):
            logging.debug("Skipping %s unrecognized type %s" % (picture,ct) )
            continue
        if ct == "tiff" or ct == "tif":
            png_picture = picture.replace(".tiff",".tif").replace(".tif", ".png")
            logging.debug("Converting %s to %s" % (picture, png_picture))
            img = PythonMagick.Image()
            img.read(picture)
            if img.depth() > 8: # powerpoint can't handle 16 bit TIFF images.
                img.write(png_picture)
                del img
                picture = png_picture
                ct,w,h = getImageInfoFileName(picture)

        images_added += 1
        if w*pageheight > h*pagewidth: #check if width or height is limit to zooming
            h = float(h) * (pagewidth-2.0)/float(w)
            w = pagewidth - 2.0
        else:
            w = float(w)*(pageheight-2.0) / float(h)
            h = pageheight -2.0

        page = Page(stylename=dstyle, masterpagename=masterpage)
        doc.presentation.addElement(page)

        offsetx = (pagewidth - w)/2.0
        offsety = (pageheight - h)/2.0
        photoframe = Frame(stylename=photostyle, width='%fpt' % w, height='%fpt' % h,
                           x = '%fpt' % offsetx, y='%fpt' % offsety)
        page.addElement(photoframe)
        href = doc.addPicture(picture)
        photoframe.addElement(Image(href=href))

    if images_added > 0:
        logging.debug('Saving ODP as %s/%s' % (os.path.realpath('.'), odpfile))
        doc.save(odpfile)
    return (odpfile, images_added, ppt_content) if images_added > 0 else (False, 0, None)
Example #17
0
def create_cover(issuefile=None):
    if not lazylibrarian.IMP_CONVERT == 'None':  # special flag to say "no covers required"
        # create a thumbnail cover if there isn't one
        extn = os.path.splitext(issuefile)[1]
        if extn:
            coverfile = issuefile.replace(extn, '.jpg')
        else:
            logger.debug('Unable to create cover for %s, no extension?' %
                         issuefile)
            return
        if not os.path.isfile(coverfile):
            converter = lazylibrarian.MAGICK
            if len(lazylibrarian.IMP_CONVERT):
                converter = lazylibrarian.IMP_CONVERT
            logger.debug("Creating cover %s for %s using %s" %
                         (coverfile, issuefile, converter))
            try:
                # No PythonMagick in python3, hence allow wand, but more complicated
                # to install - try to use external imagemagick convert?
                # should work on win/mac/linux as long as imagemagick is installed
                # and config points to external "convert" program

                if len(lazylibrarian.IMP_CONVERT
                       ):  # allow external convert to override libraries
                    try:
                        params = [
                            lazylibrarian.IMP_CONVERT, issuefile + '[0]',
                            coverfile
                        ]
                        res = subprocess.check_output(params,
                                                      stderr=subprocess.STDOUT)
                        if res:
                            logger.debug('%s reports: %s' %
                                         (lazylibrarian.IMP_CONVERT, res))
                    except subprocess.CalledProcessError as e:
                        logger.debug(params)
                        logger.debug('ImageMagick "convert" failed %s' %
                                     e.output)

                elif lazylibrarian.MAGICK == 'wand':
                    with Image(filename=issuefile + '[0]') as img:
                        img.save(filename=coverfile)

                elif lazylibrarian.MAGICK == 'pythonmagick':
                    img = PythonMagick.Image()
                    img.read(issuefile + '[0]')
                    img.write(coverfile)
                else:
                    try:
                        params = [
                            lazylibrarian.MAGICK, issuefile + '[0]', coverfile
                        ]
                        res = subprocess.check_output(params,
                                                      stderr=subprocess.STDOUT)
                        if res:
                            logger.debug('%s reports: %s' %
                                         (lazylibrarian.IMP_CONVERT, res))
                    except subprocess.CalledProcessError as e:
                        logger.debug(params)
                        logger.debug('ImageMagick "convert" failed %s' %
                                     e.output)

            except:
                logger.debug("Unable to create cover for %s using %s" %
                             (issuefile, lazylibrarian.MAGICK))
    oldProcessedImages = [
        image for image in os.listdir(font) if image.endswith('_trim.png')
    ]
    for image in oldProcessedImages:
        os.remove(os.path.join(font, image))

    # for each glyph image, remove the background and trim the image
    images = [image for image in os.listdir(font) if image.endswith('.png')]
    # Define colors
    white = PM.Color("#ffffff")
    trans = PM.Color("#00000000")

    glyphProgBar = tqdm(total=len(images), desc='Glyphs', leave=False)
    for image in images:
        # Read the image
        glyphImage = PM.Image(os.path.join(font, image))
        # Remove the backgroundf
        glyphImage.transparent(white, False)
        # Trim the image
        glyphImage.trim()

        # If glyph is a Number resize it to 87 pixel height(35 for zero).
        # otherwise 58 pixel height.
        if os.path.splitext(image)[0].isnumeric():
            if os.path.splitext(image)[0] == '0': glyphImage.resize('x35')
            else: glyphImage.resize('x87')
        else:
            glyphImage.resize('x58')
        glyphImage.write(os.path.join(font, f'{image.split(".")[0]}_trim.png'))

        glyphProgBar.update(1)
Example #19
0
    color = []
    for i in colorString:
        color += [int(i)]
    for i in range(len(color)):
        color[i] = math.floor(color[i] / 255 * 65535)
    color1 = color[0:3]
    color2 = color[3:6]
    color3 = color[6:9]
    # -------------------------------------------------------------

    # ---------------get the base layer texture-------------------------------
    Scenes = pathwalk('.\SceneData\\')
    randomScene = random.choice(Scenes)
    randomScene = randomScene[0] + randomScene[1]

    randomSceneImage = PythonMagick.Image(randomScene)
    randomSceneGeo = PythonMagick.Geometry(randomSceneImage.size())
    widthRange = randomSceneGeo.width() - 100
    heightRange = randomSceneGeo.height() - 32

    cutGeo = PythonMagick.Geometry('100x32+' +
                                   str(random.randint(0, widthRange)) + '+' +
                                   str(random.randint(0, heightRange)))
    randomSceneImage.crop(cutGeo)
    # randomSceneImage.write('cutOutImage.jpg')
    # ------------------------------------------------------------------

    # --------create the base layer, base texture + base color----------
    baseImage = PythonMagick.Image(
        '100x32', PythonMagick.Color(color1[0], color1[1], color1[2]))
    # baseImage.write('baseColor.jpg')
Example #20
0
# -*- coding: utf-8 -*-
# !/usr/bin/python
# Create Date 2018/11/10 0010
__author__ = 'huohuo'
import os

pdf_path = '/tumor/facets_cval_50.pdf'
print os.path.exists(pdf_path)
import PythonMagick

p = 0

try:
    im = PythonMagick.Image(pdf_path)
    im.density('300')  #设置dpi,不设置估计就96dpi
    im.read(pdf_path + '[' + str(p) + ']')
    im.write('file_out-' + str(p) + '.png')
except:
    print "PythonMagick 产生错误:"
Example #21
0
            if len(nOrderID) != 16:
                nOrderID = ""
                sBarCode = ""
        else:
            print "Invalid scan: " + sBarCode

    # clean up
    del (image)

    return sBarCode


ClearFile()

#Use PythonMagik to convert the pdf to a tiff
img = PythonMagick.Image(argv[1])

# Try a raw return
print "raw check..."
img.write("test" + sFileExt)
sBC = GetBarcode("test" + sFileExt)

if sBC == "":
    print "enhance..."
    ClearFile()
    img.enhance()
    img.write("test" + sFileExt)
    sBC = GetBarcode("test" + sFileExt)

if sBC == "":
    print "sharpen..."
from pdfminer.pdfparser import PDFParser
from pdfminer.pdfdocument import PDFDocument
from pdfminer.pdfpage import PDFPage
from pdfminer.pdfpage import PDFTextExtractionNotAllowed
from pdfminer.pdfinterp import PDFResourceManager
from pdfminer.pdfinterp import PDFPageInterpreter
from pdfminer.pdfdevice import PDFDevice
from pdfminer.layout import LAParams
from pdfminer.converter import PDFPageAggregator
import pdfminer
import PythonMagick as pm

img = pm.Image()
img.density('1000')

img.read('nn041.pdf')
img.write('a.jpg')

img.write('b.png')

# # Open a PDF file.
# fp = open('express_religare.pdf', 'rb')

# # Create a PDF parser object associated with the file object.
# parser = PDFParser(fp)

# # Create a PDF document object that stores the document structure.
# # Password for initialization as 2nd parameter
# document = PDFDocument(parser)

# # Check if the document allows text extraction. If not, abort.
Example #23
0
time1 = time.time()

for i in range(10):
    word = python2access.randomWords()
    # ---------------generate background color----------------------------
    redQuantum = random.randint(0, 65525)
    greenQuantum = random.randint(0, 65535)
    blueQuantum = random.randint(0, 65535)

    # --------------------------------------------------------------------

    color = PythonMagick.Color(redQuantum, greenQuantum, blueQuantum)

    # -----------------create photo-----------------------
    img = PythonMagick.Image('100x32', color)
    img.xResolution = 96
    img.yResolution = 96
    # ----------------------------------------------------

    # ---------------------generate font-------------------------------------------------------------------
    fonts = pathwalk('D:\code\MC lab\\usingImageMagick\\fonts\\font_en\\')
    randomFont = random.choice(fonts)
    randomFont = randomFont[0] + randomFont[1]

    initialPointsize = 40

    img.font(randomFont)
    fontcolor = PythonMagick.Color(random.randint(0, 65535),
                                   random.randint(0, 65535),
                                   random.randint(0, 65535))
    conn = sqlite3.connect(dbFile)
except Exception as e:
    eprint(e)
    exit(1)

c = conn.cursor()
c.execute(selectQuery)
rows = c.fetchall()

os.chdir(imageFolder)

i = 1
for row in rows:
    imageFile = row[1].replace('\\','/')
    try:
        img = PythonMagick.Image(imageFile)
    except Exception as e:
        eprint(imageFile + ': ' + e)
        continue
    imageFile = img.fileName()
    if max(img.size().height(), img.size().width()) > thumbDimension :
        try:
            img.transform(transformStr)
        except RuntimeError as e:
            eprint(str(row[0]) + " " + imageFile + ": " + str(e))
    blob = PythonMagick.Blob()
    img.quality(jpgQuality)
    img.write(blob, "jpg")
    #workaround in order the access the data within the blob
    try:
        blobData = blob.data
Example #25
0
env = jinja2.Environment(loader=jinja2.FileSystemLoader('.'))
template = env.get_template('iaproofread03.jinja2')

#IA_NAME = 'windinwillows00grah'
#IA_NAME = 'artpracticeoftyp00gres'
#IA_NAME = 'manualoflinotype00merg'
IA_NAME = 'glimpsesofworldp00stod'

# must already exist
OUTPUT_FOLDER = 'iapr'

brittlefragments = pickle.load(open(os.path.join(OUTPUT_FOLDER, '%s_brittlefragments.pickle' % IA_NAME), 'rb'))
print '%d fully computed fragments' % len(brittlefragments)

for idx_fra, a in enumerate(brittlefragments):
    idx_obj, idx_reg, idx_par, idx_lin = [int(b) for b in a['name'].split('-')]

    # let's assume if the PNG exists, it's correct.  this may not be true!
    if not os.path.exists(os.path.join(OUTPUT_FOLDER, '%s.png' % a['name'])):
        jp2file = PythonMagick.Image(str(os.path.join('%s_jp2' % IA_NAME, '%s.jp2' % a['jp2name'])))
        jp2file.crop(a['geometrystring'])
        jp2file.write(os.path.join(OUTPUT_FOLDER, '%s.png' % a['name']))

    a['fragment']['unicodetext'] = cgi.escape(a['fragment']['text']).encode('utf8').decode('utf8')
    a['fragment']['unicodeinputtext'] = cgi.escape(a['fragment']['text'], quote=True).encode('utf8').decode('utf8')
    output_from_parsed_template = template.render(a=a)

    # to save the results
    with open(os.path.join(OUTPUT_FOLDER, '%s.html' % a['name']), 'wb') as fh:
        fh.write(output_from_parsed_template.encode('utf8'))
        #print patch_config

        for patch in patch_config['bills']:
            #input_file = './currency/' locality + '/' + bill + '.png'

            bill = patch['type']
            print 'processing: ' + bill

            if 'input' not in patch:
                in_file = bill + '.png'
            else:
                in_file = patch['input']

            input_file = './currency/' + locality + '/' + in_file
            image = Magick.Image(input_file)

            if 'width' not in patch:
                # Don't crop
                pass
            else:
                crop_string = str(patch['width']) + "x" + str(
                    patch['height']) + "+" + str(patch['left']) + "+" + str(
                        patch['top'])
                image.crop(crop_string)

            print "  - patch: " + patch['patch']
            #print image.fileName()
            #print image.magick()
            #print image.size().width()
            #print image.size().height()
Example #27
0
def createMagCover(issuefile=None, refresh=False):
    if not lazylibrarian.CONFIG['IMP_MAGCOVER']:
        return
    if issuefile is None or not os.path.isfile(issuefile):
        logger.debug('No issuefile %s' % issuefile)
        return

    base, extn = os.path.splitext(issuefile)
    if not extn:
        logger.debug('Unable to create cover for %s, no extension?' % issuefile)
        return

    coverfile = base + '.jpg'

    if os.path.isfile(coverfile):
        if refresh:
            os.remove(coverfile)
        else:
            logger.debug('Cover for %s exists' % issuefile)
            return  # quit if cover already exists and we didn't want to refresh

    logger.debug('Creating cover for %s' % issuefile)
    data = ''  # result from unzip or unrar
    extn = extn.lower()
    if extn in ['.cbz', '.epub']:
        try:
            data = zipfile.ZipFile(issuefile)
        except Exception as why:
            logger.error("Failed to read zip file %s, %s %s" % (issuefile, type(why).__name__, str(why)))
            data = ''
    elif extn in ['.cbr']:
        try:
            # unrar will complain if the library isn't installed, needs to be compiled separately
            # see https://pypi.python.org/pypi/unrar/ for instructions
            # Download source from http://www.rarlab.com/rar_add.htm
            # note we need LIBRARY SOURCE not a binary package
            # make lib; sudo make install-lib; sudo ldconfig
            # lib.unrar should then be able to find libunrar.so
            from lib.unrar import rarfile
            data = rarfile.RarFile(issuefile)
        except Exception as why:
            logger.error("Failed to read rar file %s, %s %s" % (issuefile, type(why).__name__, str(why)))
            data = ''
    if data:
        img = None
        try:
            for member in data.namelist():
                memlow = member.lower()
                if '-00.' in memlow or '000.' in memlow or 'cover.' in memlow:
                    if memlow.endswith('.jpg') or memlow.endswith('.jpeg'):
                        img = data.read(member)
                        break
            if img:
                with open(coverfile, 'wb') as f:
                    if PY2:
                        f.write(img)
                    else:
                        f.write(img.encode())
                return
            else:
                logger.debug("Failed to find image in %s" % issuefile)
        except Exception as why:
            logger.error("Failed to extract image from %s, %s %s" % (issuefile, type(why).__name__, str(why)))

    elif extn == '.pdf':
        generator = ""
        if len(lazylibrarian.CONFIG['IMP_CONVERT']):  # allow external convert to override libraries
            generator = "external program: %s" % lazylibrarian.CONFIG['IMP_CONVERT']
            if "gsconvert.py" in lazylibrarian.CONFIG['IMP_CONVERT']:
                msg = "Use of gsconvert.py is deprecated, equivalent functionality is now built in. "
                msg += "Support for gsconvert.py may be removed in a future release. See wiki for details."
                logger.warn(msg)
            converter = lazylibrarian.CONFIG['IMP_CONVERT']
            postfix = ''
            # if not os.path.isfile(converter):  # full path given, or just program_name?
            #     converter = os.path.join(os.getcwd(), lazylibrarian.CONFIG['IMP_CONVERT'])
            if 'convert' in converter and 'gs' not in converter:
                # tell imagemagick to only convert first page
                postfix = '[0]'
            try:
                params = [converter, '%s%s' % (issuefile, postfix), '%s' % coverfile]
                res = subprocess.check_output(params, stderr=subprocess.STDOUT)
                res = makeUnicode(res).strip()
                if res:
                    logger.debug('%s reports: %s' % (lazylibrarian.CONFIG['IMP_CONVERT'], res))
            except Exception as e:
                # logger.debug(params)
                logger.warn('External "convert" failed %s %s' % (type(e).__name__, str(e)))

        elif platform.system() == "Windows":
            GS = os.path.join(os.getcwd(), "gswin64c.exe")
            generator = "local gswin64c"
            if not os.path.isfile(GS):
                GS = os.path.join(os.getcwd(), "gswin32c.exe")
                generator = "local gswin32c"
            if not os.path.isfile(GS):
                params = ["where", "gswin64c"]
                try:
                    GS = subprocess.check_output(params, stderr=subprocess.STDOUT)
                    GS = makeUnicode(GS).strip()
                    generator = "gswin64c"
                except Exception as e:
                    logger.debug("where gswin64c failed: %s %s" % (type(e).__name__, str(e)))
            if not os.path.isfile(GS):
                params = ["where", "gswin32c"]
                try:
                    GS = subprocess.check_output(params, stderr=subprocess.STDOUT)
                    GS = makeUnicode(GS).strip()
                    generator = "gswin32c"
                except Exception as e:
                    logger.debug("where gswin32c failed: %s %s" % (type(e).__name__, str(e)))
            if not os.path.isfile(GS):
                logger.debug("No gswin found")
                generator = "(no windows ghostscript found)"
            else:
                # noinspection PyBroadException
                try:
                    params = [GS, "--version"]
                    res = subprocess.check_output(params, stderr=subprocess.STDOUT)
                    res = makeUnicode(res).strip()
                    logger.debug("Found %s [%s] version %s" % (generator, GS, res))
                    generator = "%s version %s" % (generator, res)
                    issuefile = issuefile.split('[')[0]
                    params = [GS, "-sDEVICE=jpeg", "-dNOPAUSE", "-dBATCH", "-dSAFER", "-dFirstPage=1", "-dLastPage=1",
                              "-dUseCropBox", "-sOutputFile=%s" % coverfile, issuefile]

                    res = subprocess.check_output(params, stderr=subprocess.STDOUT)
                    res = makeUnicode(res).strip()

                    if not os.path.isfile(coverfile):
                        logger.debug("Failed to create jpg: %s" % res)
                except Exception:  # as why:
                    logger.warn("Failed to create jpg for %s" % issuefile)
                    logger.debug('Exception in gswin create_cover: %s' % traceback.format_exc())
        else:  # not windows
            try:
                # noinspection PyUnresolvedReferences
                from wand.image import Image
                interface = "wand"
            except ImportError:
                try:
                    # No PythonMagick in python3
                    # noinspection PyUnresolvedReferences
                    import PythonMagick
                    interface = "pythonmagick"
                except ImportError:
                    interface = ""
            try:
                if interface == 'wand':
                    generator = "wand interface"
                    with Image(filename=issuefile + '[0]') as img:
                        img.save(filename=coverfile)

                elif interface == 'pythonmagick':
                    generator = "pythonmagick interface"
                    img = PythonMagick.Image()
                    # PythonMagick requires filenames to be bytestr, not unicode
                    if type(issuefile) is text_type:
                        issuefile = makeBytestr(issuefile)
                    if type(coverfile) is text_type:
                        coverfile = makeBytestr(coverfile)
                    img.read(issuefile + '[0]')
                    img.write(coverfile)

                else:
                    GS = os.path.join(os.getcwd(), "gs")
                    generator = "local gs"
                    if not os.path.isfile(GS):
                        GS = ""
                        params = ["which", "gs"]
                        try:
                            GS = subprocess.check_output(params, stderr=subprocess.STDOUT)
                            GS = makeUnicode(GS).strip()
                            generator = GS
                        except Exception as e:
                            logger.debug("which gs failed: %s %s" % (type(e).__name__, str(e)))
                        if not os.path.isfile(GS):
                            logger.debug("Cannot find gs")
                            generator = "(no gs found)"
                        else:
                            params = [GS, "--version"]
                            res = subprocess.check_output(params, stderr=subprocess.STDOUT)
                            res = makeUnicode(res).strip()
                            logger.debug("Found gs [%s] version %s" % (GS, res))
                            generator = "%s version %s" % (generator, res)
                            issuefile = issuefile.split('[')[0]
                            params = [GS, "-sDEVICE=jpeg", "-dNOPAUSE", "-dBATCH", "-dSAFER", "-dFirstPage=1",
                                      "-dLastPage=1", "-dUseCropBox", "-sOutputFile=%s" % coverfile, issuefile]
                            res = subprocess.check_output(params, stderr=subprocess.STDOUT)
                            res = makeUnicode(res).strip()
                            if not os.path.isfile(coverfile):
                                logger.debug("Failed to create jpg: %s" % res)
            except Exception as e:
                logger.warn("Unable to create cover for %s using %s %s" % (issuefile, type(e).__name__, generator))
                logger.debug('Exception in create_cover: %s' % traceback.format_exc())

        if os.path.isfile(coverfile):
            setperm(coverfile)
            logger.debug("Created cover for %s using %s" % (issuefile, generator))
            return

    # if not recognised extension or cover creation failed
    try:
        coverfile = safe_copy(os.path.join(lazylibrarian.PROG_DIR, 'data/images/nocover.jpg'), coverfile)
        setperm(coverfile)
    except Exception as why:
        logger.error("Failed to copy nocover file, %s %s" % (type(why).__name__, str(why)))
    return
Example #28
0
import PIL # sudo apt install -y python3-willow
resolution = PythonMagick.Geometry(width, height)
import time
import datetime
#composite -size 400x300 -resize 400x300 -gravity center time.svg canvas:white time.png
# from https://stackoverflow.com/a/6209894/5728815
import inspect
import os
filename = inspect.getframeinfo(inspect.currentframe()).filename
path = os.path.dirname(os.path.abspath(filename))
#print(path)

#while /bin/true; do ./clock.py ; sleep 60; done
make_clock.set_width(width)
make_clock.set_height(height)
palette = PythonMagick.Image(path + "/palette.png")

def setup(time = datetime.datetime.now()):
	#print("")
	#print(str(datetime.datetime.now()) + " setup(" + str(time) + ")")
	make_clock.generate_clock(time) # generates an svg file with a clockface of the given time
	image = PythonMagick.Image(path + "/time.svg")
	image.size(resolution)
	image.pixelColor(width//2, height//2, "red")
	image.map(palette)
	image.write(path + "/output.png")
	img = PIL.Image.new("P", (inky_display.WIDTH, inky_display.HEIGHT))
	img = PIL.Image.open(path + "/output.png")
	inky_display.set_image(img)
	#print(str(datetime.datetime.now()) + " setup() complete")
Example #29
0
# -*- coding: utf-8 -*-
import zipfile
import PythonMagick
img = PythonMagick.Image("E:\code\py\Annual\ico.png")
img.sample('100x100')
img.write(r'E:\code\py\Annual\001.ico')
# img.write('001.png')
# img.write('001.gif')
Example #30
0
import PythonMagick
n = 1
for i in range(n):
    image = PythonMagick.Image("{}.jpg".format(i))
    image.crop(PythonMagick.Geometry(1500, 1000, 0, 00)) # w, h, x, y
    image.write('{}.tooth.jpg'.format(i))