Exemple #1
0
def make_image(data: Optional[bytes]) -> io.BytesIO:
    image_buffer = None
    if data:
        image_buffer = io.BytesIO(data)
        try:
            Image.from_blob(image_buffer.getbuffer())
        except UnrecognizedImageError:
            image_buffer = None

    if not image_buffer:
        broken_img_path = pathlib.Path(__file__).parent / "image-broken.png"
        image_buffer = io.BytesIO(broken_img_path.read_bytes())

    return image_buffer
Exemple #2
0
def make_image(data):
    image_buffer = None
    if data:
        image_buffer = io.BytesIO(data)
        try:
            Image.from_blob(image_buffer.getbuffer())
        except (UnrecognizedImageError, UnexpectedEndOfFileError,
                InvalidImageStreamError):
            image_buffer = None

    if not image_buffer:
        broken_img = load_inline_image(IMG_BLANK)
        image_buffer = io.BytesIO(broken_img)

    return image_buffer
Exemple #3
0
 def it_can_construct_from_an_image_path(self, from_path_fixture):
     image_path, _from_stream_, stream_, blob, filename, image_ = (
         from_path_fixture
     )
     image = Image.from_file(image_path)
     _from_stream_.assert_called_once_with(stream_, blob, filename)
     assert image is image_
Exemple #4
0
    def it_can_construct_from_an_image_blob(self, blob_, BytesIO_,
                                            _from_stream_, stream_, image_):
        image = Image.from_blob(blob_)

        BytesIO_.assert_called_once_with(blob_)
        _from_stream_.assert_called_once_with(stream_, blob_)
        assert image is image_
def parse_image(file, guid):
    if file.startswith("http://") or file.startswith("https://"):
        response = requests.get(file)
        image = Image.open(BytesIO(response.content))
    else:
        image = Image.open(file)
    iwidth, iheight = image.size
    f_format = get_extension(file)
    with connection.cursor() as cursor:
        cursor.execute(
            """
			INSERT INTO image_metadata (
				file_guid, width, height, file_format
			) VALUES (
				%s, %s, %s, %s
			)
		""", [guid, iwidth, iheight, f_format])
    return True
Exemple #6
0
 def replace_part(items, raw_items):
     for k, p in items:
         if path.basename(p.partname) == from_pic:
             image = Image.from_file(to_pic)
             partname = path.join(path.dirname(p.partname), image.filename)
             partname = PackURI(partname)
             img_part = ImagePart.from_image(image, partname)
             raw_items.__setitem__(k, img_part)
             break
Exemple #7
0
 def get_or_add_image_part(self, image_descriptor):
     """
     Return an |ImagePart| instance containing the image identified by
     *image_descriptor*, newly created if a matching one is not present in
     the collection.
     """
     image = Image.from_file(image_descriptor)
     matching_image_part = self._get_by_sha1(image.sha1)
     if matching_image_part is not None:
         return matching_image_part
     return self._add_image_part(image)
Exemple #8
0
 def get_or_add_image_part(self, image_descriptor):
     """
     Return an |ImagePart| instance containing the image identified by
     *image_descriptor*, newly created if a matching one is not present in
     the collection.
     """
     image = Image.from_file(image_descriptor)
     matching_image_part = self._get_by_sha1(image.sha1)
     if matching_image_part is not None:
         return matching_image_part
     return self._add_image_part(image)
Exemple #9
0
    def it_can_construct_from_an_image_stream(self, from_stream_fixture):
        stream_, blob_, filename_in = from_stream_fixture[:3]
        _ImageHeaderFactory_, image_header_ = from_stream_fixture[3:5]
        Image__init_, filename_out = from_stream_fixture[5:]

        image = Image._from_stream(stream_, blob_, filename_in)

        _ImageHeaderFactory_.assert_called_once_with(stream_)
        Image__init_.assert_called_once_with(ANY, blob_, filename_out,
                                             image_header_)
        assert isinstance(image, Image)
Exemple #10
0
 def it_correctly_characterizes_known_images(self, known_image_fixture):
     image_path, characteristics = known_image_fixture
     ext, content_type, px_width, px_height, horz_dpi, vert_dpi = (
         characteristics)
     with open(test_file(image_path), 'rb') as stream:
         image = Image.from_file(stream)
         assert image.content_type == content_type
         assert image.ext == ext
         assert image.px_width == px_width
         assert image.px_height == px_height
         assert image.horz_dpi == horz_dpi
         assert image.vert_dpi == vert_dpi
