Skip to content

Commit

Permalink
updates
Browse files Browse the repository at this point in the history
  • Loading branch information
cabreraalex committed Nov 1, 2024
1 parent 6a8dc14 commit 5b8186b
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 4 deletions.
13 changes: 9 additions & 4 deletions streaming/base/format/mds/encodings.py
Original file line number Diff line number Diff line change
Expand Up @@ -464,10 +464,11 @@ def decode(self, data: bytes) -> Image.Image:


class JPEG(Encoding):
"""Store PIL image as JPEG."""
"""Store PIL image as JPEG. Optionally specify quality."""

def __init__(self, quality: int = 75):
assert 0 <= quality <= 100
if not (0 <= quality <= 100):
raise ValueError('JPEG quality must be between 0 and 100')
self.quality = quality

@classmethod
Expand All @@ -481,9 +482,13 @@ def from_str(cls, text: str) -> Self:
Self: The initialized Encoding.
"""
args = text.split(':') if text else []
assert len(args) in {0, 1}
if len(args) not in {0, 1}:
raise ValueError('JPEG encoding string must have 0 or 1 arguments')
if len(args) == 1:
quality = int(args[0])
try:
quality = int(args[0])
except ValueError:
raise ValueError('JPEG quality must be an integer between 0 and 100')
else:
quality = 75
return cls(quality)
Expand Down
25 changes: 25 additions & 0 deletions tests/test_encodings.py
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,30 @@ def test_jpeg_encode_decode(self, mode: str):
dec_data = dec_data.convert('I')
assert isinstance(dec_data, Image.Image)

@pytest.mark.parametrize('mode', ['L', 'RGB'])
def test_jpeg_encode_decode_with_quality(self, mode: str):
jpeg_enc = mdsEnc.JPEG(quality=50)
assert jpeg_enc.size is None

# Creating the (32 x 32) NumPy Array with random values
np_data = np.random.randint(255, size=(32, 32), dtype=np.uint32)
# Default image mode of PIL Image is 'I'
img = Image.fromarray(np_data).convert(mode)

# Test encode
enc_data = jpeg_enc.encode(img)
assert isinstance(enc_data, bytes)

# Test decode
dec_data = jpeg_enc.decode(enc_data)
dec_data = dec_data.convert('I')
assert isinstance(dec_data, Image.Image)

@pytest.mark.parametrize('quality', [-1, 101, 'foo'])
def test_jpeg_encode_decode_with_quality_invalid(self, quality: Any):
with pytest.raises(ValueError):
mdsEnc.JPEG(quality=quality)

@pytest.mark.parametrize('mode', ['L', 'RGB'])
def test_jpegfile_encode_decode(self, mode: str):
jpeg_enc = mdsEnc.JPEG()
Expand Down Expand Up @@ -224,6 +248,7 @@ def test_jpeg_encode_invalid_data(self, data: Any):
with pytest.raises(AttributeError):
jpeg_enc = mdsEnc.JPEG()
_ = jpeg_enc.encode(data)


@pytest.mark.parametrize('mode', ['I', 'L', 'RGB'])
def test_png_encode_decode(self, mode: str):
Expand Down

0 comments on commit 5b8186b

Please sign in to comment.