C#:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Drawing; using System.IO; namespace test_CS_1 { class Program { static void Main(string[] args) { string fileDir = "E:/DX12/Sketch3DToolkit-master/matlab/"; //文件名称 string filePath = Path.Combine(fileDir, "new"); string UserPhoto; //读图片转为Base64String System.Drawing.Bitmap bmp1 = new System.Drawing.Bitmap(Path.Combine(fileDir, "2.png")); using (MemoryStream ms1 = new MemoryStream()) { //将文件指定格式保存到指定流中 bmp1.Save(ms1, System.Drawing.Imaging.ImageFormat.Png); byte[] arr1 = new byte[ms1.Length]; ms1.Position = 0; //从当前流读取字节块,并写入缓存区 ms1.Read(arr1, 0, (int)ms1.Length); ms1.Close(); //将缓存区数据byte[],转为base64string UserPhoto = Convert.ToBase64String(arr1); } //将Base64String转为图片并保存 byte[] arr2 = Convert.FromBase64String(UserPhoto); using (MemoryStream ms2 = new MemoryStream(arr2)) { System.Drawing.Bitmap bmp2 = new System.Drawing.Bitmap(ms2); //以指定格式保存到指定文件 bmp2.Save(filePath + ".png", System.Drawing.Imaging.ImageFormat.Png); } } } }
unity:
using System.Collections; using System.Collections.Generic; using UnityEngine; using System; using System.IO; public class test_texture2d : MonoBehaviour { // Use this for initialization //base64转图片 public string Base64ToTexture2d(string Base64STR) { Texture2D pic = new Texture2D(1111, 1111); byte[] data = System.Convert.FromBase64String(Base64STR); pic.LoadImage(data); byte[] bytes = pic.EncodeToPNG(); //下面是为了方便了解图片的信息写的 string year = System.DateTime.Now.Year.ToString(); string month = System.DateTime.Now.Month.ToString(); string day = System.DateTime.Now.Day.ToString(); string hour = System.DateTime.Now.Hour.ToString(); string minute = System.DateTime.Now.Minute.ToString(); string secend = System.DateTime.Now.Second.ToString(); //存储路径 string FileFullPath = Application.dataPath/*这是获取assets前的文件路径*/ + "/" + year + "-" + month + "-" + day + "-" + hour + "-" + minute + "-" + secend + ".png"; File.WriteAllBytes(FileFullPath, bytes); return FileFullPath; } //图片转base64string public string Texture2dToBase64(string texture2d_path) { //将图片文件转为流文件 FileStream fs = new System.IO.FileStream(texture2d_path, System.IO.FileMode.Open, System.IO.FileAccess.Read); byte[] thebytes = new byte[fs.Length]; fs.Read(thebytes, 0, (int)fs.Length); //转为base64string string base64_texture2d = Convert.ToBase64String(thebytes); return base64_texture2d; } void Start () { } // Update is called once per frame void Update () { } }
注意:需要生成其他格式图片,改相应的输出图片格式方法。
时间: 2024-10-11 00:18:51