added a check for image index out of bounds