Last active
January 24, 2024 16:20
-
-
Save Kurante2801/9fcc04ef40e6a7a34511ad2ac71f5dbe to your computer and use it in GitHub Desktop.
VTF Compression script
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# MAKE A BACKUP OF YOUR FILES BEFORE USING SCRIPT | |
# Requires VTFCmd.exe | |
import os, subprocess | |
from PIL import Image | |
from time import time | |
MAX_WIDTH = 1024 | |
MAX_HEIGHT = 1024 | |
start_time = time() | |
initials = [] | |
finals = [] | |
for root, dirs, files in os.walk("."): | |
path = root.split(os.sep) | |
for filename in files: | |
if filename.endswith(".vtf"): | |
# Full path to give vtfcmd | |
fullpath = '/'.join(path) | |
print(f"Compressing {fullpath}/{filename}") | |
subprocess.run(f"vtfcmd -file {fullpath}/{filename}", stdout=subprocess.DEVNULL) | |
tgafilename = f"{os.path.splitext(filename)[0]}.tga" | |
if not os.path.exists(f"{fullpath}/{tgafilename}"): | |
print(f"Could not convert to tga.") | |
continue | |
initial_size = os.stat(f"{fullpath}/{filename}").st_size / 1024 | |
initials.append(initial_size) | |
with Image.open(f"{fullpath}/{tgafilename}", "r") as tga: | |
has_alpha = False | |
width, height = tga.size | |
# Checking for transparency, this is probably slow as fuck but I don't give a fuck | |
if tga.mode == "RGBA": | |
alpha = tga.split()[3] | |
for x in range(width): | |
for y in range(height): | |
if alpha.getpixel((x, y)) != 255: | |
has_alpha = True | |
break | |
dx = has_alpha and "DXT5" or "DXT1" | |
subprocess.run(f"vtfcmd -file {fullpath}/{tgafilename} -resize -rclampwidth {MAX_WIDTH} -rclampheight {MAX_HEIGHT} -nomipmaps -format {dx} -alphaformat {dx} -flag NOLOD -flag TRILINEAR", stdout=subprocess.DEVNULL) | |
final_size = os.stat(f"{fullpath}/{filename}").st_size / 1024 | |
finals.append(final_size) | |
print(f"{round(initial_size, 1)} KB -> {round(final_size, 1)} KB ({round(final_size * 100 / initial_size, 2)}%)") | |
# Deletes TGA | |
os.remove(f"{fullpath}/{tgafilename}") | |
initial = 0 | |
final = 0 | |
for size in initials: | |
initial += size | |
for size in finals: | |
final += size | |
print(f"Finished. {round(initial, 2)} KB -> {round(final, 2)} KB ({round(final * 100 / initial, 2)}%)") | |
print(f"Time elapsed: {round(time() - start_time, 2)} seconds") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Does this make existing .vtf files smaller? Sorry to be a pain.