Exemplo n.º 1
0
def convert_pdf2img(file_name, file_path):
	pdf_im = pyPdf.PdfFileReader(open(file_name, "rb"))
	npage = pdf_im.getNumPages()
	for p in range(0, npage):
	    im = PythonMagick.Image()
	    im.density('200')
	    im.quality(80)
	    im.read(file_name+'['+ str(p) +']')
	    im.write(file_path+'/question' + str(p+1)+ '.jpg')
	
	img_array = sorted(glob.glob(file_path+"/*.jpg"), key=lambda name: int(name[name.find('question')+8:-4]))

	if(len(img_array) == 0):
	    err = Error("No Files To Convert!")
	    raise err

	return img_array
Exemplo n.º 2
0
def minify_cover(path):
    try:
        try:
            image = Image.open(path).convert('RGB')
        except:
            magick_image = PythonMagick.Image(path + '[0]')
            magick_image.write(path)
            image = Image.open(path).convert('RGB')
        width = image.size[0]
        if width > 600:
            new_width = 500
            new_height = int(float(new_width) * image.size[1] / width)
            image.thumbnail((new_width, new_height), Image.ANTIALIAS)
        ImageFile.MAXBLOCK = image.size[0] * image.size[1]
        image.save(path, 'JPEG', optimize=True, progressive=True)
    except:
        pass
Exemplo n.º 3
0
def gen_first_page_pdf():
    try:
        from pyPdf import PdfFileWriter, PdfFileReader
        inputpdf = PdfFileReader(open("/home/pylibs/TESTUPLOAD2.pdf", "rb"))
        output = PdfFileWriter()
        output.addPage(inputpdf.getPage(0))
        with open("/home/pylibs/first-page.pdf", "wb") as outputStream:
            output.write(outputStream)
        import PythonMagick
        img = PythonMagick.Image()
        img.read("/home/pylibs/first-page.pdf")
        print(str(img.size().width()) + "/" + str(img.size().height()))
        img.write("/home/pylibs/first-page.png")
        os.remove("/home/pylibs/first-page.pdf")
        return dict(result="success")
    except Exception as ex:
        return dict(error=ex.message + " on line: "+str(sys.exc_traceback.tb_lineno))
Exemplo n.º 4
0
def save_and_convert_image_upload(inputname):
    imgfile = request.files[inputname]
    if imgfile:
        if not allowed_file(imgfile.filename):
            raise UserWarning(
                "Uploaded image is not in the list of allowed file types.")
        filename = os.path.join(config.uploaddir,
                                secure_filename(imgfile.filename))
        imgfile.save(filename)
        img = PythonMagick.Image(filename)
        imgname = os.path.splitext(secure_filename(
            imgfile.filename))[0].replace('.', '_') + '.png'
        savedfilename = os.path.join(config.imagedir, imgname)
        img.write(savedfilename)
        os.remove(filename)
        return imgname
    return None
Exemplo n.º 5
0
def convertPDFtoImg(pdf, dest=None):
    try:
        import PythonMagick
        img = PythonMagick.Image()
        img.density('100')
        img.read(pdf)
        path, ext = os.path.splitext(pdf)
        img.write('%s.png' % path)

        if dest:
            os.rename('%s.png' % path, dest)
        else:
            return '%s.png' % path

    except:
        pass
    return dest
Exemplo n.º 6
0
def pdf2png(file_path, outdir,imageformat, max_page=None):

    import PythonMagick

    npage = pdf_num_page(file_path)
    if max_page and npage > max_page:
        npage = max_page
    print npage,'page'
    stime=time.time()
    for p in range(npage):
        im = PythonMagick.Image()
        im.density('200')
        im.read(file_path + '[{page}]'.format(page=p))
        im.write(os.path.join(outdir,'{page}.png'.format(page=p)))

    return npage
    print time.time()-stime
 def pdf_to_img(self): 
     """Convert pdf to png image
     """
     self.folder_name = "output_"+self.pdfFile
     if(not os.path.exists(self.folder_name)):
         os.makedirs(self.folder_name)
     img = PythonMagick.Image()
     img.density(self.density)
     my_file = PdfFileReader(file("{0}".format(self.pdfFile),"r"))
     self.numPages= my_file.getNumPages()
     for i in range(self.numPages):
         img.read("{0}[{1}]".format(self.pdfFile,i))
         #img.write("self.folder_name/{0}_image{1}.png".format(self.pdfFile,i))
         #img.write("{0}_image{1}.jpg".format(self.pdfFile,i))
         img.write(self.folder_name+"/page_"+str(i)+".png".format(self.pdfFile,i))
         
         #self.pdfImage = self.folder_name+"/page_"+str(i)+".png"
         self.pagelist.append(self.folder_name+"/page_"+str(i)+".png")
