How can I create jpeg images of a given file size?

Cross-posted at Wolfram Community

I would like to have a function makeJPG[megabytes_] that generates random jpg images of given file sizes with itf filesize (in megabytes) watermarked on the image itself.

This is tricky because jpg compression isn't constant. Here's my first pass at it (but the watermark is squished, and the filesizes are not accurate):

(*Estimated by hand*)
points =
{{0.841, 1241.906471417973}, {2.399941, 2000}, {9.597819, 4000}, {38.390543, 8000}};
ifun = Interpolation[points];

makeJPG[megabytes_] :=
Module[{dim = IntegerPart @ ifun[megabytes], numberWatermark},
numberWatermark =
Rasterize[Style[ToString[megabytes],
FontFamily -> "Helvetica Neue"], ImageSize -> {dim, dim}];
Export[ToString[megabytes]~~".jpg",
ImageAdd[Image[RandomReal[1, {dim, dim, 3}]],
ImageSubtract[Image @ numberWatermark, 0.7]]]]


Motivation

The application here is an iphone app that I need to test on images of different megapixels.

-
What you could try is to make a function makeImage[text_, dim_] which produces a watermarked image of a specified size, then have another routine try different values of dim until your exported image has the right file size. I wonder if FindRoot will work for that... –  Rahul Sep 7 '13 at 3:15
To get the watermark at the right size without changing the aspect ratio try this: ImageCrop[Rasterize[string, RasterSize -> dim, ImageSize -> {dim}], {dim, dim}, Padding -> White] –  Simon Woods Sep 7 '13 at 10:20
For the file size you might consider fine tweaking by changing the maximum image value instead of the dimensions. E.g. a random image with a maximum of 0.1 will compress more than one with a maximum of 1.0 –  Simon Woods Sep 7 '13 at 10:24
Not fully related but funny: xkcd.com/688 –  belisarius Sep 7 '13 at 19:20