예제 #1
0
def bend(img: Image):
    resize(img)
    img.alpha_channel = False
    img.virtual_pixel = "transparent"
    img.distort(method="plane_2_cylinder", arguments=[90])

    return img
예제 #2
0
    def get_thumbnail_from_pdf(self, file):
        try:
            filename = file.name
            img = None

            # Convert PDF files
            imgs_pdf = Image(file=file)
            imgs = imgs_pdf.convert('jpeg')

            if imgs:
                img = Image(image=imgs.sequence[0])
                img.background_color = Color('white')
                img.alpha_channel = 'remove'

                # resized and save the converted file
                img.transform(crop='', resize=THUMBNAIL_SIZE)
                img.thumbnail()

                temp = NamedTemporaryFile(delete=False)
                temp.flush()
                temp0 = File(temp)

                with temp0.open('wb') as f:
                    img.save(file=f)

                return temp0.open('rb')

        except Exception as e:
            print(repr(e))

        return None
예제 #3
0
파일: debug.py 프로젝트: stefanw/pdfcutter
 def get_image(self, page_no):
     filename = "{}[{}]".format(self.filename, page_no - 1)
     img = Image(filename=filename,
                 resolution=self.resolution,
                 background=Color('#fff'))
     img.alpha_channel = False
     return img
예제 #4
0
def vaporwave(img: Image):
    resize(img)
    img.alpha_channel = False
    img.function('sinusoid', [3, -90, 0.2, 0.7])
    img.modulate(saturation=25, brightness=75)

    return img
예제 #5
0
def _lsd(img: Image):
    _magic(img)
    img.alpha_channel = False
    img.function('sinusoid', [3, -90, 0.2, 0.7])
    img.modulate(saturation=200, brightness=75)

    return img
예제 #6
0
def edge(img: Image):
    resize(img)
    img.alpha_channel = False
    img.transform_colorspace('gray')
    img.edge(2)

    return img
예제 #7
0
파일: cron.py 프로젝트: jasonvank/variora
def _generate_thumbnail_image_content_file(document):
    content = None

    if document.file_on_server:
        content = document.unique_file.file_field.read()
    else:
        with requests.request('get', document.external_url,
                              stream=True) as response:
            content = response.content

    temp_pdf_path = os.path.join(settings.MEDIA_ROOT, 'document_thumbnails',
                                 'temp.pdf')
    with open(temp_pdf_path, 'w+') as f:
        f.write(content)

    reader = PdfReader(temp_pdf_path)

    if len(reader.pages) > 1:
        page = reader.pages[0]
        writer = PdfWriter()
        writer.addpage(page)
        writer.write(temp_pdf_path)

    images = Image(filename=temp_pdf_path, resolution=38)
    images.background_color = Color('white')
    images.alpha_channel = 'flatten'
    os.remove(temp_pdf_path)
    return ContentFile(images.make_blob('jpg'))
예제 #8
0
파일: app.py 프로젝트: fyttyf/tikz_WEB
def _run_convert(filename, page, res=120):
    idx = page + 1
    temp_time = time.time() * 1000
    # 由于每次转换的时候都需要重新将整个PDF载入内存,所以这里使用内存缓存
    pdfile = getPdfReader(filename)
    pageObj = pdfile.getPage(page)
    dst_pdf = PdfFileWriter()
    dst_pdf.addPage(pageObj)

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

    img = Image(file=pdf_bytes, resolution=res)
    img.format = 'png'
    img.compression_quality = 90

    img.background_color = Color('white')
    img.alpha_channel = 'remove'
    #img.channels = 'rgb_channels'
    # 保存图片
    #filename[:filename.rindex('.')]
    img_path = './image/%s.png' % (filename[filename.rindex('/pdf/') +
                                            5:filename.rindex('.pdf')])
    #)
    img.save(filename=img_path)
    img.destroy()
    img = None
    pdf_bytes = None
    dst_pdf = None
