예제 #1
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)
예제 #2
0
파일: views.py 프로젝트: aki9762/myapp
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")
예제 #3
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)
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
예제 #5
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')
예제 #6
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
예제 #7
0
파일: app.py 프로젝트: Chipsnet/mineshot-py
    def on_created(self, event):
        filepath = event.src_path
        filename = os.path.basename(filepath)

        print('newfile: ' + filepath)

        time.sleep(1)
        Image(filepath).write("clipboard:")
예제 #8
0
    def __init__(self, filename, i):
        self.image = Image()
        self.image.density('%d' % DENSITY)
        self.image.read('%s[%d]' % (filename, i))

        temp = tempfile.NamedTemporaryFile(suffix='.png')
        self.image.write(temp.name)
        self.pimage = pygame.image.load(temp.name)
        temp.close()
예제 #9
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)
예제 #10
0
파일: gettags.py 프로젝트: offbyone/cjb
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)
예제 #11
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")
예제 #12
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")
예제 #13
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)
예제 #14
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)
예제 #15
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))
예제 #16
0
    def thumbnail(self, infile, outfile, size, quality, no_upscale=False):
        #image = Image(infile)
        #image.resize(size)
        #image.write(outfile)

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

        return { 'width': image.size().width(), \
                 'height': image.size().height() }
예제 #17
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)
예제 #19
0
def pdf_page_to_png(
    src_pdf,
    pagenum=0,
    resolution=72,
):
    """
    Returns specified PDF page as wand.image.Image png.
    :param PyPDF2.PdfFileReader src_pdf: PDF from which to take pages.
    :param int pagenum: Page number to take.
    :param int resolution: Resolution for resulting png in DPI.
    """
    dst_pdf = PyPDF2.PdfFileWriter()
    dst_pdf.addPage(src_pdf.getPage(pagenum))

    pdf_bytes = io.BytesIO()
    dst_pdf.write(pdf_bytes)
    pdf_bytes.seek(0)

    img = Image(pdf_bytes, resolution=resolution)
    img.convert("png")

    return img
예제 #20
0
파일: clipmage.py 프로젝트: Jubjub/clipmage
def screenshot(word, word_eol, userdata):
    try:
        Image("clipboard:").write("PNG32:clipmage.png")
    except RuntimeError:
        xchat.prnt('no image in the clipboard')
        return xchat.EAT_ALL
    response = cStringIO.StringIO()
    c = pycurl.Curl()
    values = [("key", "37c8847d8ce46eb4bb4175ad4573441b"),
              ("image", (c.FORM_FILE, "clipmage.png"))]
    c.setopt(c.URL, "http://api.imgur.com/2/upload.xml")
    c.setopt(c.HTTPPOST, values)
    c.setopt(c.WRITEFUNCTION, response.write)
    c.perform()
    c.close()
    os.remove('clipmage.png')
    try:
        xchat.command(
            'say %s' %
            response.getvalue().split('<original>')[1].split('</original>')[0])
    except IndexError:
        xchat.prnt('couldn\'t upload the image')
    return xchat.EAT_ALL
