You cannot stop this from happening, because the photo belongs to your friend and not to you, and therefore only he/she is the one that determines who sees posts and comments by other people (such as you) on his/her timeline.
The setting that your friend can use to control this visibility is:
Account Settings | Timeline and Tagging | Who can see things on my timeline? | Who can see what others post on your timeline?
However, when viewing other people's posts inside your News Feed, you have the ability to see with what scope that item was published, and this information might help you make a more informed decision regarding whether or not to comment on that item.
At the end of the line offering Like, Comment, and Share options, there is a little icon indicating "Shared with". If you hover over it, you will see something similar to one of the following:
- Shared with: Public
- Shared with: X's friends
- Shared with: X's friends of friends
- Shared with: Members of group-X
This information might help you estimate an "upper bound" for how "far" your comment might be seen. For example, if the photo was shared with "Public", then anyone on Facebook that will directly visit the photo will see your comment, and -- depending on the setting your friend chose for "Who can see what others post on your timeline?" -- a very large number of that person's friends (or even friends-of-friends) will also see your comment in their News Feeds!
Keep in mind, however, that your friend can change the privacy setting for an individual post retroactively! A post that was initially shared with only a small set of friends might one day become shared with Public.
So, the bottom-line recommendation is:
Before posting anything (including comments) to a social network such as Facebook, always consider the possibility that it might be seen (if not now then maybe later) by perfect strangers or, even worse, by antagonists.