예제 #9
0
def createAndStoreThumbnail(**kwargs):

    # fileDirectory = "/home/akshat/Desktop/"
    # inFileName="test_doc_2.pdf"
    # outFileName="myOutputfile.jpg"
    imageFromPdf = Image(filename=kwargs["fileLocation"] + kwargs["fileName"])
    # pages = len(imageFromPdf.sequence)
    # print(pages)

    # creates an empty Image.
    image = Image(width=imageFromPdf.width, height=imageFromPdf.height)

    # resize the empty image
    image.sample(470, 330)

    #superimpose on the empty image the argument given, at the position specified
    image.composite(imageFromPdf.sequence[0], top=0, left=0)
    image.background_color = Color("white")
    image.alpha_channel = 'remove'
    # for i in range(pages):
    # 	image.composite(
    #  		imageFromPdf.sequence[i],
    #  		top=imageFromPdf.height * i,
    #  		left=0
    # 	)

    image.format = "jpg"
    image.save(filename=kwargs["imageLocation"] + kwargs["imageName"] + ".jpg")
    return kwargs["imageName"] + ".jpg"
    # display(image)
예제 #10
0
def cube(image: Image):
    """Make a 3D cube out of the image."""
    def s(x):
        return int(x / 3)

    image.resize(s(1000), s(860))
    image.format = "png"
    image.alpha_channel = 'opaque'

    image1 = image
    image2 = Image(image1)

    out = Image(width=s(3000 - 450), height=s(860 - 100) * 3)
    out.format = "png"

    image1.shear(background=Color("none"), x=-30)
    image1.rotate(-30)
    out.composite(image1, left=s(500 - 250), top=s(0 - 230) + s(118))
    image1.close()

    image2.shear(background="rgba(0,0,0,0)", x=30)
    image2.rotate(-30)
    image3 = Image(image2)
    out.composite(image2, left=s(1000 - 250) - s(72), top=s(860 - 230))
    image2.close()

    image3.flip()
    out.composite(image3, left=s(0 - 250) + s(68), top=s(860 - 230))
    image3.close()

    out.crop(left=80, top=40, right=665, bottom=710)

    return out
예제 #11
0
def image_labels_to_countable_npy():
    _user = User.objects.filter(username='******')[0]
    _labeler = Labeler.objects.filter(user=_user)[0]
    labels = ImageLabel.objects.filter(labeler=_labeler)
    foldername = 'npy'

    for label in labels:
        parent_image = label.parentImage
        filename = '%s' % parent_image.name.replace('.JPG', '')
        outputFilenameNpy = (settings.STATIC_ROOT +
                             settings.LABEL_FOLDER_NAME + foldername + '/' +
                             filename + '.npy')
        categorylabels = label.categorylabel_set.all()
        height = parent_image.height
        width = parent_image.width
        total_paths = 254
        masks_ndarray = np.zeros((total_paths, height, width))
        ctr = 0

        for cat_id, categorylabel in enumerate(categorylabels):
            svg = categorylabel.labelShapes
            paths = []
            poly = []
            paths = re.findall(SVGRegex.rePath, svg)
            poly = re.findall(SVGRegex.rePolygon, svg)
            shapes = paths + poly
            if len(paths) + len(poly) > 0:
                for idx, path in enumerate(shapes):
                    print(ctr, cat_id, idx, path)
                    img = WandImage(blob=image_string_to_SVG_string_file(
                        image_label_string_to_SVG_string(path, height, width)))
                    img.resize(width, height)
                    img.background_color = WandColor('white')
                    img.alpha_channel = 'remove'
                    img.negate()
                    img.threshold(0)
                    img.format = 'png'
                    if not os.path.exists(settings.STATIC_ROOT +
                                          settings.LABEL_FOLDER_NAME +
                                          foldername):
                        os.makedirs(settings.STATIC_ROOT +
                                    settings.LABEL_FOLDER_NAME + foldername)
                    outputFilename = (settings.STATIC_ROOT +
                                      settings.LABEL_FOLDER_NAME + foldername +
                                      '/' + filename + '_' + str(idx) + '_' +
                                      str(ctr) + IMAGE_FILE_EXTENSION)
                    img.save(filename=outputFilename)
                    im = imageio.imread(outputFilename)
                    masks = np.array(im)
                    category_id = categorylabel.categoryType_id
                    cat_mask = np.where(masks == 255, category_id, masks)
                    masks_ndarray[ctr, :, :] = cat_mask
                    ctr = ctr + 1
            else:
                print(ctr, cat_id, 0, 'EMPTY')
        masks_ndarray.resize(ctr, height, width)
        print(masks_ndarray.shape)
        np.save(outputFilenameNpy, masks_ndarray)