Exemple #11
0
def image_size(
    image_buffer: io.BytesIO,
    width_px: Optional[int] = None,
    height_px: Optional[int] = None,
) -> Dict[str, int]:
    """
    Compute width and height to feed python-docx so that image is contained in the page
    and respects width_px and height_px.

    Return:
        Empty: No resize
        Single dimension (width or height): image ratio is expected to be maintained
        Two dimensions (width and height): image should be resized to dimensions
    """
    image = Image.from_blob(image_buffer.getbuffer())

    # Normalize image size to inches.
    # - Without a specified pixel size, images are their actual pixel size, so that
    #   images of the same pixel size appear the same size in the document, regardless
    #   of their resolution.
    # - With a specified pixel size, images should take the specified size, regardless
    #   of their resolution.
    if height_px is None:
        height = image.px_height / image.vert_dpi
    else:
        height = height_px / DEFAULT_DPI
    if width_px is None:
        width = image.px_width / image.horz_dpi
    else:
        width = width_px / DEFAULT_DPI

    height = Inches(height)
    width = Inches(width)

    size = {}
    if width > USABLE_WIDTH:
        new_height = round(image.px_height / (image.px_width / USABLE_WIDTH))
        if new_height > USABLE_HEIGHT:
            size["height"] = USABLE_HEIGHT
        else:
            size["width"] = USABLE_WIDTH
    elif height > USABLE_HEIGHT:
        new_width = round(image.px_width / (image.px_height / USABLE_HEIGHT))
        if new_width > USABLE_WIDTH:
            size["width"] = USABLE_WIDTH
        else:
            size["height"] = USABLE_HEIGHT
    else:
        if width_px is not None:
            size["width"] = width
        if height_px is not None:
            size["height"] = height
    return size
Exemple #12
0
 def it_correctly_characterizes_known_images(self, known_image_fixture):
     image_path, characteristics = known_image_fixture
     ext, content_type, px_width, px_height, horz_dpi, vert_dpi = (
         characteristics
     )
     with open(test_file(image_path), 'rb') as stream:
         image = Image.from_file(stream)
         assert image.content_type == content_type
         assert image.ext == ext
         assert image.px_width == px_width
         assert image.px_height == px_height
         assert image.horz_dpi == horz_dpi
         assert image.vert_dpi == vert_dpi
Exemple #13
0
 def it_can_construct_from_an_image_stream(self, from_stream_fixture):
     # fixture ----------------------
     stream_, blob_, filename_in = from_stream_fixture[:3]
     _ImageHeaderFactory_, image_header_ = from_stream_fixture[3:5]
     Image__init_, filename_out = from_stream_fixture[5:]
     # exercise ---------------------
     image = Image._from_stream(stream_, blob_, filename_in)
     # verify -----------------------
     _ImageHeaderFactory_.assert_called_once_with(stream_)
     Image__init_.assert_called_once_with(
         blob_, filename_out, image_header_
     )
     assert isinstance(image, Image)
 def _get_parts(self):
     parts = []
     pkg_meta = self._get_pkg_meta()
     for part_name, content_type in pkg_meta:
         blob = self.blob_for(part_name)
         if 'image' in content_type:
             image = Image(blob, None, None, content_type)
             part = ImagePart.from_image(image, PackURI(part_name))
         else:
             part = XmlPart.load(PackURI(part_name), content_type, blob,
                                 None)
         parts.append(part)
     return parts
    def dimensions_fixture(self, request):
        image_file_path = test_file('monty-truth.png')
        image = Image.from_file(image_file_path)
        expected_cx, expected_cy = 1905000, 2717800

        # case 1: image part is loaded by PartFactory w/no Image inst
        if request.param == 'loaded':
            partname = PackURI('/word/media/image1.png')
            content_type = CT.PNG
            image_part = ImagePart.load(partname, content_type, image.blob,
                                        None)
        # case 2: image part is newly created from image file
        elif request.param == 'new':
            image_part = ImagePart.from_image(image, None)

        return image_part, expected_cx, expected_cy
Exemple #16
0
    def dimensions_fixture(self, request):
        image_file_path = test_file('monty-truth.png')
        image = Image.from_file(image_file_path)
        expected_cx, expected_cy = 1905000, 2717800

        # case 1: image part is loaded by PartFactory w/no Image inst
        if request.param == 'loaded':
            partname = PackURI('/word/media/image1.png')
            content_type = CT.PNG
            image_part = ImagePart.load(
                partname, content_type, image.blob, None
            )
        # case 2: image part is newly created from image file
        elif request.param == 'new':
            image_part = ImagePart.from_image(image, None)

        return image_part, expected_cx, expected_cy