Exemplo n.º 8
0
def convertPDFtoImg(pdf, dest=None):
    try:
        import PythonMagick
        img = PythonMagick.Image()
        img.density('100')
        img.read('%s[0]' % pdf)
        path, ext = os.path.splitext(os.path.basename(pdf))
        img.write('PNG8:/convert/%s.png' % path)

        if dest:
            os.rename('/convert/%s.png' % path, dest)
        else:
            return '/convert/%s.png' % path

    except Exception as e:
        print(e)
        print('could not convert %s' % pdf)
    return dest
Exemplo n.º 9
0
def selectimagetest(request):
    ip = get_client_ip(request)
    widthImage = 1024.0
    heightImage = 768.0
    pathFix = setpath()
    path1 = str(pathFix + "/chequeApp/static/" + ip + "/abc.jpg")
    img = PythonMagick.Image(path1)
    img.read(path1)  # read in at 300 dpi
    imageSize = img.size()
    print "*******crop image", imageSize.height(
    ), "*****crop image", imageSize.width()
    crpImageHeight = imageSize.height() * 1.0
    crpImageWidth = imageSize.width() * 1.0
    widthRatio = crpImageWidth / widthImage
    heightRatio = crpImageHeight / heightImage
    print widthRatio, '*****', heightRatio

    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        x1 = float(request.POST['x1'])
        x2 = float(request.POST['x2'])
        y1 = float(request.POST['y1'])
        y2 = float(request.POST['y2'])
        mainImgPath = str(pathFix + "/chequeApp/static/" + ip + "/abc.jpg")
        img = Image.open(mainImgPath)
        print x1, y1, x2, y2
        imgCrop = img.crop((int(x1 * widthRatio), int(y1 * heightRatio),
                            int(x2 * widthRatio), int(y2 * heightRatio)))
        cropImgPath = str(pathFix + "/chequeApp/static/" + ip + "/abcCrop.jpg")
        imgCrop.save(cropImgPath)
        return render(request, 'chequeApp/imagetotextcopy.html', {
            'form': form,
            'ip': ip,
            'x1': x1,
            'y1': y1,
            'x2': x2,
            'y2': y2
        })
    else:
        form = DocumentForm()
        return render(request, 'chequeApp/imagetotextcopy.html', {
            'form': form,
            'ip': ip
        })
def pdf2imageextract(pdffilename, pages):
    pdf_im = pyPdf.PdfFileReader(file(pdffilename, "rb"))
    npage = pdf_im.getNumPages()  # It gives the number of pages in given input pdf file

    if int(pages) <= npage:
        for p in range(int(pages)):
            im = PythonMagick.Image()
            print type(im)
            im.density("300")
            im.read("{}[{}]".format(pdffilename, str(p)))  # format strings
            im.write("{0}{1}{2}".format("file_out-", str(p), ".png"))
            blob = PythonMagick.Blob()
            im.write(blob, "png")
            print blob.data
            print type(blob)
            data = PythonMagick.get_blob_data(blob)
            print type(data)
    else:
        print "Page Limit Exceeded"
Exemplo n.º 11
0
def saveImageFiles(image_file_list):
    """Serially labels all images by class:  and saves them to the designated tidy image directory."""
    counts = {'improbable':1,
                'possible':1,
                'probable':1,
                'unknown':1}
    csv_col_index = ['labeled_image', 'original_file_path']
    index = {}
    shutil.rmtree(TIDY_IMAGE_DIR, ignore_errors=True) # Deletes the directory containing any existing labeled images
    shutil.rmtree(INDEX_DIR, ignore_errors=True)
    if not os.path.exists(TIDY_IMAGE_DIR):
        os.makedirs(TIDY_IMAGE_DIR)
    for filename in image_file_list:
        if '.JPG'.casefold() in filename.casefold():
            save_name = updateNameCount(filename, counts)
            imageio.imwrite(save_name, np.array(Image.open(filename)))
            index[save_name] = filename
        if '.HEIC'.casefold() in filename.casefold():
            df = pd.read_csv(TRIMMED)
            for row in df.itertuples():
                image_name = row.file_name
                rating = row.likelihood_of_failure_rating
                if image_name == filename.split("Failure Images/",1)[1]:
                    save_name = updateNameCount(rating, counts)
                    PythonMagick.Image(filename).write(save_name) # convert .HEIC to .JPG
                    continue                    
            index[save_name] = filename
    if not os.path.exists(INDEX_DIR):
        os.makedirs(INDEX_DIR)
    with open(INDEX_LABELS, 'w', newline='') as f: # TODO: separate by tab not comma
        writer = csv.DictWriter(f, fieldnames=csv_col_index)
        writer.writeheader()
        for key in natsort.natsorted(index.keys()): # iterate through the alphanumeric keys in a natural order
            key_name = key.replace(TIDY_IMAGE_DIR,'')
            val_name = index[key]
            f.write("%s,%s\n"%(key_name,val_name))
    
    print('Number of improbable images:', counts['improbable']-1)    
    print('Number of possible images:', counts['possible']-1)
    print('Number of probable images:', counts['probable']-1)
    print('Number of unknown images:', counts['unknown']-1)
    print('Total number of classified images:', counts['improbable']+counts['possible']+counts['probable']-3)
