Skip to content

Commit

Permalink
Figure.savefig: Support .jpeg as JPEG image extension (#2691)
Browse files Browse the repository at this point in the history
Co-authored-by: Yvonne Fröhlich <[email protected]>
Co-authored-by: Wei Ji <[email protected]>
  • Loading branch information
3 people authored Sep 19, 2023
1 parent 1e48454 commit efb3c62
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 6 deletions.
20 changes: 15 additions & 5 deletions pygmt/figure.py
Original file line number Diff line number Diff line change
Expand Up @@ -260,9 +260,9 @@ def savefig(
This method implements a matplotlib-like interface for
:meth:`pygmt.Figure.psconvert`.
Supported formats: PNG (``.png``), JPEG (``.jpg``), PDF (``.pdf``),
BMP (``.bmp``), TIFF (``.tif``), EPS (``.eps``), and KML (``.kml``).
The KML output generates a companion PNG file.
Supported formats: PNG (``.png``), JPEG (``.jpg`` or ``.jpeg``),
PDF (``.pdf``), BMP (``.bmp``), TIFF (``.tif``), EPS (``.eps``), and
KML (``.kml``). The KML output generates a companion PNG file.
You can pass in any keyword arguments that
:meth:`pygmt.Figure.psconvert` accepts.
Expand Down Expand Up @@ -304,8 +304,13 @@ def savefig(
"kml": "g",
}

prefix, ext = os.path.splitext(fname)
ext = ext[1:] # Remove the .
fname = Path(fname)
prefix, suffix = fname.with_suffix("").as_posix(), fname.suffix
ext = suffix[1:] # Remove the .
# alias jpeg to jpg
if ext == "jpeg":
ext = "jpg"

if ext not in fmts:
if ext == "ps":
raise GMTInvalidInput(
Expand All @@ -327,6 +332,11 @@ def savefig(
kwargs["W"] = "+k"

self.psconvert(prefix=prefix, fmt=fmt, crop=crop, **kwargs)

# Rename if file extension doesn't match the input file suffix
if ext != suffix[1:]:
fname.with_suffix("." + ext).rename(fname)

if show:
launch_external_viewer(fname)

Expand Down
2 changes: 1 addition & 1 deletion pygmt/tests/test_figure.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ def test_figure_savefig_exists():
fig = Figure()
fig.basemap(region="10/70/-300/800", projection="X3i/5i", frame="af")
prefix = "test_figure_savefig_exists"
for fmt in "png pdf jpg bmp eps tif".split():
for fmt in "png pdf jpg jpeg bmp eps tif".split():
fname = ".".join([prefix, fmt])
fig.savefig(fname)
assert os.path.exists(fname)
Expand Down

0 comments on commit efb3c62

Please sign in to comment.