Do not use buffer

This commit is contained in:
Andrew Murray 2025-05-06 20:22:39 +10:00
parent b40aa6888c
commit 270313048d
2 changed files with 11 additions and 6 deletions

View File

@ -110,17 +110,19 @@ def test_vtf_read(
(VtfPF.RGBA8888, "Tests/images/vtf_rgba8888.png", "RGBA", 0), (VtfPF.RGBA8888, "Tests/images/vtf_rgba8888.png", "RGBA", 0),
], ],
) )
@pytest.mark.parametrize("version", ((7, 1), (7, 2), (7, 3)))
def test_vtf_save( def test_vtf_save(
pixel_format: VtfPF, pixel_format: VtfPF,
file_path: str, file_path: str,
expected_mode: str, expected_mode: str,
epsilon: int, epsilon: int,
version: tuple[int, int],
tmp_path: Path, tmp_path: Path,
) -> None: ) -> None:
im: Image.Image im: Image.Image
with Image.open(file_path) as im: with Image.open(file_path) as im:
out = tmp_path / "tmp.vtf" out = tmp_path / "tmp.vtf"
im.save(out, pixel_format=pixel_format) im.save(out, pixel_format=pixel_format, version=version)
if pixel_format == VtfPF.DXT1: if pixel_format == VtfPF.DXT1:
im = im.convert("RGBA") im = im.convert("RGBA")
with Image.open(out) as expected: with Image.open(out) as expected:

View File

@ -14,7 +14,6 @@ from __future__ import annotations
import struct import struct
from enum import IntEnum, IntFlag from enum import IntEnum, IntFlag
from io import BytesIO
from math import ceil, log from math import ceil, log
from typing import IO, NamedTuple from typing import IO, NamedTuple
@ -308,11 +307,9 @@ def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
mipmap_count = _get_mipmap_count(width, height) if generate_mips else 0 mipmap_count = _get_mipmap_count(width, height) if generate_mips else 0
thumb_buffer = BytesIO()
thumb = im.convert("RGB") thumb = im.convert("RGB")
thumb.thumbnail((min(16, width), min(16, height))) thumb.thumbnail((min(16, width), min(16, height)))
thumb = thumb.resize((_closest_power(thumb.width), _closest_power(thumb.height))) thumb = thumb.resize((_closest_power(thumb.width), _closest_power(thumb.height)))
_write_image(thumb_buffer, thumb, VtfPF.DXT1)
header = VTFHeader( header = VTFHeader(
0, 0,
@ -352,10 +349,16 @@ def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
fp.write(b"\x01\x00\x00\x00") fp.write(b"\x01\x00\x00\x00")
fp.write(struct.pack("<I", header.header_size)) fp.write(struct.pack("<I", header.header_size))
fp.write(b"\x30\x00\x00\x00") fp.write(b"\x30\x00\x00\x00")
fp.write(struct.pack("<I", header.header_size + len(thumb_buffer.getbuffer()))) fp.write(
struct.pack(
"<I",
header.header_size
+ _get_texture_size(VtfPF.DXT1, thumb.width, thumb.height),
)
)
else: else:
fp.write(b"\x00" * (16 - fp.tell() % 16)) fp.write(b"\x00" * (16 - fp.tell() % 16))
fp.write(thumb_buffer.getbuffer()) _write_image(fp, thumb, VtfPF.DXT1)
min_size = 4 if pixel_format in BLOCK_COMPRESSED else 1 min_size = 4 if pixel_format in BLOCK_COMPRESSED else 1