Refactored to extract the image processing part