def to_png(name):
    pdfname = name

    pdf = open(pdfname, "rb")
    pdf_im = PyPDF2.PdfFileReader(pdf)
    npage = pdf_im.getNumPages()
    print("Converting %d pages..." % npage)
    for p in range(npage):
        im = PythonMagick.Image()
        im.density('200')
        im.read(pdfname + "[" + str(p) + "]")
        # im.defineValue("png", "bit-depth", "8")
        im.defineValue("png", "format", "png24")
        im.defineValue("png", "color-type", "2")
        print("    Converting %d/%d of %s..." % (p + 1, npage, name))
        pngname = str(p + 1) + '.png'
        im.write(pngname)
    pdf.close()

    return npage
Exemplo n.º 13
0
 def pdf_to_img1(self, input_file,
                 density):  #give density in string format("200")
     img = PythonMagick.Image()
     img.density(density)
     input_file = str(input_file)
     my_file = PdfFileReader(file("{0}".format(input_file), "r"))
     numPages = my_file.getNumPages()
     basename = os.path.basename(input_file)
     for i in range(numPages):
         img.read("{0}[{1}]".format(input_file, i))
         img.alpha = False
         filename = "{0}{1}.png".format(basename, i)
         filename = os.path.join(ImageThread.working_dir, filename)
         filename1 = "{0}{1}new.png".format(basename, i)
         filename1 = os.path.join(ImageThread.working_dir, filename1)
         print(filename, filename1)
         img.write(filename)
         os.system("convert -flatten " + filename + " " + filename1)
         self.progress.emit(ResultObj(i, numPages))
     self.finished.emit(ResultObj(numPages, numPages))
Exemplo n.º 14
0
def pdf_to_jpg(pdffilename):

    pdf_im = PyPDF2.PdfFileReader(file(pdffilename, "rb"))
    npage = pdf_im.getNumPages()
    root_path = '/media/xian/tripitaka/ZC'
    vol = os.path.basename(pdffilename)[-7:-4]
    father_path = os.path.join(root_path, vol)
    if not os.path.isdir(father_path):
        os.makedirs(father_path)
    for p in range(npage):
        img = PythonMagick.Image(pdffilename + '[' + str(p) + ']')
        img.density('300')
        # geometry = img.size()
        # w, h = geometry.width(), geometry.height()
        # new_width = 1200
        # factor = new_width/float(w)
        # new_height = int(h * factor)
        # img.resize("{}x{}".format(new_width, new_height))
        #im.read(pdffilename + '[' + str(p) +']')
        img.write(os.path.join(father_path, str(p + 1) + '.jpg'))
Exemplo n.º 15
0
 def playpdf(self, ds):
     """
     split pdf file
     :param ds: (int) set ds = 1024 ~= 1MB output under my test
     :return: splited PNG image file
     """
     pages = PyPDF2.PdfFileReader(file(self.i_file, "rb")).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, e:
         print(str(e))
Exemplo n.º 16
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
        if '.' in issuefile:
            words = issuefile.split('.')
            extn = '.' + words[len(words) - 1]
            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 for %s using %s" % (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)
            except:
                logger.debug("Unable to create cover for %s using %s" % (issuefile, lazylibrarian.MAGICK))
