I'm a bit confused. I want to program a perspective transformation and thought that it is an affine one, but seemingly it is not. As an example, I want to perspective a square into a quadrilateral (as shown below), but it seems impossible to represent such a transform as a matrix multiplication+shift:

1) What I can't understand is that by definition affine transform is the one, that preserves all the staight lines. Can you provide an example of straight line, which is not preserved in this case?
2) How do I represent perspective transforms as this one numerically?
Thank you.
There is no affine transformation that will do what you want. If two lines are parallel before an affine transformation then they will be parallel afterwards. You start with a square and want a trapezium. This is not possible. The best you can get is a parallelogram.
You will need to move up a level and look at projective transformations. Affine transformations form a subset of the projective transformations. They are the ones that fix the line at infinity. (Parallel lines are thought to cross at infinity.)
In local coordinates, a projective transformation is given by: $$(x,y) \longmapsto \left(\frac{ax+by+c}{gx+hy+k},\frac{dx+ey+f}{gx+hy+k}\right) $$
It is possible to find all of the constants by substituting and solving. I get:
$$T : (x,y) \longmapsto \left( \frac{12x+3y}{4y+16} , \frac{3y}{y+4} \right) . $$