From 15eabfdabf30973c1e99b015060b7da2190ccdf1 Mon Sep 17 00:00:00 2001
From: 13693261870 <252740454@qq.com>
Date: 星期六, 06 一月 2024 15:47:26 +0800
Subject: [PATCH] 获取图片的GPS信息

---
 JiangSu/JiangSu.csproj                              |    3 
 JiangSu/index.html                                  |    5 
 JiangSu/Models/FileDesc.cs                          |   24 ++++
 JiangSu/cs/Tools.cs                                 |  104 ++++++++++++++++++++
 JiangSu/Controllers/ImgController.cs                |   58 +++++++++++
 JiangSu/App_Start/WebApiConfig.cs                   |    7 +
 JiangSu/cs/CustomMultipartFormDataStreamProvider.cs |   23 ++++
 JiangSu/cs/NoBufferPolicySelector.cs                |   27 +++++
 8 files changed, 249 insertions(+), 2 deletions(-)

diff --git a/JiangSu/App_Start/WebApiConfig.cs b/JiangSu/App_Start/WebApiConfig.cs
index 4a89acf..fbc6810 100644
--- a/JiangSu/App_Start/WebApiConfig.cs
+++ b/JiangSu/App_Start/WebApiConfig.cs
@@ -1,8 +1,10 @@
-锘縰sing Newtonsoft.Json.Converters;
+锘縰sing JiangSu.cs;
+using Newtonsoft.Json.Converters;
 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Web.Http;
+using System.Web.Http.Hosting;
 
 namespace JiangSu
 {
@@ -17,6 +19,9 @@
                 defaults: new { id = RouteParameter.Optional }
             );
 
+            // 娉ㄥ唽鎵╁睍涓绘満缂撳瓨Policy
+            GlobalConfiguration.Configuration.Services.Replace(typeof(IHostBufferPolicySelector), new NoBufferPolicySelector());
+
             // 灞忚斀杩斿洖XML鏍煎紡
             GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
 
diff --git a/JiangSu/Controllers/ImgController.cs b/JiangSu/Controllers/ImgController.cs
index a2e0a22..a6da6c5 100644
--- a/JiangSu/Controllers/ImgController.cs
+++ b/JiangSu/Controllers/ImgController.cs
@@ -2,15 +2,23 @@
 using JiangSu.Models;
 using System;
 using System.Collections.Generic;
+using System.IO;
 using System.Linq;
 using System.Net;
 using System.Net.Http;
+using System.Net.Http.Headers;
+using System.Threading.Tasks;
 using System.Web.Http;
+using System.Web;
 
 namespace JiangSu.Controllers
 {
     public class ImgController : ApiController
     {
+        public static string uploadPath = "Images";
+
+        public static List<string> extension = new List<string> { ".jpg", "png" };
+
         [HttpGet]
         public List<Img> SelectByPage(string name, int pageSize = 10, int pageIndex = 1)
         {
@@ -86,5 +94,55 @@
                 return 0;
             }
         }
+
+        [HttpPost]
+        public Task<IEnumerable<FileDesc>> Post()
+        {
+            string root = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, uploadPath);
+            if (!Directory.Exists(root)) Directory.CreateDirectory(root);
+
+            if (!Request.Content.IsMimeMultipartContent()) throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
+
+            var provider = new CustomMultipartFormDataStreamProvider(root);
+            var task = Request.Content.ReadAsMultipartAsync(provider).ContinueWith<IEnumerable<FileDesc>>(t =>
+            {
+                if (t.IsFaulted || t.IsCanceled) throw new HttpResponseException(HttpStatusCode.InternalServerError);
+
+                List<FileDesc> infos = new List<FileDesc>();
+                foreach (MultipartFileData f in provider.FileData)
+                {
+                    FileInfo info = new FileInfo(f.LocalFileName);
+                    if (!extension.Contains(info.Extension.ToLower()))
+                    {
+                        File.Delete(f.LocalFileName);
+                        continue;
+                    }
+
+                    string md5 = Tools.CalcFileMD5(f.LocalFileName);
+                    string newName = md5 + info.Extension;
+                    string newFile = Path.Combine(root, uploadPath, newName);
+
+                    Img img = new Img();
+                    img.name = info.Name;
+                    img.path = uploadPath + "\\" + newName;
+                    img.geom = Tools.GetImgGps(f.LocalFileName);
+
+                    if (!File.Exists(newFile)) File.Move(f.LocalFileName, newFile);
+                    int rows = ImgDAL.Insert(img);
+
+                    infos.Add(new FileDesc(info.Name, info.Length));
+                }
+
+                return infos;
+            });
+
+            return task;
+        }
+
+        [HttpGet]
+        public string GetGps()
+        {
+            return Tools.GetImgGps(@"D:\SEM\鐥呭绀轰緥_pos\1.jpg");
+        }
     }
 }
