我可以创建具有特定大小(以字节为单位)的图像吗?

Joh*_*Doe 9 image-conversion

我想创建一个图像文件,所以它正好是 5MB 用于测试目的。是否可以?

gnu*_*ard 26

图像格式的大多数实现忽略尾随零。因此,将文件填充到所需大小相对简单。(5 兆字节是 10240 个块。)

#! /usr/bin/env bash

print_usage_and_exit(){
  echo "Usage: $0 FILE BLOCKS"
  echo "This script will pad FILE with zeros up to BLOCKS."
  echo "FILE must not already be larger than BLOCKS."
  exit
}
FILE=$1
BLOCKS=$2
if [ -z $FILE ] || [ -z $BLOCKS ] || [ -z "${BLOCKS##*[!0-9]*}" ]; then
  print_usage_and_exit
fi
FILE_SIZE=$(stat $FILE | awk '/Blocks:/ { print $4 }')
SIZE_DIFFERENCE=$(($BLOCKS-$FILE_SIZE))
if [ $SIZE_DIFFERENCE -le 0 ]; then
  print_usage_and_exit
fi
dd if=/dev/zero iflag=append count=$SIZE_DIFFERENCE >> $FILE 2>/dev/null
Run Code Online (Sandbox Code Playgroud)

  • 一些图像格式也有元数据区域,我假设也可以添加数据来填充大小 (13认同)
  • @JohnDoe 它不是 PHP,它是 bash 的 shell 脚本,如第一行所示。 (11认同)
  • @JohnDoe 由于您打算进行一些安全测试,因此您可以表现出一点学习新东西的意愿,并设置一个 Linux VM 以在那里运行脚本。 (10认同)
  • 不需要成熟的虚拟机。只需安装 cygwin shell 就可以了。如果您使用 git,您甚至可能已经有了一个 shell,因为 Windows 上的标准 git shell 是一个基于 minGW 的 bash。 (9认同)
  • 是bash脚本,看shebang行 https://bash.cyberciti.biz/guide/Shebang (4认同)
  • @JohnDoe 该脚本是为 linux 编写的。它可以在带有 [WSL](https://docs.microsoft.com/en-us/windows/wsl/install-win10) 的 Windows 上运行,但这只是为了运行一个脚本而进行的大量设置。 (3认同)

Kam*_*ski 5

很少有其他答案会计算您需要追加多少个尾随零,然后再追加。在 Linux 中有这种简单的方法:

truncate -s 5MB image
Run Code Online (Sandbox Code Playgroud)

(假设您需要 5 MB,即 5*1000*1000 字节。对于 5 MiB,即 5*1024*1024 字节,请使用-s 5M)。

如果原来image大于指定的大小,那么额外的数据将会丢失。如果最初image较小,则将添加填充零。如果可能,添加的片段将是稀疏的。

如果出于任何原因您不想要稀疏,请使用fallocate

fallocate -l 5MB image
Run Code Online (Sandbox Code Playgroud)

(类似但不完全相同:-l 5MB5 MB,-l 5MiB5 MiB)。

fallocate用这种方式只能扩展image。如果文件已经至少那么大,那么它的大小不会改变(稀疏性可以改变,我不会详细说明)。


chi*_*NUT 4

正如评论中所建议的,您可以使用图像元数据。jpg 支持 exif 数据。您提到了 php,它可以使用iptcembed(). 生成足够长的空字节(二进制 0)字符串以填充文件

<?php
$path = '/path/to/image.jpg';
$size = filesize($path);
$goal = 1024 * 1024 * 5; //5MB
$zeros = str_pad("", $goal - $size, "\0"); // make a string of ($goal - $size) binary 0s
$paddedImage = iptcembed($zeros, $path);
file_put_contents("/path/to/padded-image.jpg", $paddedImage);
Run Code Online (Sandbox Code Playgroud)