Sort all the pixels of an image by the number of occurrences
Mathematica, 125 123 bytes

Export["a"&lt;&gt;#,i=ImageData@Import@#;Image@ArrayReshape[Join@@ConstantArray@@@SortBy[Tally[Join@@i],-Last@#&amp;],Dimensions@i]]&amp;


This defines an unnamed function which takes the file name in any common image format and writes the result to the a file with the same name but prepended with a. The result looks a bit different from the OP's, since Mathematica's SortBy breaks ties by default sort order, so the bottom bits where loads of ties occur look a bit neater:



The implementation itself is really straightforward:


ImageData to get a grid of colour values.
Join to flatten the array.
Tally to count the occurrence of each colour.
SortBy[...,-Last@#&amp;] to sort by frequencies from highest to lowest.
ConstantArray and Join to expand the tallies again.
ArrayReshape to recover the original image shape (obtained with Dimensions).
Image to convert the data back to an image object.


FYI, 22 bytes are used on file I/O. An equivalent version that takes and returns an image object comes in at 103 bytes:

(i=ImageData@#;Image@ArrayReshape[Join@@ConstantArray@@@SortBy[Tally[Join@@i],-Last@#&amp;],Dimensions@i])&amp;