diff --git a/JiangSu/JiangSu.csproj b/JiangSu/JiangSu.csproj
index 3b68141..273178e 100644
--- a/JiangSu/JiangSu.csproj
+++ b/JiangSu/JiangSu.csproj
@@ -142,17 +142,20 @@
     <Compile Include="Controllers\OpController.cs" />
     <Compile Include="Controllers\ValuesController.cs" />
     <Compile Include="Controllers\GridController.cs" />
+    <Compile Include="cs\CustomMultipartFormDataStreamProvider.cs" />
     <Compile Include="cs\GridDAL.cs" />
     <Compile Include="cs\ImgDAL.cs" />
     <Compile Include="cs\LogOut.cs" />
     <Compile Include="cs\ModelDAL.cs" />
     <Compile Include="cs\ModelHandler.cs" />
+    <Compile Include="cs\NoBufferPolicySelector.cs" />
     <Compile Include="cs\PostgreHelper.cs" />
     <Compile Include="cs\SQLiteHelper.cs" />
     <Compile Include="cs\Tools.cs" />
     <Compile Include="Global.asax.cs">
       <DependentUpon>Global.asax</DependentUpon>
     </Compile>
+    <Compile Include="Models\FileDesc.cs" />
     <Compile Include="Models\Grid.cs" />
     <Compile Include="Models\Img.cs" />
     <Compile Include="Models\Model.cs" />
diff --git a/JiangSu/Models/FileDesc.cs b/JiangSu/Models/FileDesc.cs
new file mode 100644
index 0000000..d4a0b82
--- /dev/null
+++ b/JiangSu/Models/FileDesc.cs
@@ -0,0 +1,24 @@
+锘縰sing JiangSu.cs;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Web;
+
+namespace JiangSu.Models
+{
+    /// <summary>
+    /// 鏂囦欢鎻忚堪
+    /// </summary>
+    public class FileDesc
+    {
+        public FileDesc(string name, long length)
+        {
+            this.Name = name;
+            this.Length = Tools.FormatBytes(length);
+        }
+
+        public string Name { set; get; }
+
+        public string Length { set; get; }
+    }
+}
diff --git a/JiangSu/cs/CustomMultipartFormDataStreamProvider.cs b/JiangSu/cs/CustomMultipartFormDataStreamProvider.cs
new file mode 100644
index 0000000..2dcf539
--- /dev/null
+++ b/JiangSu/cs/CustomMultipartFormDataStreamProvider.cs
@@ -0,0 +1,23 @@
+锘縰sing System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Net.Http;
+using System.Web;
+
+namespace JiangSu.cs
+{
+    public class CustomMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
+    {
+        public CustomMultipartFormDataStreamProvider(string path)
+            : base(path)
+        { }
+
+        public override string GetLocalFileName(System.Net.Http.Headers.HttpContentHeaders headers)
+        {
+            //string name = !string.IsNullOrWhiteSpace(headers.ContentDisposition.FileName) ? headers.ContentDisposition.FileName : "NoName";
+            //return name.Replace("\"", string.Empty);
+
+            return headers.ContentDisposition.FileName.Replace("\"", string.Empty);
+        }
+    }
+}
\ No newline at end of file
diff --git a/JiangSu/cs/NoBufferPolicySelector.cs b/JiangSu/cs/NoBufferPolicySelector.cs
new file mode 100644
index 0000000..2a4e08a
--- /dev/null
+++ b/JiangSu/cs/NoBufferPolicySelector.cs
@@ -0,0 +1,27 @@
+锘縰sing System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Net.Http;
+using System.Web;
+using System.Web.Http.WebHost;
+
+namespace JiangSu.cs
+{
+    public class NoBufferPolicySelector : WebHostBufferPolicySelector
+    {
+        public override bool UseBufferedInputStream(object hostContext)
+        {
+            var context = hostContext as HttpContextBase;
+
+            if (context != null)
+            {
+                if (context.Request.HttpMethod == HttpMethod.Post.ToString() && context.Request.ContentLength > 102400)
+                {
+                    return false;
+                }
+            }
+
+            return true;
+        }
+    }
+}
diff --git a/JiangSu/cs/Tools.cs b/JiangSu/cs/Tools.cs
index 69e3b2e..c4e9961 100644
--- a/JiangSu/cs/Tools.cs
+++ b/JiangSu/cs/Tools.cs
@@ -3,8 +3,12 @@
 using System.Collections.Generic;
 using System.Data.Common;
 using System.Data.SQLite;
+using System.Drawing;
+using System.Drawing.Imaging;
+using System.IO;
 using System.Linq;
 using System.Reflection;
+using System.Security.Cryptography;
 using System.Web;
 
 namespace JiangSu.cs
