利用MD5码检查图片资源是否重复

本文介绍了一种通过计算纹理文件的MD5码来检查项目中是否有纹理被重复使用的方法。利用Unity编辑器脚本,可以批量获取项目中所有Texture2D资源的MD5码,并将相同MD5码的纹理路径收集起来,便于发现重复使用的纹理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本次实验中,我检查的是项目中的哪些贴图是否被重用。代码如下:

首先,就是MD5码的生成,这个是最重要的:

using System.IO;
using System.Security.Cryptography;
using System.Text;

public class FileHelper{
    public static string MD5Stream(Stream inputStream){
        MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
        md5.ComputeHash(inputStream);
        byte[] bt = md5.Hash;
        
        StringBuilder sb = new StringBuilder();
        for(int i =0;i < bt.Length; i++){
            sb.Append(bt[i].ToString("X2"));
        }
        return sb.ToString();
    }

    public static string MD5Stream(string filePath){
        try{
            using(FileStream stream = File.Open(filePath,FileMode.Open)){
                return MD5Stream(stream);
            }
        }
         catch(System.Exception e){
            Debug.Log("抛出异常:" + e);
            return;
        }
    }
}

然后我们只需要提供需要检查资源的路径就可以了。

using UnityEngine;
using System.Collections;
using UnityEditor;
using System.IO;
using System.Collections.Generic;

public class MD5Test:Editor{
    private static Dictionary<string, List<string>> ;
    private static List<string> listPaths;

    [MenuItem("MD5/SearchTexture")]
    public static void SearchAllTexture(){
        dics = new Dictionary<string,List<string>>();
        listPaths = new List<string>();

        string[] guids = AssetDatabase.FindAssets("t:" + "Texture2D",new string[]{"Assets"});
        for(int i =0;i<guids.Length;i++){
            string texturePath = AssetDatabase.GUIDToAssetPath(guids[i]);
            string code = FileHelper.MD5Stream(texturePath);
            listPaths.clear();
            if(!dics.ContainsKey(ecode)){
                listPaths.Add(texturePath);
                dics.Add(ecode,listPaths);
            }
            else
            {
                dics[ecode].Add(listPaths);
            }
        }
    }
}

这样的话,我们就获得了所有的Texture2D的MD5码。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值