예제 #12
0
    def upload_from_web(self, request, pk=None):
        from wand.image import Image
        from wand.color import Color
        from wand import exceptions as wand_exceptions
        from apps.group.models import CourseGroup, CourseGroupMember

        chatroom = self.get_object()
        try:
            chatroom_member = ChatroomMember.objects.get(chatroom=chatroom, user=request.user)
        except ChatroomMember.DoesNotExist:
            # Create the course group member (is past)
            course_group = CourseGroup.objects.get(chatroom=chatroom)
            course_group_member = CourseGroupMember.objects.create(course_group=course_group, student=request.user.student, is_past=True)

            # Create the chatroom member (is past)
            chatroom_member = ChatroomMember.objects.create(user=request.user, chatroom=chatroom, is_past=True)

        name = request.data.get('name')
        is_anonymous = int(request.data.get('is_anonymous', False))
        tag = Tag.objects.get(pk=int(request.POST.get('tag_id')))

        new_upload = Upload.objects.create(chatroom_member=chatroom_member, chatroom=chatroom, name=name, tag=tag, is_anonymous=is_anonymous)
        all_urls = ""

        for fp in request.FILES:
            uploadedFile = request.data.get(fp)
            if uploadedFile.content_type == "application/pdf":
                image_pdf = Image(file=uploadedFile, resolution=250, background=Color("white"))
                image_jpeg = image_pdf.convert('jpeg')
                count = 0
                for single_img in image_jpeg.sequence:
                    img = Image(image=single_img, resolution=250)
                    temp = tempfile.TemporaryFile()
                    img.alpha_channel = False
                    img.save(file=temp)
                    url = new_upload.upload_file(temp)
                    temp.close()
                    all_urls = all_urls + url + "\n"
                    count += 1
                    if count >= 25:
                        break
                break
            url = new_upload.upload_file(uploadedFile)
            all_urls = all_urls + url + "\n"

        activity_type = ChatroomActivityType.objects.get_activity_type(ChatroomActivityTypeManager.UPLOAD)
        activity = ChatroomActivity.objects.create(chatroom=chatroom, chatroom_activity_type=activity_type, activity_id=new_upload.pk)
        new_upload.send_created_notification(activity, request, True)

        # post to slack TODO add detail
        message = request.user.email + " uploaded files to " + chatroom.name + ":\n[" + str(new_upload.id) + "] " + all_urls
        slack_utils.send_simple_slack_message(message)

        return Response(200)
예제 #13
0
def pagify_pdf(fname):
    """Create a PNG image for each page of a PDF document"""
    all_pages = Image(filename=fname+'.pdf', resolution=250)
    count = 1
    for page in all_pages.sequence:
        img = Image(page)
        img.format = 'png'
        img.background_color = Color('white')
        img.alpha_channel = 'remove'
        img.save(filename=fname+str(count)+'.png')
        count += 1
    return count - 1