Exemple #17
0
def image_size(
    image_buffer: io.BytesIO,
    width_px: Optional[int] = None,
    height_px: Optional[int] = None,
) -> Dict[str, int]:
    """
    Compute width and height to feed python-docx so that image is contained in the page
    and respects width_px and height_px.

    Return:
        Empty: No resize
        Single dimension (width or height): image ratio is expected to be maintained
        Two dimensions (width and height): image should be resized to dimensions
    """
    image = Image.from_blob(image_buffer.getbuffer())

    height = image.px_height if height_px is None else height_px
    width = image.px_width if width_px is None else width_px

    height = Inches(height / image.vert_dpi)
    width = Inches(width / image.horz_dpi)

    size = {}
    if width > USABLE_WIDTH:
        new_height = round(image.px_height / (image.px_width / USABLE_WIDTH))
        if new_height > USABLE_HEIGHT:
            size["height"] = USABLE_HEIGHT
        else:
            size["width"] = USABLE_WIDTH
    elif height > USABLE_HEIGHT:
        new_width = round(image.px_width / (image.px_height / USABLE_HEIGHT))
        if new_width > USABLE_WIDTH:
            size["width"] = USABLE_WIDTH
        else:
            size["height"] = USABLE_HEIGHT
    else:
        if width_px is not None:
            size["width"] = width
        if height_px is not None:
            size["height"] = height
    return size
Exemple #18
0
 def it_knows_the_image_filename_extension(self):
     image = Image(None, 'foobar.png', None)
     assert image.ext == 'png'
Exemple #19
0
 def image(self):
     if self._image is None:
         self._image = Image.from_blob(self.blob)
     return self._image
Exemple #20
0
 def image(self):
     if self._image is None:
         self._image = Image.from_blob(self.blob)
     return self._image
Exemple #21
0
 def it_can_construct_from_an_image_blob(self, from_blob_fixture):
     blob_, BytesIO_, _from_stream_, stream_, image_ = from_blob_fixture
     image = Image.from_blob(blob_)
     BytesIO_.assert_called_once_with(blob_)
     _from_stream_.assert_called_once_with(stream_, blob_)
     assert image is image_
Exemple #22
0
 def it_can_construct_from_an_image_file_like(self, from_filelike_fixture):
     image_stream, _from_stream_, blob, image_ = from_filelike_fixture
     image = Image.from_file(image_stream)
     _from_stream_.assert_called_once_with(image_stream, blob, None)
     assert image is image_
Exemple #23
0
 def it_knows_the_image_filename(self):
     filename = 'foobar.png'
     image = Image(None, filename, None)
     assert image.filename == filename
Exemple #24
0
 def it_knows_the_horz_and_vert_dpi_of_the_image(self, dpi_fixture):
     image_header_, horz_dpi, vert_dpi = dpi_fixture
     image = Image(None, None, image_header_)
     assert image.horz_dpi == horz_dpi
     assert image.vert_dpi == vert_dpi
Exemple #25
0
 def it_knows_the_image_px_dimensions(self, dimensions_fixture):
     image_header_, px_width, px_height = dimensions_fixture
     image = Image(None, None, image_header_)
     assert image.px_width == px_width
     assert image.px_height == px_height
Exemple #26
0
 def it_knows_the_image_content_type(self, content_type_fixture):
     image_header_, content_type = content_type_fixture
     image = Image(None, None, image_header_)
     assert image.content_type == content_type
Exemple #27
0
 def it_provides_access_to_the_image_blob(self):
     blob = b'foobar'
     image = Image(blob, None, None)
     assert image.blob == blob
Exemple #28
0
 def it_can_construct_from_an_image_file_like(self, from_filelike_fixture):
     image_stream, _from_stream_, blob, image_ = from_filelike_fixture
     image = Image.from_file(image_stream)
     _from_stream_.assert_called_once_with(image_stream, blob, None)
     assert image is image_
Exemple #29
0
 def size_fixture(self, image_header_):
     image_header_.px_width, image_header_.px_height = 150, 75
     image_header_.horz_dpi, image_header_.vert_dpi = 72, 200
     image = Image(None, None, image_header_)
     return image, 1905000, 342900
Exemple #30
0
 def scale_fixture(self, request, width_prop_, height_prop_):
     width, height, scaled_width, scaled_height = request.param
     width_prop_.return_value = Emu(1000)
     height_prop_.return_value = Emu(2000)
     image = Image(None, None, None)
     return image, width, height, (scaled_width, scaled_height)
Exemple #31
0
 def it_knows_the_sha1_of_its_image(self):
     blob = b'fO0Bar'
     image = Image(blob, None, None)
     assert image.sha1 == '4921e7002ddfba690a937d54bda226a7b8bdeb68'
Exemple #32
0
def when_construct_image_using_path(context):
    context.image = Image.from_file(context.image_path)