예제 #21
0
    def convert_directory_to_tiff(source, destination,
                                  remove_source_directory):
        """This method converts a directory containing bitmaps to tiffs and stores them in a new location. PythonMagick
        is used in the process of conversion the resulting images are uncompressed and are of the same size as the
        original bitmaps therefore implying loss-less conversion

        remove_source_directory takes 'yes' or 'no'
        """
        if remove_source_directory == 'yes' or 'no':
            list_of_files_in_the_directory = os.listdir(source)
            for files in list_of_files_in_the_directory:
                name, ext = os.path.splitext(files)
                if ext.lower() == '.bmp':
                    Image(os.path.join(source, files)).write(
                        os.path.join(source, name + str('.tiff')))
            refresh_list = os.listdir(source)
            tiff_folder = os.path.join(
                destination,
                datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S'))
            TIFFManipulation.recent_converted_directory = tiff_folder
            os.mkdir(tiff_folder)
            for tiffs in refresh_list:
                name, ext = os.path.splitext(tiffs)
                if ext.lower() == '.tiff':
                    shutil.move(os.path.join(source, tiffs),
                                os.path.join(tiff_folder, tiffs))
            if remove_source_directory == 'yes':

                def on_rm_error(func, path, exc_info):
                    # path contains the path of the file that couldn't be removed
                    # let's just assume that it's read-only and unlink it.
                    os.chmod(path, stat.S_IWRITE)
                    os.unlink(path)

                shutil.rmtree(source, onerror=on_rm_error)
        else:
            print "The third argument is either the string 'yes' or 'no'"
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'))
예제 #23
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")
예제 #24
0
pdfname='??'
DPI='85'
APP_ID='??'
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=[]
예제 #25
0
# print datetime.now() - start_time

from wand.image import Image
from PIL import Image as PI
import sys
import os
from pyocr import pyocr
from pyocr import builders
import io
#TESSERACT_CMD = os.environ["TESSDATA_PREFIX"] + os.sep + 'tesseract.exe' if os.name == 'nt' else 'tesseract'

tool = pyocr.get_available_tools()[0]
print tool
lang = tool.get_available_languages()
print lang
req_image = []
final_text = []

image_pdf = Image(file="test_pf.pdf", resolution=300)
image_jpeg = image_pdf.convert('jpeg')

for img in image_jpeg.sequence:
    img_page = Image(image=img)
    req_image.append(img_page.make_blob('jpeg'))

for img in req_image:
    txt = tool.image_to_string(PI.open(io.BytesIO(img)),
                               lang=lang,
                               builder=pyocr.builders.TextBuilder())
    final_text.append(txt)
예제 #26
0
        dir, fname = os.path.split(_pdf_path)
        base, ext = os.path.splitext(fname)
        out_base, _ = os.path.splitext(_pdf_path)

        # convert the pdf file to the jpg images
        command = 'pdftoppm %s %s -jpeg' % (_pdf_path.replace(
            ' ', '\ '), out_base.replace(' ', '\ '))
        os.system(command)

        paths = []
        # convert the jpg files to the list of cv image
        for f in os.listdir(dir):
            path = os.path.join(dir, f)
            if os.path.exists(path) and f.find(
                    base) != -1 and os.path.splitext(f)[1].find('jpg') != -1:
                paths.append(path)

        return paths


if __name__ == '__main__':
    import os, PythonMagick
    from PythonMagick import Image
    from datetime import datetime

    bg_colour = "#ffffff"
    input_pdf = pdf_dir + "\\" + pdf
    img = Image()
    img.density('300')
    img.read(input_pdf)
예제 #27
0
# -*- coding: utf-8 -*-
# @Time    : 2021/1/14
# @Author  : jhh
# @File    : readpdf1.py
# @Software: PyCharm
# import pdfminer
# import pdfplumber
# import pandas as pd

# path = r'2.pdf'
# with pdfplumber.open(path) as pdf:
#     first_page = pdf.pages[0]  # 获取第一页
#     print(first_page.extract_text())
# print(1)

from PythonMagick import Image
import cv2 as cv

with Image(filename=r'E:\work\segmentation\2.pdf') as img:
    with img.convert('jpeg') as converted:
        converted.save(filename='image.jpeg')
예제 #28
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")
예제 #29
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")
예제 #30
0
#Fails 231.py
#Autors Reinis Prockans

from PythonMagick import Image

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

#Izgatavojam mainigos x un y
x = y = 0

#Uzstada objekta 'bilde' x,y pixela krasu
bilde.pixelColor(1, 13, "#eeff22")
bilde.pixelColor(1, 14, "#eeff22")
bilde.pixelColor(1, 15, "#eeff22")
bilde.pixelColor(1, 16, "#eeff22")
bilde.pixelColor(1, 17, "#eeff22")
bilde.pixelColor(1, 18, "#eeff22")
bilde.pixelColor(1, 19, "#eeff22")
bilde.pixelColor(1, 20, "#eeff22")
bilde.pixelColor(2, 13, "#eeff22")
bilde.pixelColor(3, 13, "#eeff22")
bilde.pixelColor(4, 13, "#eeff22")
bilde.pixelColor(5, 13, "#eeff22")
bilde.pixelColor(5, 14, "#eeff22")
bilde.pixelColor(5, 15, "#eeff22")
bilde.pixelColor(5, 16, "#eeff22")
bilde.pixelColor(4, 16, "#eeff22")
bilde.pixelColor(3, 16, "#eeff22")
bilde.pixelColor(2, 16, "#eeff22")