예제 #14
0
파일: CourseCreator.py 프로젝트: tcc25/AutO
 def makeKmzFile(self,filename,title):
     '''Produce the MapRun map, as a georeferenced JPG image in a KMZ file.'''
     if self.aspect == "landscape":
         ss = "style=streeto|paper=0.297,0.210|scale=10000|centre="
     else:
         ss = "style=streeto|paper=0.210,0.297|scale=10000|centre="
     mp = self.getMidpoint().getEPSG3857()
     ss += str(int(mp[1])) + "," + str(int(mp[0])) + "|title="+title+"|club=|mapid=|start="
     ss += str(int(self.startFinish.getEPSG3857()[1])) + "," + str(int(self.startFinish.getEPSG3857()[0]))
     ss += "|crosses=|controls="
     #TODO Remove controls from request for actual MapRun map
     ss += ",".join([str(control.getNumber()) + ",45," + str(int(control.getEPSG3857()[1])) + "," + str(
         int(control.getEPSG3857()[0])) for control in self.getControls()])
     r = requests.get(PDF_SERVER+"/pdf/?"+ss)
     pdfFile = tempfile.NamedTemporaryFile(delete=False)
     for chunk in r.iter_content(chunk_size=128):
         pdfFile.write(chunk)
     pdfFile.close()
     with Image(filename=pdfFile.name, resolution=180) as img_pdf:
         img = Image(image=img_pdf.sequence[0])
         img.background_color = Color('white')
         img.alpha_channel = 'remove'
         img.format = "jpeg"
         img.save(filename=pdfFile.name+".jpg")
     kml = Element("kml", {"xmlns": "http://www.opengis.net/kml/2.2"})
     document = SubElement(kml, "Document")
     folder = SubElement(document, "Folder")
     groundOverlay = SubElement(folder, "GroundOverlay")
     name=SubElement(groundOverlay,"name")
     name.text="tile.jpg"
     drawOrder=SubElement(groundOverlay,"drawOrder")
     drawOrder.text="75"
     icon=SubElement(groundOverlay,"Icon")
     href=SubElement(icon,"href")
     href.text="files/tile.jpg"
     latLonBox=SubElement(groundOverlay,"LatLonBox")
     north=SubElement(latLonBox,"north")
     north.text=str(self.topLeft.getLat())
     south=SubElement(latLonBox,"south")
     south.text=str(self.bottomRight.getLat())
     east=SubElement(latLonBox,"east")
     east.text=str(self.bottomRight.getLon())
     west=SubElement(latLonBox,"west")
     west.text=str(self.topLeft.getLon())
     rotation=SubElement(latLonBox,"rotation")
     rotation.text="0.0"
     docKmlFile = tempfile.NamedTemporaryFile(delete=False)
     docKmlFile.write(tostring(kml))
     docKmlFile.close()
     with zipfile.ZipFile(filename,"w") as kmzFile:
         kmzFile.write(docKmlFile.name,"doc.kml")
         kmzFile.write(pdfFile.name+".jpg","files/tile.jpg")
예제 #15
0
def convert_pdf_to_png(filenameVal):
    pdf = Image(filename=filenameVal, resolution=200)

    pages = len(pdf.sequence)

    image = Image(width=pdf.width, height=pdf.height * pages)

    for i in xrange(pages):
        image.composite(pdf.sequence[i], top=pdf.height * i, left=0)
    image.background_color = Color("white")
    image.alpha_channel = 'remove'
    image.save(filename="out.png")
    return remove_points_from_image(filenameVal)
예제 #16
0
def floor(img: Image):
    resize(img, 128)
    img.alpha_channel = False
    img.background_color = Color("light-blue")
    img.virtual_pixel = "tile"

    img.distort(
        method="perspective",
        arguments=[0, 0, 20, 61, 90, 0, 70, 63, 0, 90, 0, 83, 90, 90, 85, 88])

    resize(img, 512)

    return img
예제 #17
0
def _floor(img: Image):
    x, y = img.size

    img.alpha_channel = False
    img.background_color = Color("#81cfe0")
    img.virtual_pixel = "tile"

    img.distort(
        method="perspective",
        arguments=[0, 0, 20, 61, 90, 0, 70, 63, 0, 90, 0, 83, 90, 90, 85, 88])

    img.resize(x, y)

    return img
