The site will limit the maximun size, but I want to produce a as big as possible image to ensure its quality. So I want to further control its size.
When I faced the problem of limited allowed image file size on image-hosing websites I always had to adjust the ImageSize
manually and then use a third-party tool for achieving minimal possible filesize (Mathematica's built-in compression is far from the best), this process was always iterative. For GIF I recommend commercial GIF Movie Gear (and I haven't found anything better). For PNG there is free PNGOUT (included in free IrfanView as a plugin), also a commercial version is available. For JPG there is commercial JPEG Compressor which makes a pretty good job.
And as I see, the algorithm of compressed is certain,why we cannot predict it exactly?
As Rom38 correctly notes in the comments,
the result of compression depends on namely content which will be compressed. Therefore, each image, in general, will be compressed to a bit different sizes.
In the other words, only without compression the filesize may be completely predictable if we know only ImageDimensions
.
So how to export the image with filesize exactly 1.2 Mb?
In the general case for lossless formats like PNG it isn't possible to produce a file with arbitrary small FileByteCount
because we have no option to drop some information from the image. But as Gregory correctly notes, lossless format like PNG may give smaller filesize than lossy depending on the structure of image. Also it is worth to know that starting from upcoming version 11.2 there is "CompressionLevel"
option supported for PNG export.
For lossy image formats it is possible to fit the filesize, and JPEG Compressor seemingly has an option to restrict maximum target file size. With Mathematica only something similar (but very crude as compared to what JPEG Compressor does) can be achieved using the "CompressionLevel"
option (the following code just shows the idea):
FindRoot[ByteCount[
ExportString[Plot[Sin[x], {x, 0, 6 Pi}], "JPEG", "CompressionLevel" -> x]] ==
10000, {x, 0, 1}, PrecisionGoal -> 0, AccuracyGoal -> 1, Evaluated -> False]
FindRoot::brmp: The root has been bracketed as closely as possible with machine precision but the function value exceeds the absolute tolerance 0.1`.
{x -> 0.51}
Some potentially useful ideas can be found also in this WC thread.
FileSize
. They do not require that the image must have explicit size in bytes (only maximum size may be specified). $\endgroup$ – Alexey Popkov Apr 18 '17 at 6:03