@@ -268,11 +268,26 @@ def astc(image_data: bytes, width: int, height: int, block_size: tuple) -> Image
268268 context = ASTC_CONTEXTS [block_size ] = astc_encoder .ASTCContext (config )
269269
270270 image = astc_encoder .ASTCImage (astc_encoder .ASTCType .U8 , width , height , 1 )
271- context .decompress (image_data , image , astc_encoder .ASTCSwizzle .from_str ("RGBA" ))
271+ texture_size = calculate_astc_compressed_size (width , height , block_size )
272+ if len (image_data ) < texture_size :
273+ raise ValueError (f"Invalid ASTC data size: { len (image_data )} < { texture_size } " )
274+ context .decompress (
275+ image_data [:texture_size ], image , astc_encoder .ASTCSwizzle .from_str ("RGBA" )
276+ )
272277
273278 return Image .frombytes ("RGBA" , (width , height ), image .data , "raw" , "RGBA" )
274279
275280
281+ def calculate_astc_compressed_size (width : int , height : int , block_size : tuple ) -> int :
282+ """Calculate the size of the compressed data for ASTC."""
283+ # calculate the number of blocks
284+ block_count_x = (width + block_size [0 ] - 1 ) // block_size [0 ]
285+ block_count_y = (height + block_size [1 ] - 1 ) // block_size [1 ]
286+ # ignore depth for 2D textures
287+ # calculate the size of the compressed data
288+ return block_count_x * block_count_y * 16
289+
290+
276291def pvrtc (image_data : bytes , width : int , height : int , fmt : bool ) -> Image .Image :
277292 image_data = texture2ddecoder .decode_pvrtc (image_data , width , height , fmt )
278293 return Image .frombytes ("RGBA" , (width , height ), image_data , "raw" , "BGRA" )
0 commit comments