@@ -92,5 +96,105 @@
 
             return list.ToArray();
         }
+
+        /// <summary>
+        /// 瀛楄妭鏍煎紡鍖�
+        /// </summary>
+        public static string FormatBytes(long bytes)
+        {
+            string[] Suffix = { "Byte", "KB", "MB", "GB", "TB" };
+
+            int i = 0;
+            double dblSByte = bytes;
+            if (bytes > 1024)
+                for (i = 0; (bytes / 1024) > 0; i++, bytes /= 1024)
+                    dblSByte = bytes / 1024.0;
+
+            return String.Format("{0:0.##}{1}", dblSByte, Suffix[i]);
+        }
+
+        /// <summary>
+        /// 璁$畻鏂囦欢鐨凪D5鐮�
+        /// </summary>
+        public static string CalcFileMD5(string filePath)
+        {
+            using (var md5 = new MD5CryptoServiceProvider())
+            {
+                using (var stream = File.OpenRead(filePath))
+                {
+                    byte[] hash = md5.ComputeHash(stream);
+                    return BitConverter.ToString(hash).Replace("-", "").ToLower();
+                }
+            }
+        }
+
+        /// <summary>
+        /// 鑾峰彇鍥剧墖鐨凣PS淇℃伅
+        /// </summary>
+        public static string GetImgGps(string path)
+        {
+            Image img = null;
+            try
+            {
+                img = Image.FromFile(path);
+                var items = img.PropertyItems.OrderByDescending(x => x.Id);
+
+                List<string> list = new List<string> { "0", "0", "0" };
+                foreach (PropertyItem item in items)
+                {
+                    if (item.Id >= 0x0000 && item.Id <= 0x001e) // 鍙彇Id鑼冨洿涓�0x0000鍒�0x001e
+                    {
+                        switch (item.Id)
+                        {
+                            case 0x0002: // 璁剧疆绾害
+                                list[1] = GetGpsVal(item.Value);
+                                break;
+                            case 0x0004: // 璁剧疆缁忓害
+                                list[0] = GetGpsVal(item.Value);
+                                break;
+                            case 0x0006:
+                                if (item.Value.Length == 8)
+                                {
+                                    double altitude = BitConverter.ToUInt32(item.Value, 0) * 1.0d / BitConverter.ToUInt32(item.Value, 4);
+                                    list[2] = altitude.ToString("0.000");
+                                }
+                                break;
+                        }
+                    }
+                }
+
+                return string.Format("POINT Z ({0})", string.Join(" ", list.ToArray()));
+            }
+            catch (Exception ex)
+            {
+                LogOut.Error(ex.Message + "\r\n" + ex.StackTrace);
+                return null;
+            }
+            finally
+            {
+                if (null != img) img.Dispose();
+            }
+        }
+
+        /// <summary>
+        /// 鑾峰彇GPS鍊�
+        /// </summary>
+        private static string GetGpsVal(byte[] bytes)
+        {
+            if (bytes.Length != 24) return "0";
+
+            //degrees(灏哹yte[0]~byte[3]杞垚uint, 闄や互byte[4]~byte[7]杞垚鐨剈int)   
+            double d = BitConverter.ToUInt32(bytes, 0) * 1.0d / BitConverter.ToUInt32(bytes, 4);
+
+            //minutes(灏哹yte[8]~byte[11]杞垚uint, 闄や互byte[12]~byte[15]杞垚鐨剈int)   
+            double m = BitConverter.ToUInt32(bytes, 8) * 1.0d / BitConverter.ToUInt32(bytes, 12);
+
+            //seconds(灏哹yte[16]~byte[19]杞垚uint, 闄や互byte[20]~byte[23]杞垚鐨剈int)   
+            double s = BitConverter.ToUInt32(bytes, 16) * 1.0d / BitConverter.ToUInt32(bytes, 20);
+
+            double val = (((s / 60 + m) / 60) + d);
+
+            return val.ToString("0.00000000");
+        }
     }
 }
diff --git a/JiangSu/index.html b/JiangSu/index.html
index 0b7ab2a..0d7f156 100644
--- a/JiangSu/index.html
+++ b/JiangSu/index.html
@@ -116,7 +116,10 @@
   </script>
 </head>
 <body>
-  <a href="http://localhost/JiangSu/Values/Get">Test</a> <br /> <br />
+  <a href="http://localhost/JiangSu/Values/Get">Test</a>
+  <span style="width: 50px;">&nbsp;</span>
+  <a href="http://localhost/JiangSu/Img/GetGps">GetGps</a>
+  <br /> <br />
 
   <a href="http://localhost/JiangSu/Op/SelectByPage?pageSize=10&pageIndex=1&name=">SelectByPage?pageSize=10&pageIndex=1&name=</a> <br />
 

--
Gitblit v1.9.3