\startluacode
local format = string.format
-- figures.cachepaths.path = "cache" -- should be setup-option
local function sample_down(oldname, newname, resolution)
  local request = figures.current().request
  local width = request.width:sub(1, -3)
  local height = request.height:sub(1, -3)
  if resolution == "" or (width == "" and height == "") then
    print(format("Nothing to do: %s, %s, %s", oldname, newname, resolution))
    return
  end
  local inch = 72.27
  local image = img.scan{filename = oldname}
  local xy = image.xsize / image.ysize
  if width == "" then
    width = height * xy
  end
  if height == "" then
    height = width / xy
  end
  local xsize = resolution * width / inch
  local ysize = resolution * height / inch
  if xsize < image.xsize or ysize < image.ysize then
    local s = format("gm convert -resize %dx%d %s %s",
                     xsize, ysize, oldname, newname)
    print("Conversion: " .. s)
    os.execute(s)
  else
    print(format("Nothing to do: %s, %s, %s", oldname, newname, resolution))
    print(format("xsize = %d, ysize = %d", xsize, ysize))
  end
end

figures.converters.jpg = figures.converters.jpg or {}
figures.converters.jpg["lowres.jpg"] = sample_down
\stopluacode

\starttext
\setupexternalfigures[resolution=50, conversion=lowres.jpg]
\externalfigure[hacker][width=0.5\textwidth]
\setupexternalfigures[resolution=10]
\externalfigure[hacker][width=0.5\textwidth]
\stoptext