예제 #18
0
파일: utils.py 프로젝트: jma/rerodoc-app
def generate_thumbnail(filename, outfilename=None):
    """Generate a thumnail for a given pdf filename."""
    img = Image(filename=filename + '[0]', resolution=20)

    try:
        img.alpha_channel = 'off'
        img.transform(resize='150x150>')

    except:
        error('image generation failed')
        return None
    if outfilename:
        return img.save(filename=outfilename)
    return img
예제 #19
0
def toPNG(filePath, xResScale=220, yResScale=220):
    # converts a pdf to GIF
    # for each page, say og file is Goldenrod_Full.pdf
    # output will be Goldenrod_Full-0.png, Goldenrod_Full-1.png

    img = Image(filename=filePath, resolution=400)

    if len(img.sequence) == 1:

        # whole file as 1 page for now
        img.format = 'png'
        img.background_color = Color('white')
        img.alpha_channel = 'remove'

        # image resolution scale adjustment for display
        img.resample(x_res=xResScale, y_res=yResScale)

        # saving
        img.save(filename=filePath[:-4] + '.png')

    else:  # multipage image

        for i in range(len(img.sequence)):
            indiv = Image(image=img.sequence[i], resolution=400)
            indiv.format = 'png'
            indiv.background_color = Color('white')
            indiv.alpha_channel = 'remove'

            # adjust resolution for display
            indiv.resample(x_res=xResScale, y_res=yResScale)

            # save it
            indiv.save(filename=filePath[:-4] + '-' + str(i) + '.png')

    # returns number of pages converted
    return len(img.sequence)
예제 #20
0
def toGIF(filePath, xResScale=220, yResScale=220):
    # converts a pdf to PNG
    # beware when converting to multiple pages, it might become an
    # animated GIF

    img = Image(filename=filePath, resolution=400)

    if len(img.sequence) == 1:

        # whole file as 1 page for now
        img.format = 'gif'
        img.background_color = Color('white')
        img.alpha_channel = 'remove'

        # image resolution scale adjustment for display
        img.resample(x_res=xResScale, y_res=yResScale)

        # saving
        img.save(filename=filePath[:-4] + '.gif')

    else:  # multipage image

        for i in range(len(img.sequence)):
            indiv = Image(image=img.sequence[i], resolution=400)
            indiv.format = 'gif'
            indiv.background_color = Color('white')
            indiv.alpha_channel = 'remove'

            # adjust resolution for display
            indiv.resample(x_res=xResScale, y_res=yResScale)

            # save it
            indiv.save(filename=filePath[:-4] + '-' + str(i) + '.gif')

    # returns number of pages converted
    return len(img.sequence)
예제 #21
0
def resize_image(path, width, height):
    with WAND_LOCK.reader_lock, Image(width=width, height=height) as bg:
        # Resize our input image.
        with Image(filename=path, resolution=300) as s:
            d = Image(s.sequence[0])
            d.background_color = Color("white")
            d.alpha_channel = 'remove'
            d.transform(resize='%ix%i>' % (width, height))
            # Offset input image on top of background.
            left = (bg.width - d.width) // 2
            top = (bg.height - d.height) // 2
            bg.composite(d, left, top, operator='over')

        with tempfile.NamedTemporaryFile(delete=False, suffix='.gif') as t:
            bg.save(filename=t.name)
            return t.name
예제 #22
0
def resize_img(file1, content):
    img = WandImage(filename=file1)
    if (img.width > 1920):
        img.resize(width=1920)
    if (img.height > 1080):
        img.resize(height=1080)
    img.format = "png"
    stream_out = six.BytesIO()
    img.alpha_channel = 'remove'
    img.save(file=stream_out)
    picture = Image()
    picture.content = content
    picture.image.save(name="content" + str(content.pk) + ".png",
                       content=stream_out)
    picture.save()
    os.remove(file1)
