BMW has confirmed it will pull out of Formula One racing at the end of this season for "image reasons" to focus on sustainability and the environment.