def get_image_from_texture2d(texture_2d, flip=True) -> Image: """converts the given texture into PIL.Image :param texture_2d: texture to be converterd :type texture_2d: Texture2D :param flip: flips the image back to the original (all Unity textures are flipped by default) :type flip: bool :return: PIL.Image object :rtype: Image """ image_data = copy(bytes(texture_2d.image_data)) if not image_data: return Image.new("RGB", (0, 0)) texture_format = ( texture_2d.m_TextureFormat if isinstance(texture_2d.m_TextureFormat, TF) else TF(texture_2d.m_TextureFormat) ) selection = CONV_TABLE[texture_format] if len(selection) == 0: raise NotImplementedError( f"Not implemented texture format: {texture_format.name}" ) if texture_format in XBOX_SWAP_FORMATS: image_data = swap_bytes_for_xbox(image_data, texture_2d.platform) if "Crunched" in texture_format.name: version = texture_2d.version if ( version[0] > 2017 or (version[0] == 2017 and version[1] >= 3) # 2017.3 and up or texture_format == TF.ETC_RGB4Crunched or texture_format == TF.ETC2_RGBA8Crunched ): image_data = texture2ddecoder.unpack_unity_crunch(image_data) else: image_data = texture2ddecoder.unpack_crunch(image_data) img = selection[0]( image_data, texture_2d.m_Width, texture_2d.m_Height, *selection[1:] ) if img and flip: return img.transpose(Image.FLIP_TOP_BOTTOM) return img
def _test_crunched(name, func, unity=False): # load sample data data: bytes = zip.open(name + ".data", "r").read() details: dict = json.loads(zip.open(name + ".json", "r").read()) ori_img: Image = Image.open(zip.open(name + ".png", "r")) if unity: data = texture2ddecoder.unpack_unity_crunch(data) else: data = texture2ddecoder.unpack_crunch(data) # decompress data width = details["m_Width"] height = details["m_Height"] dec = func(data, width, height) # load raw image data dec_img = Image.frombytes("RGBA", (width, height), dec, 'raw', ("BGRA")) dec_img = dec_img.convert(ori_img.mode) # compare images assert (ImageChops.difference(ori_img, dec_img).getbbox() is None)