Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 34 additions & 4 deletions src/imcflibs/imagej/misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,13 @@

from ij import IJ # pylint: disable-msg=import-error
from ij.plugin import Duplicator, ImageCalculator, StackWriter
from org.scijava.widget import TextWidget, WidgetStyle

from .. import pathtools
from ..log import LOG as log
from . import bioformats as bf
from . import prefs

from org.scijava.widget import WidgetStyle
from org.scijava.widget import TextWidget


def show_status(msg):
"""Update the ImageJ status bar and issue a log message.
Expand Down Expand Up @@ -533,7 +531,9 @@ def write_ordereddict_to_csv(out_file, content):
dict_writer.writerows(content)


def save_image_in_format(imp, format, out_dir, series, pad_number, split_channels, suffix=""):
def save_image_in_format(
imp, format, out_dir, series, pad_number, split_channels, suffix=""
):
"""Save an ImagePlus object in the specified format.

This function provides flexible options for saving ImageJ images in various
Expand Down Expand Up @@ -790,3 +790,33 @@ def save_script_parameters(destination, save_file_name="script_parameters.txt"):
f.write("%s: %s\n" % (key, str(val)))

timed_log("Saved script parameters to: %s" % out_path)


def bytes_to_human_readable(size):
"""Convert a byte count to a human-readable string using binary units.

Parameters
----------
size : int
Byte size (number of bytes).

Returns
-------
str
Human-friendly size string, e.g. `"512.0 bytes"`, `"2.0 KB"`,
`"1.0 MB"`.

Notes
-----
- Uses powers of 1024 (KB = 1024 bytes).
- Always returns a string with one decimal place and the unit.
"""

for unit in ["bytes", "KB", "MB", "GB", "TB"]:
if size < 1024.0:
return "%3.1f %s" % (size, unit)
size /= 1024.0

# If the value is larger than the largest unit, fall back to TB with
# the current value (already divided accordingly).
return "%3.1f %s" % (size, "TB")
18 changes: 18 additions & 0 deletions tests/test_misc.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
"""Tests for `imcflibs.imagej.misc` utility functions."""

from imcflibs.imagej.misc import bytes_to_human_readable


def test_bytes_to_human_readable_simple():
"""Ensure common sizes are formatted into human-readable strings."""
assert bytes_to_human_readable(500) == "500.0 bytes"
assert bytes_to_human_readable(2048) == "2.0 KB"
assert bytes_to_human_readable(1024 * 1024) == "1.0 MB"
assert bytes_to_human_readable(5 * 1024**3) == "5.0 GB"


def test_bytes_to_human_readable_large():
"""Verify formatting for large sizes such as terabytes."""
# 1.5 TB in bytes should format as 1.5 TB
size = int(1.5 * (1024**4))
assert bytes_to_human_readable(size) == "1.5 TB"
Loading