Exemplo n.º 17
0
def Pdf2Pic(pdffilename, ds=128, start=0, end=None):
    """
    param pdffilename: (str) input pdf file (eg: "/home/file.pdf") 
    param ds: (int) set ds = 1024 ~= 1MB output under my test
    """

    pdf_im = PyPDF2.PdfFileReader(pdffilename)
    npage = pdf_im.getNumPages()

    df = os.path.splitext(pdffilename)
    dn = df[0].split('/')[-1]
    if not os.path.exists(dn):
        dirs = os.mkdir(dn)
    abspf = os.path.abspath(pdffilename)

    os.chdir(dn)
    if start is None:
        start = 0
    if end is None or end > npage:
        end = npage

    print('Converting %d pages.' % npage)
    atext = []
    im = PythonMagick.Image()
    im.density(str(ds))
    for p in range(start, end):
        #im = PythonMagick.Image(abspf + '[' + str(p) +']')
        #im.density(str(ds))
        im.read(abspf + '[' + str(p) + ']')
        im.magick("PNG")
        path = 'file_out-' + str(p) + '.png'
        im.write(path)
        atext.append(jsonTtext(path))
    os.chdir('../')
    d = '\n'.join(atext)
    f = open('temp.txt', 'w', encoding='utf8')
    f.write(d)
    f.close()
    return d
Exemplo n.º 18
0
def setup(time=datetime.datetime.now()):
    hhmm = "%02d%02d" % (time.hour, time.minute)
    #print(hhmm)
    svgfile = path + "/" + hhmm + ".svg"
    pngfile = path + "/" + hhmm + ".png"
    if not os.path.isfile(pngfile):
        if not os.path.isfile(svgfile):
            #print("")
            #print(str(datetime.datetime.now()) + " setup(" + str(time) + ")")
            make_clock.generate_clock(
                svgfile, time
            )  # generates an svg file with a clockface of the given time
            #print(str(datetime.datetime.now()) + " setup() midway 1")
            image = PythonMagick.Image(svgfile)
            #print(str(datetime.datetime.now()) + " setup() midway 2")
            image.resize(resolution)
            #print(str(datetime.datetime.now()) + " setup() midway 3")
            image.write(pngfile)
            #print(str(datetime.datetime.now()) + " setup() midway 4")
        global img
        img = PILImage.open(pngfile)
        img = img.convert('RGB')
Exemplo n.º 19
0
def convert_imageofpdf_2_jpg(pdfpath, jpgpath):
    input_stream = open(pdfpath, 'rb')
    pdf_input = PdfFileReader(input_stream,
                              strict=False)  # 获取一个 PdfFileReader 对象
    page_count = pdf_input.getNumPages()  # 获取 PDF的页数
    print('page numbers. ', page_count)
    #img = PythonMagick.Image()   # empty object first
    #img.density('300')           # set the density for reading (DPI); must be as a string

    for i in range(page_count):
        print('done.', i)
        #img.read(pdfpath + '[' + str(i) +']')     #分页读取 PDF
        #imgCustRes = PythonMagick.Image(img)  # make a copy
        #imgCustRes.sample('x1600')
        #imgCustRes.write(jpgpath+'/'+(C_JPGNAME%i))
        imgCustRes = PythonMagick.Image(pdf_input.getPage(i))
        #imgCustRes = PythonMagick.Image(pdfpath + '[' + str(i) +']')  # 分页读取 PDF
        imgCustRes.density('300')
        imgCustRes.write(jpgpath + '/' + 'pdf_1.jpg')

    print('all done')
    return page_count
Exemplo n.º 20
0
    def translate(self):
        imgFileVar = self.imgFile.get()
        if not os.path.exists(imgFileVar):
            messagebox.showerror(title='路径错误', message='图片路径未指定或不存在!')
            return
        icoFileVar = self.icoFile.get()
        if not icoFileVar:
            messagebox.showerror(title='路径错误', message='存储路径未指定!')
            return

        # 确保保存的文件的扩展名为.ico
        if not icoFileVar.endswith('.ico'):
            icoFileVar += '.ico'

        img = PythonMagick.Image(imgFileVar)

        size = self.size.get()
        if not self.scale.get():
            size = self.size.get() + '!'
        img.sample(size)
        img.write(icoFileVar)
        messagebox.showinfo(title='转换完成', message=f'文件保存于{icoFileVar}.')
Exemplo n.º 21
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')
Exemplo n.º 22
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)
Exemplo n.º 23
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,
Exemplo n.º 24
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")
Exemplo n.º 25
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
Exemplo n.º 26
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'))
Exemplo n.º 27
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'
Exemplo n.º 28
0
            paths.append([root, fn])
    return paths


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)
Exemplo n.º 29
0
import PythonMagick
import sys
image = PythonMagick.Image(sys.stdin)
print image.fileName()
print image.magick()
print image.size().width()
print image.size().height()
Exemplo n.º 30
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..."
Exemplo n.º 31
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')
Exemplo n.º 32
0
#!/usr/bin/python
import PythonMagick as pm



# Read the image
img = pm.read('temp.jpg')

img.display()