Those are called CAPTCHAs. See:
http://www.captcha.net/
If you search on Google, there are some free scripts to do what you want. They're designed to beat OCR -- it's a challenge in Artificial Intelligence, i.e. design a test that a human can pass easily, but represents a difficult problem for a computer.