예제 #23
0
def writeImageNoWarp(pdf, out, resolution=pdfDense, trim=True):
    with Image(filename=pdf, resolution=resolution) as pdf:

        pages = len(pdf.sequence)
        height = 0
        width = 0
        for j in range(pages):
            ## Go through the sequence and trim them individually
            with pdf.sequence.index_context(j):
                if trim:
                    pdf.trim()
                    height += pdf.height + 10
                    if (width < pdf.width):
                        width = pdf.width
                else:
                    width = pdf.width
                    height = pdf.height

        i = Image(width=width, height=height)

        height = [r.height for r in pdf.sequence]
        height = height[::-1]
        height.append(0)
        height = height[::-1]
        width = [math.floor((width - r.width) / 2) for r in pdf.sequence]

        for j in range(pages):
            i.composite(pdf.sequence[j], top=height[j] + j * 10, left=width[j])
        i.background_color = Color('white')  # Set white background.
        i.alpha_channel = 'remove'
        if trim:  ## This is necessary because of stacked charts (above)
            i.trim()
        i.sharpen(radius=5.0, sigma=5.0)
        i.normalize()
        i.quantize(16, dither=False)
        i.compression_quality = 00
        i.save(filename=out.replace(".png", ".png8"))
        tmp = out.replace(".png", "") + "*"
        #out = glob.glob(tmp)
        if (os.system("rename .png8 .png %s*" % tmp)):
            print("Error in saving file.")
        if (os.system("optipng -quiet %s*" % tmp)):
            print("Error in optipng.")
        commstr = 'cwebp -quiet -lossless -z 9 -metadata exif %s -o %s' % (
            out, out.replace(".png", ".webp"))
        if (os.system(commstr)):
            print("Error in cwebp")
예제 #24
0
def read_image(image_path : str, dpi=300):
    assert os.path.exists(image_path)
    image_list = []
    if image_path.endswith(".pdf"):
        with WandImage(filename=image_path, resolution=dpi) as img:
            for page_img_seq in img.sequence:
                page_img = WandImage(page_img_seq)
                page_img.background_color = Color('white')
                page_img.alpha_channel = 'remove'
                img_buffer = np.asarray(bytearray(page_img.make_blob(format='jpeg')), dtype=np.uint8)
                if img_buffer is not None:
                    image_list.append(imdecode(img_buffer, IMREAD_COLOR))
    elif image_path.endswith(".png") or image_path.endswith(".jpg") or image_path.endswith(".jpeg"):
        image_list.append(imread(image_path, IMREAD_COLOR))
    else:
        sys.exit("Unknown input file format. Accepted inputs: .pdf, .jpg, .jpeg, .png")
    return image_list
def download_image(path):
    cache_path = '.cache'
    cache_filename = os.path.join(cache_path, path)
    if os.path.exists(cache_filename):
        f = open(cache_filename, 'rb')
    else:
        url = f'{BASE_URL}/{path}'
        r = requests.get(url)
        f = io.BytesIO(r.content)
        cache_subdir = os.path.dirname(cache_filename)
        if not os.path.exists(cache_subdir):
            os.makedirs(cache_subdir)
        with open(cache_filename, 'wb') as cache:
            cache.write(f.read())
        f.seek(0)
    img = Image(file=f)
    img.alpha_channel = True
    f.close()
    return img
    def create_thumb_from_pdf(self, pdf_path):
        """
        Creates thumbnail from the first page of pdf file using wand module.
        :param pdf_path: path to pdf file from which the thumbnail will be created
        :return: thmb_path: path to created thumbnail
        """
        log.msg("PDF PATH: {}".format(pdf_path))
        thmb_path = os.path.join(os.path.dirname(pdf_path), 'thumbnail.png')
        log.msg("THMB PATH: {}".format(thmb_path))

        first_page = pdf_path + '[0]'
        log.msg("First page: ", first_page)
        img = Image(filename=first_page)
        img.format = 'png'
        img.resize(200, 300)
        img.background_color = Color('white')
        img.alpha_channel = 'remove'
        img.save(filename=thmb_path)
        return thmb_path
