How does MATLAB recover picture from magnitude spectrum alone?
Your code uses the phase for the reconstruction. Have a look at the output of fft2(x); they are complex numbers, i.e. the contain phase and magnitude. Have a look at this code:

%%
[x,map] = imread('http://www.cs.cmu.edu/~chuck/lennapg/lena_std.tif'); %import image
%%
i = rgb2gray(x);   % to greyscale

I = fft2(i); % 2D FFT

I = fftshift(I); % centre
mag = abs(I);
phase = angle(I);
I_magonly = abs(I);
I_phaseonly = I ./ abs(I);

figure(1);
subplot(321); imshow(abs(i),[]); title('Original');
subplot(322); imshow(log(double(abs(I))),[]); title('spectrum magnitude');
subplot(323); imshow(phase,[]); title('spectrum phase');
subplot(324); imshow(abs(ifft2(I)),[]); title('reconstructed');
subplot(325); imshow(abs(ifft2(I_magonly)),[]); title('reconstructed magnitude only');
subplot(326); imshow(abs(ifft2(I_phaseonly)),[]); title('reconstructed phase only');




It loads the Lena image, creates the FFT, and displays phase and magnitude information. Then it tries to reconstruct only based on phase or magnitude. Apparently, phase contains more information (for our eyes) than the magnitude. But you need to both exactly reproduce the image from its Fourier transform.