# 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",

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 Narain 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