def hash_image_file(filepath):
  """
  Get pHash dct hash of local image file.
  :param filepath: path to image file
  :return: perceptual hash of image file, or None on error
  """
  if not os.path.exists(filepath):
    print("File {0} does not exist".format(filepath))
    return None

  img = Image(filename=filepath)
  if not img.alpha_channel:
    return dct_hash(filepath)

  # strip alpha channel and write to temp file before hashing
  _, without_alpha = mkstemp()
  img.alpha_channel = False
  img.save(filename=without_alpha)
  h = dct_hash(without_alpha)
  os.remove(without_alpha)
  return h
예제 #28
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(file = pdf_bytes, resolution = resolution)
    img.convert("png")
    img.background_color = Color('white')
    img.alpha_channel = 'remove'

    return img
def get_cv2_images(pdf_path: AbsolutePath) -> List[np.ndarray]:
    """
    Get CV2 images for PDF, as a list with one image for each page.
    """
    page_images = []

    with open(pdf_path, "rb") as pdf_file:
        pdf = PdfFileReader(pdf_file)

        for page_index in range(pdf.getNumPages()):
            # TODO(andrewhead): handle rotated pages. This will likely require:
            # 1. Saving the rotation value for a page
            # 2. Once bounding boxes are found, applying an inverse rotation to them
            # The inverse rotation must be applied to the bounding boxes because annotations like the
            # bounding boxes are applied using positions relative to the rotated page.
            page = pdf.getPage(page_index)

            pdf_writer = PdfFileWriter()
            pdf_writer.addPage(page)
            bytes_io = BytesIO()
            pdf_writer.write(bytes_io)

            bytes_io.seek(0)
            image = Image(file=bytes_io)

            # Replace transparent background with white background.
            image.background_color = "white"
            image.alpha_channel = "remove"

            # XXX(andrewhead): For some reason, the width and height dimensions of the PDF get
            # flipped when the image is loaded into a numpy array. Flip them back.
            np_image = np.array(image)
            shape = np_image.shape
            np_image = np_image.reshape((shape[1], shape[0], shape[2])  # pylint: disable=unsubscriptable-object
                                        )

            cv2_image = cv2.cvtColor(np_image, cv2.COLOR_RGBA2BGR)
            page_images.append(cv2_image)

    return page_images
예제 #30
0
    def verify_correct_image(self,
                             browser,
                             view,
                             expected_format,
                             expected_color=None):
        """
        Verify that a logo/icon at a given view is as expected

        expected_format ('png', 'svg' etc.)
        expected_color - proves the *source* of the image by looking at the histogram
            - we use ZCML to set the base SVG image to 100% 'blue'
            - the TTW SVG (if set) is 100% 'red'
            - the TTW PNG (if set) is 100% GREEN ('#0f0')
        """
        # We logout to test images are *publicly* visible
        browser.logout()
        browser.visit(self.portal, view=view)
        self.assertEqual(200, browser.status_code)
        try:
            im = Image(blob=browser.contents, format=expected_format)
        except CorruptImageError:  # pragma: no cover
            self.fail("Image is incorrect format - expected {}".format(
                expected_format))
        if (expected_color):
            # Determine the source (SVG, PNG) by using the colour
            # Test that 90% of image is expected_color
            total_pixels = im.height * im.width
            im.alpha_channel = 'opaque'
            try:
                # I try rgb value as key otherwise rgba.
                value = (im.histogram.get(Color(get_rgb(expected_color)[0])) or
                         im.histogram.get(Color(get_rgb(expected_color)[1])))
                self.assertGreater(value, total_pixels * 0.9)
            except KeyError:  # pragma: no cover
                self.fail(("expected_color {} not found in image histogram\n"
                           "First 5 colours were: {}").format(
                               Color(expected_color),
                               im.histogram.keys()[:5]))
        return im
