python生成一个20MB大小的图片
·
测试接口时,网上半天找不到大图,危急之际,只能用python生成一个了
from PIL import Image, ImageDraw
import os
import random
def create_large_image(target_size_mb=20):
target_bytes = target_size_mb * 1024 * 1024 # Convert MB to bytes
width = 20000 # Start with a very large width
height = 20000 # Start with a very large height
temp_file = 'E:\\temp_image.png' # Specify a complete file path
img = Image.new('RGB', (width, height), color='white')
draw = ImageDraw.Draw(img)
# Add complex patterns to avoid all-zero compression
for i in range(0, width, 10):
draw.line((i, 0, i, height), fill=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))
for j in range(0, height, 10):
draw.line((0, j, width, j), fill=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))
# Add random noise to the image
for x in range(0, width, 50):
for y in range(0, height, 50):
draw.ellipse((x, y, x+10, y+10), fill=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))
img.save(temp_file, format="PNG")
# Check the size of the generated image
generated_size = os.path.getsize(temp_file)
print(f"Generated image size: {generated_size / (1024 * 1024):.2f} MB")
if generated_size < target_bytes:
print("The generated image is smaller than the target size.")
else:
print("The generated image meets the target size requirement.")
img.save('output_large_image.png', format="PNG")
os.remove(temp_file) # Final cleanup
create_large_image()
放心食用,哈哈哈哈
更多推荐
所有评论(0)