[英]How to generate a random image of specified file size (e.g. x Kb) using NodeJS
I am working on some project where I need to have a lot of image files (preferably in jpg) format of predefined sizes (Not the height and width but file size in Kb/Mb). 我正在做一个项目,我需要准备很多预定义大小的图像文件(最好是jpg)(不是高度和宽度,而是文件大小,单位为Kb / Mb)。
So I might need to generate a random image of 100 KB in size and another random image of 2 MB in size. 因此,我可能需要生成一个大小为100 KB的随机图像和另一个大小为2 MB的随机图像。
How should I go about this using NodeJS? 我应该如何使用NodeJS做到这一点?
I found this Random Image Generator code to generate a random image but it does not allow me to specify the file size. 我发现此“随机图像生成器”代码可生成随机图像,但不允许我指定文件大小。
All suggestions and wild guesses are welcome. 欢迎提出所有建议和猜测。
I don't speak node, but at the command line using ImageMagick, this will get you a large JPEG image: 我不讲节点,但是在使用ImageMagick的命令行中,这将为您提供大的JPEG图像:
convert -size 1000x2000 xc:gray +noise gaussian large.jpg
If you then use -define jpeg:extent=400kb
on that you will get a 400kb file, +/- a little: 如果然后使用-define jpeg:extent=400kb
,则会得到一个400kb的文件,+ /-一点:
convert large.jpg -define jpeg:extent=400kb 400kb.jpg
Change the 400kb
to suit your needs. 更改400kb
以适合您的需求。 If you want to do it all in one go, you can do this: 如果您想一次完成所有操作,则可以执行以下操作:
convert -size 1000x2000 xc:gray +noise gaussian jpg: | convert -define jpeg:extent=400kb - 400kb.jpg
In node, can you use the raw interface? 在节点中,您可以使用原始接口吗? It'll look something like 看起来像
im.convert(['-size','1000x2000','xc:gray','+noise','gaussian','output.jpg'],
function(...)
You need to work out what dimensions and DPI will give you the file-size you want. 您需要确定什么尺寸和DPI将为您提供所需的文件大小。 Given that you don't seem to care too much about what the image looks like, let's pick 100 DPI pseudo-randomly. 考虑到您似乎不太在乎图像的外观,让我们选择100 DPI伪随机。
An image that is x
inches by y
inches at 100 DPI will take up 在100 DPI下x
英寸x
y
英寸的图像将被占用
(100*x)*(100*y)==fileSize
per colour channel. 每个颜色通道。 If you're looking for full colour, you'll need three of these, so 如果您要寻找全彩色,则需要其中三种,所以
3*(100*x)*(100*y)==fileSize
Now you need to drop in your fileSize
, pick a value for x
or y
, solve for the other value and generate an image of size x
by y
at 100 DPI to produce your required filesize. 现在,您需要放入fileSize
,为x
或y
选择一个值,求解另一个值,并以100 DPI生成大小为y
x
图像,以生成所需的文件大小。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.