yanjinhui
2025-06-12 95ac5296182b763d12125c1d47f53c00632ffc41
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
using System;
using System.IO;
using System.Drawing;
 
 
namespace FaceAI
{
    class ImageUtil
    {
        // 图片文件转Base64String
        public static string img2byte(string filePath)
        {
            // 只保留文件名,避免路径错误
            string fileName = Path.GetFileName(filePath);
 
            // 获取文件的完整路径
            string fullPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "image", fileName);
 
            if (!File.Exists(fullPath))
            {
                throw new FileNotFoundException("文件不存在:" + fullPath);
            }
 
            using (FileStream filestream = new FileStream(fullPath, FileMode.Open, FileAccess.Read))
            {
                byte[] arr = new byte[filestream.Length];
                filestream.Read(arr, 0, arr.Length);
                return Convert.ToBase64String(arr);
            }
 
            ////将Image转换成流数据,并保存为byte[]
            //MemoryStream mstream = new MemoryStream();
            //img.Save(mstream, System.Drawing.Imaging.ImageFormat.Jpeg);
            //byte[] byData = new Byte[mstream.Length];
            //mstream.Position = 0;
            //mstream.Read(byData, 0, byData.Length);
            //mstream.Close();
            //return byData;
        }
        // 图片文件转bytes
        public static byte[] get_img_data(string img_path)
        {
            //根据图片文件的路径使用文件流打开,并保存为byte[]   
            FileStream fs = new FileStream(img_path, FileMode.Open);//可以是其他重载方法 
            byte[] byData = new byte[fs.Length];
            fs.Read(byData, 0, byData.Length);
            fs.Close();
            return byData;
        }
        // bytes转图片文件
        //public static void byte2img(byte[] b, int len, string file_name)
        //{
        //    MemoryStream ms = new MemoryStream(b);
        //    ms.Position = 0;
        //    System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
        //    img.Save(file_name);
        //    ms.Close();
        //}
        //// 二进制byte图片流转mat示例
        //public static Mat image2mat(string img_path)
        //{
        //    System.Drawing.Image img = System.Drawing.Image.FromFile(img_path);
        //    byte[] img_bytes = ImageUtil.img2byte(img);
        //    Mat mat = Cv2.ImDecode(img_bytes, ImreadModes.Color);
        //    return mat;
        //}
    }
}