The spring has been compressed by doing work.
The work needed to push the piston to x is the area under the force-compression graph