예제 #31
0
파일: imwand.py 프로젝트: Scrik/sk1-wx
def process_image(raw_content):
	alpha = None
	img = Image(file=StringIO(raw_content))

	if img.alpha_channel:
		img_png = img.convert('png')
		img_png.type = 'truecolormatte'
		img.alpha_channel = False
		alpha = StringIO()
		img_png.save(file=alpha)
		alpha.seek(0)

	if img.type == 'colorseparation' or img.colorspace == 'lab':
		base_img = img.convert('tiff')
	else:
		base_img = img.convert('png')

#	base_img = img.convert('tiff')
	base = StringIO()
	base_img.save(file=base)
	base.seek(0)
	return base, alpha
    def create(self, validated_data):
        # Create a document in which to store the images:
        document_name = validated_data.get('document_name')
        document = Document.objects.create(document_name=document_name)

        # Handle PDF:
        if self.doc_ext == 'pdf':
            pdf = validated_data.get('file')
            images_list = []
            image_pdf = Image(file=pdf, resolution=150)
            image_png = image_pdf.convert('png')
            for img in image_png.sequence:
                img_page = Image(image=img)
                # Remove transparency and replace with white background:
                img_page.background_color = Color('white')
                img_page.alpha_channel = 'remove'
                # Convert to blob and push to images list:
                images_list.append(img_page.make_blob('png'))
            # Save the images into a DocumentImage
            for page_no, img_data in enumerate(images_list):
                buffer = BytesIO()
                pi_image = PI.open(BytesIO(img_data))
                # Save pi_image into the buffer:
                pi_image.save(buffer, 'png')
                # Convert buffer into InMemoryFile:
                image_in_memory = InMemoryUploadedFile(
                    buffer, None, 'test.png', 'image/png',
                    buffer.getbuffer().nbytes, None)
                # Create the image and attach it to the document overlay:
                document_image = DocumentImage(document=document,
                                               page_no=page_no + 1)
                document_image.image.save('test.png', image_in_memory)

        # Handle DOCX:
        elif self.doc_ext == 'docx':
            pass

        return document
예제 #33
0
# Read in the input image ... i.e., the B&W octal page.
img = Image(filename=backgroundImage)
if invert:
	img.negate()
backgroundWidth = img.width
backgroundHeight = img.height

if swapColors:
	print 'Swapping colors'
	for i in range(0, 8):
		replaceColorsInImage(images[i], Color(matchColor), Color(scanColor))
	replaceColorsInImage(img, Color(scanColor), Color(matchColor))

# Make certain conversions on the background image.
img.type = 'truecolor'
img.alpha_channel = 'activate'

# Determine the range of binsource lines we need to use.  We're guaranteed
# they're all in the binsource lines[] array.
if bankNumber < 4:
	bankNumber = bankNumber ^ 2
startIndex = bankNumber * 4 * 8 * 4 + pageInBank * 4 * 8
endIndex = startIndex + 4 * 8

draw = Drawing()
evilColor = Color("#FF00FF")
extraColor = Color("#FF8000")
draw.stroke_color = evilColor
draw.stroke_width = 4
draw.fill_opacity = 0
예제 #34
0
        pages = 1
        
        image = Image(
            width = imageFromPdf.width,
            height = imageFromPdf.height*pages          
           
        )
        
        for i in range(pages):
            image.composite(
                imageFromPdf.sequence[i],
                top = imageFromPdf.height * i,
                left = 0
            )
            
        image.resize(250,250)
        image.alpha_channel = False
        image.format = 'png'
        print(image.size)
        image.background_color = Color('pink')
        
        image.type = 'grayscale'
        image.caption = file.split('.')[0]
        image.save(filename = fileDirectory+file.split('.')[0]+".png")

        image.clear()
        image.close()

        #display(image)