luahammerspoon

How to crop screen captures using hammerspoon


I wrote the safest possible example of screen capture using hammerspoon, here it is

function SafeSnapshotWindow(appName, savePath)
  local app = hs.application.find(appName)
  if not app then
    logger.colorError("App not found: " .. appName)
    return
  end

  local win = app:mainWindow()
  if not win then
    logger.colorError("Main window not found for app: " .. appName)
    return
  end

  win:unminimize()
  win:focus()
  win:raise()
  logger.colorDebug("Focusing window: " .. appName)

  hs.timer.doAfter(1.0, function()
    local snapshot = win:snapshot()

    if not snapshot then
      logger.colorError("Snapshot failed (nil image).")
      return
    else
      logger.colorDebug("Snapshot taken successfully.")
    end

    local imageSize = snapshot:size()
    local cropRect = {
      x = 0,
      y = 0,
      w = math.floor(imageSize.w / 2),
      h = math.floor(imageSize.h / 2)
    }
    if cropRect then
      snapshot = snapshot:croppedToRect(cropRect)
      logger.colorDebug(string.format("Image cropped to x=%d, y=%d, w=%d, h=%d",
        cropRect.x, cropRect.y, cropRect.w, cropRect.h))
    end

    local saveTo = savePath or (os.getenv("HOME") .. "/Desktop/snapshot.png")
    if snapshot:saveToFile(saveTo) then
      logger.colorInfo("Snapshot saved to: " .. saveTo)
    else
      logger.colorError("Failed to save image to file.")
    end
  end)
end

I know that snapshot is not nil I know that the rect dimensions aren't too big But I'm still getting attempt to call a nil value (method 'croppedToRect')

I'm out of ideas, any help would be appreciated


Solution

  • In the method call snapshot:croppedToRect(cropRect) snapshot is an hs.image-object.

    There is no croppedToRect method for image-objects listed in the Hammerspoon documentation, but there is a croppedCopy method that takes a rectangle argument.