1.合并图片
using System;
using System.IO;
using UnityEditor;
using UnityEngine;
public class TextureCombine
{
[MenuItem("Tools/TextureCombine")]
static void Combine()
{
Texture2D pic1 = AssetDatabase.LoadAssetAtPath<Texture2D>("Assets/Images/pic1.jpg");
Texture2D pic2 = AssetDatabase.LoadAssetAtPath<Texture2D>("Assets/Images/pic2.jpg");
Texture2D pic3 = AssetDatabase.LoadAssetAtPath<Texture2D>("Assets/Images/pic3.jpg");
Texture2D pic4 = AssetDatabase.LoadAssetAtPath<Texture2D>("Assets/Images/pic4.jpg");
Texture2D exportImg = Combine(new[] { pic1, pic2,pic3,pic4 }, new[] { (0, 0), (0, 484),(512,0),(512,512) } , 1024);
File.WriteAllBytes("Assets/CombineImages/out.jpg", exportImg.EncodeToJPG());
AssetDatabase.Refresh();
}
/// <summary>
/// 合并贴图
/// </summary>
/// <param name="texs">贴图</param>
/// <param name="offsets">贴图位置,左下角(0,0)</param>
/// <param name="size">自己贴图的大小</param>
/// <returns></returns>
static Texture2D Combine(Texture2D[] texs, ValueTuple<int, int>[] offsets, int size)
{
Texture2D @out = new Texture2D(size, size, TextureFormat.RGBA32, true);
for (int i = 0; i < texs.Length; i++)
{
var tex = texs[i];
var offest = offsets[i];
var width = tex.width;
var height = tex.height;
RenderTexture tmp = RenderTexture.GetTemporary(width, height, 0, RenderTextureFormat.Default, RenderTextureReadWrite.Linear);
Graphics.Blit(tex, tmp);
RenderTexture previous = RenderTexture.active;
RenderTexture.active = tmp;
Texture2D @new = new Texture2D(width, height);
@new.ReadPixels(new Rect(0, 0, width, height), 0, 0);
@new.Apply();
@out.SetPixels(offest.Item1, offest.Item2, width, height, @new.GetPixels());
RenderTexture.active = previous;
RenderTexture.ReleaseTemporary(tmp);
}
return @out;
}
}
我自己4个贴图合成的一个贴图
2.读取合并图片中任意位置的图片(示例读取右上角)
using UnityEngine;
using UnityEngine.UI;
using System.IO;
public class Test1 : MonoBehaviour
{
private string path;
private Texture2D combineTex;
public RawImage completImg;
public Image singleImg;
// Start is called before the first frame update
void Start()
{
path = Application.dataPath + "/CombineImages/out.jpg";
if (!File.Exists(path))
{
print("路径不存在");
return;
}
byte[] combineImgData= File.ReadAllBytes(path);
combineTex= ByteToTex2d(combineImgData, 1024, 1024);
CombineImg();
SingleImg();
}
//合并之后的贴图
private void CombineImg()
{
if(combineTex!=null)
{
completImg.texture = combineTex;
}
else
{
print("combineTex=null");
}
}
//合并之后贴图中的单个贴图
private void SingleImg()
{
//读取右上角的位置
Sprite sp = Sprite.Create(combineTex, new Rect(512, 512, 512, 512), new Vector2(0.5f, 0.5f));
singleImg.sprite = sp;
//设置图片宽、高
//singleImg.transform.GetComponent<RectTransform>().sizeDelta = new Vector2(256, 256);
}
public static Texture2D ByteToTex2d(byte[] bytes, int w , int h )
{
Texture2D tex = new Texture2D(w, h);
tex.LoadImage(bytes);
return tex;
}
}