Fix mask handling when some bytes are missing.
Transfer image masks when when possible, instead of copying.
Merge pull request #4406 from nnethercote/fix-and-transfer-masks

Improve image mask handling again