Python使用png图片生成MapboxGL雪碧图

在mapboxgl中,使用sprite雪碧图实现图标渲染是比较常见的方式。对于自己制作定义的图标如何生成雪碧图,本文采用Python语言实现了该过程(考虑到每个png图标的大小不同),在代码中出现的python包,请先安装。

import os

import glob

from PIL import Image

import json

#图片集地址,支持不同文件夹下的png图片合并

IMAGES_PATH = r'D:\sprite_allsvg\sprite_s\\*\\'

# 图片格式

IMAGES_FORMAT = '*.png'  

#合并后的列数

SPRITE_IMAGE_COLUMNS = 18

SPRITE_IMAGE_PATH = r'D:\sprite_allsvg\sprite_s\sprite.png'

SPRITE_JSON_PATH = r'D:\sprite_allsvg\sprite_s\sprite.json'

def walk_type(path, file_type):

    path_dir = os.path.join(path, file_type)

    #path下所有file_type类型的文件的路径列表

    paths = glob.glob(path_dir)

    return paths

#图片拼接

def merge_images():

    image_names = walk_type(IMAGES_PATH, IMAGES_FORMAT)

    images_count = len(image_names)

    sprite_image_rows = int(images_count / SPRITE_IMAGE_COLUMNS) + 1

    max_width = 0

    max_height = 0

    row_width = 0

    row_height = 0

    #存储{image:image,x:x,y:y,name:name}

    images = []

    try:

        for row in range(sprite_image_rows+1):

            if (row_width > max_width):

                max_width = row_width

            row_width = 0

            max_height += row_height

            row_height = 0

            for col in range(SPRITE_IMAGE_COLUMNS+1):

                num = row * SPRITE_IMAGE_COLUMNS + col

                if (num > images_count - 1):

                    break

                image =Image.open(image_names[num]) 

                image_width, image_height = image.size

                images.append({

                    'image': image,

                    'x': row_width,

                    'y': max_height,

                    'name':os.path.basename(image_names[num]) .split('.')[0]

                })

                if (image_height > row_height):

                    row_height = image_height

                row_width += image_width

        if (row_width > max_width):

            max_width = row_width

        max_height += row_height


        # 创建一个新图

        sprite_image = Image.new('RGBA', (max_width, max_height), (255,255,255,255))

        #写入内容

        json_img = {}

        for from_img in images:

            image=from_img['image']

            sprite_image.paste(image, (from_img['x'], from_img['y']))


            json_img[from_img['name']]={

                    'height': image.height,

                    'width': image.width,

                    'pixelRatio': 1,

                    'x': from_img['x'],

                    'y': from_img['y']

            }

        sprite_image.save(SPRITE_IMAGE_PATH)

        with open(SPRITE_JSON_PATH, 'w', encoding='utf-8') as file:

            #ensure_ascii=False可以消除json包含中文的乱码问题

            file.write(json.dumps(json_img,indent=2, ensure_ascii=False))

        print("转换成功")

    except Exception:

       print('traceback.format_exc():\n%s' % traceback.format_exc())

       print("转换失败")

#调用

merge_images()

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容