diff --git a/DevicesService/App.config b/DevicesService/App.config
index 4865121..05b125f 100644
--- a/DevicesService/App.config
+++ b/DevicesService/App.config
@@ -2,8 +2,9 @@
-
+
+
\ No newline at end of file
diff --git a/DevicesService/Commen/COMUtils.cs b/DevicesService/Commen/COMUtils.cs
index f9771c7..efc33e3 100644
--- a/DevicesService/Commen/COMUtils.cs
+++ b/DevicesService/Commen/COMUtils.cs
@@ -1,13 +1,18 @@
using DevicesService.Commen;
+using Functions.FileExt;
using NAudio.CoreAudioApi;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
+using SkiaSharp;
using System;
using System.Buffers.Text;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Configuration;
+using System.Drawing;
+using System.Globalization;
+using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Net.Http;
@@ -15,6 +20,8 @@ using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
+using System.Xml.Linq;
+using static System.Net.Mime.MediaTypeNames;
using Timer = System.Timers.Timer;
namespace DevicesService.Common
{
@@ -28,14 +35,14 @@ namespace DevicesService.Common
{
try
{
-
-
string COMName = ConfigurationManager.AppSettings["COMName"].ToString();
// 设置COM口,波特率,奇偶校验,数据位,停止位
serialPort.PortName = COMName; // 请替换为你的串口名称
serialPort.BaudRate = 115200; // 设置波特率
serialPort.Parity = Parity.None;
serialPort.DataBits = 8;
+ //serialPort.WriteBufferSize =40960;
+ // serialPort.ReadBufferSize = 40960;
serialPort.StopBits = StopBits.One;
serialPort.Handshake = Handshake.None;
serialPort.Encoding = Encoding.UTF8; // 设置正确的编码
@@ -64,14 +71,16 @@ namespace DevicesService.Common
///
///
///
+ public static string bsid = string.Empty;
+ public static string bsext = string.Empty;
+ public static string bspath = string.Empty;
+ public static bool sfjswc = false;
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
try
{
SerialPort sp = (SerialPort)sender;
string indata = sp.ReadExisting();
- //Console.WriteLine(indata);
- //Console.WriteLine(indata.Contains("\n").ToString());
if (!string.IsNullOrEmpty(indata))
{
if (indata.Contains("\n"))
@@ -119,27 +128,13 @@ namespace DevicesService.Common
SendData(base64);
#endregion
break;
- //播放:{"type":"3","param":{"text":"欢迎使用阿凯思控诉业务一体机","ispaye":false}}
- //停止:{"type":"3","param":{"text":"","ispaye":true}}
- case Func.payleText:
- #region 文字语音播报
- joparam = (JObject)JsonConvert.DeserializeObject(param);
- string text = joparam["text"].ToString();
- bool ispaye = Convert.ToBoolean(joparam["ispaye"].ToString());
- resultback = scriptCallback.payleText(text, ispaye,callback);
- Log.Info("文字语音播报 返回数据:" + resultback);
- base64 = Util.str2Base64(resultback);
- //向com对方发送数据
- SendData(base64);
- #endregion
- break;
//{"type":"4","param":{"content":"欢迎使用阿凯思控诉业务一体机","phone":"13333333333"}}
case Func.SendSSM:
#region 发送短信
joparam = (JObject)JsonConvert.DeserializeObject(param);
string content = joparam["content"].ToString();
string phone = joparam["phone"].ToString();
- resultback = scriptCallback.SendSSM(content, phone,callback);
+ resultback = scriptCallback.SendSSM(content, phone, callback);
Log.Info("发送短信 返回数据:" + resultback);
base64 = Util.str2Base64(resultback);
//向com对方发送数据
@@ -151,11 +146,11 @@ namespace DevicesService.Common
#region 打开高拍仪并且进行快速扫描文件
joparam = (JObject)JsonConvert.DeserializeObject(param);
data = joparam["url"].ToString();
- resultback = scriptCallback.openCamera(data,callback);
+ resultback = scriptCallback.openCamera(data, callback);
Log.Info("打开高拍仪并且进行快速扫描文件 返回数据:" + resultback);
- base64 = Util.str2Base64(resultback);
+ //base64 = Util.str2Base64(resultback);
//向com对方发送数据
- SendData(base64);
+ SendData(resultback);
#endregion
break;
//{"type":"6","param":{"data":""}}
@@ -163,7 +158,7 @@ namespace DevicesService.Common
#region 打开签字版数据
joparam = (JObject)JsonConvert.DeserializeObject(param);
data = joparam["data"].ToString();
- resultback = scriptCallback.OpenSign(data,callback);
+ resultback = scriptCallback.OpenSign(data, callback);
Log.Info("打开签字版数据 返回数据:" + resultback);
base64 = Util.str2Base64(resultback);
//向com对方发送数据
@@ -185,69 +180,44 @@ namespace DevicesService.Common
//{"type":"8","param":{"url":"http://192.168.0.34:92/api/UploadFP/UploadFP"}}
case Func.GetSignData:
#region 获取签字版数据
- joparam = (JObject)JsonConvert.DeserializeObject(param);
- data = joparam["url"].ToString();
- resultback = scriptCallback.GetSignData(data,callback);
+ string sourcepaht = Environment.CurrentDirectory + "\\fiveInch.png";
+ FileInfo fileInfo = new FileInfo(sourcepaht);
+ if (fileInfo.Exists)
+ {
+ double size = fileInfo.Length / 1024.0;
+ if (size > 10)
+ {
+ FileStream fs1 = fileInfo.OpenRead();
+ fs1.Close();
+ resultback = Util.ConvertImageToBase64(sourcepaht);
+ File.Delete(sourcepaht);
+ int width = 800;
+ int height = 394;
+ using (Bitmap blankImage = new Bitmap(width, height))
+ {
+ // 设置图片背景为完全透明
+ using (Graphics g = Graphics.FromImage(blankImage))
+ {
+ // 使用白色背景填充图片
+ g.Clear(Color.Transparent);
+ }
+ // 保存图片到文件系统
+ blankImage.Save(sourcepaht);
+ }
+ }
+ else
+ {
+ resultback = Util.str2Base64("400");
+ }
+ }
+ else
+ {
+ resultback = Util.str2Base64("400");
+ }
Log.Info("获取签字版数据 返回数据:" + resultback);
- base64 = Util.str2Base64(resultback);
- //向com对方发送数据
- SendData(base64);
- #endregion
- break;
- //{"type":"9","param":{"url":"http://192.168.0.88:8092/CaseFile/Detectionscheme/20230222150023148.docx","ext":"doc"}}
- case Func.PrintFile:
- #region 根据文件地址在线打印
- joparam = (JObject)JsonConvert.DeserializeObject(param);
- string url = joparam["url"].ToString();
- string ext = joparam["ext"].ToString();
- resultback = scriptCallback.PrintFile(url, ext,callback);
- Log.Info("根据文件地址在线打印 返回数据:" + resultback);
- base64 = Util.str2Base64(resultback);
- //向com对方发送数据
- SendData(base64);
- #endregion
- break;
- //{"type":"10","param":{"base64":"aaabbb","ext":"doc"}}
- case Func.PrintBase64:
- #region 根据文件base64打印
- joparam = (JObject)JsonConvert.DeserializeObject(param);
- string pdfbase64 = joparam["base64"].ToString();
- string pdfext = joparam["ext"].ToString();
- resultback = scriptCallback.PrintBase64(pdfbase64, pdfext, callback);
- Log.Info("根据文件base64打印 返回数据:" + resultback);
- base64 = Util.str2Base64(resultback);
- //向com对方发送数据
- SendData(base64);
- #endregion
- break;
- //开始录音:{"type":"11","param":{"isopen":true,"url":""}}
- //取消录音:{"type":"11","param":{"isopen":false,"url":""}}
- //结束录音:{"type":"11","param":{"isopen":false,"url":"http://192.168.0.34:92/api/UploadFP/UploadFP"}}
- case Func.SoundRecording:
- #region 开始录音、取消录音、结束录音
- joparam = (JObject)JsonConvert.DeserializeObject(param);
- bool isopen = Convert.ToBoolean(joparam["isopen"].ToString());
- string upurl = joparam["url"].ToString();
- resultback = scriptCallback.SoundRecording(isopen, upurl, callback);
- Log.Info("开始录音、取消录音、结束录音 返回数据:" + resultback);
- base64 = Util.str2Base64(resultback);
- //向com对方发送数据
- SendData(base64);
- #endregion
- break;
- //播放音频:{"type":"12","param":{"ispaly":true,"url":"http://192.168.0.34:92/test.wav"}}
- //恢复播放:{ "type":"12","param":{ "ispaly":true,"url":""} }
- //暂停播放:{"type":"12","param":{"ispaly":false,"url":""}}
- case Func.Paly:
- #region 播放与暂停
- joparam = (JObject)JsonConvert.DeserializeObject(param);
- bool ispaly = Convert.ToBoolean(joparam["ispaly"].ToString());
- string purl = joparam["url"].ToString();
- resultback = scriptCallback.Paly(purl, ispaly, callback);
- Log.Info("播放与暂停 返回数据:" + resultback);
- base64 = Util.str2Base64(resultback);
+ // base64 = Util.str2Base64(resultback);
//向com对方发送数据
- SendData(base64);
+ SendData(resultback);
#endregion
break;
default:
@@ -270,6 +240,7 @@ namespace DevicesService.Common
_json = _json + indata;
}
}
+
}
catch (Exception ex)
{
@@ -281,6 +252,41 @@ namespace DevicesService.Common
}
}
+ ///
+ /// COM接收文件
+ ///
+ private void NewMethod1(SerialPort sp, string path)
+ {
+ byte[] buffer = new byte[sp.BytesToRead];
+ sp.Read(buffer, 0, buffer.Length);
+
+ // 保存或处理接收到的字节数据,不做任何编码转换
+ File.WriteAllBytes(path, buffer);
+ }
+
+ ///
+ /// COM口公共发送文件
+ ///
+ ///
+ private void NewMethod(string url, string id)
+ {
+ string ext = Path.GetExtension(url);
+ serialPort.WriteLine("Start_" + id + "_" + ext);
+ //读取文件开始传输文件
+ using (FileStream fileStream = new FileStream(url, FileMode.Open))
+ {
+ byte[] buffer = new byte[serialPort.WriteBufferSize];
+ int bytesRead = 0;
+ while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) > 0)
+ {
+ serialPort.Write(buffer, 0, bytesRead);
+ }
+ fileStream.Close();
+ fileStream.Dispose();
+ }
+ serialPort.WriteLine("End");
+ }
+
///
/// 打开串口
///
@@ -311,7 +317,6 @@ namespace DevicesService.Common
{
if (serialPort.IsOpen)
{
-
if (data.Length <= maxChunkSize)
{
serialPort.WriteLine(data);
diff --git a/DevicesService/Commen/ScriptCallbackObject.cs b/DevicesService/Commen/ScriptCallbackObject.cs
index e61c8c4..039d566 100644
--- a/DevicesService/Commen/ScriptCallbackObject.cs
+++ b/DevicesService/Commen/ScriptCallbackObject.cs
@@ -116,36 +116,36 @@ namespace DevicesService.Common
{
try
{
- if (text.Contains("http:"))
- {
- DateTime dateTime = DateTime.Now;
- string time = DateTime.Now.ToString(
- "yyyyMMddHHmmss", DateTimeFormatInfo.InvariantInfo);
- var dirpath = Path.Combine(Environment.CurrentDirectory, "wwwroot", "TempFile");
- FileExt.MakeSureDirExist(dirpath);
- var filepath = Path.Combine(dirpath, time);
- string path = dirpath + "\\" + time + ".txt";
- WebRequest request = WebRequest.Create(text);
- WebResponse response = request.GetResponse();
- using (Stream stream = response.GetResponseStream())
- {
- using (FileStream fileStream = new FileStream(path, FileMode.Create))
- {
- stream.CopyTo(fileStream);
- }
- }
- response.Close();
- using (StreamReader sr = new StreamReader(path))
- {
- text = string.Empty;
- string line;
- while ((line = sr.ReadLine()) != null)
- {
- // 处理每一行数据
- text = text + line;
- }
- }
- }
+ //if (text.Contains("http:"))
+ //{
+ // DateTime dateTime = DateTime.Now;
+ // string time = DateTime.Now.ToString(
+ // "yyyyMMddHHmmss", DateTimeFormatInfo.InvariantInfo);
+ // var dirpath = Path.Combine(Environment.CurrentDirectory, "wwwroot", "TempFile");
+ // FileExt.MakeSureDirExist(dirpath);
+ // var filepath = Path.Combine(dirpath, time);
+ // string path = dirpath + "\\" + time + ".txt";
+ // WebRequest request = WebRequest.Create(text);
+ // WebResponse response = request.GetResponse();
+ // using (Stream stream = response.GetResponseStream())
+ // {
+ // using (FileStream fileStream = new FileStream(path, FileMode.Create))
+ // {
+ // stream.CopyTo(fileStream);
+ // }
+ // }
+ // response.Close();
+ // using (StreamReader sr = new StreamReader(path))
+ // {
+ // text = string.Empty;
+ // string line;
+ // while ((line = sr.ReadLine()) != null)
+ // {
+ // // 处理每一行数据
+ // text = text + line;
+ // }
+ // }
+ //}
Task.Run(() =>
{
text = text.Replace("(", "").Replace(")", "、");
@@ -201,45 +201,47 @@ namespace DevicesService.Common
string data = hScamera.openCamera2();
if (!string.IsNullOrEmpty(data))
{
- //string base64 = Util.ImgToBase64String(data);
-
-
- Task.Run(async () =>
- {
- UploadInfoByFile(url, data);
- });
- @event5.WaitOne();
- Regex re = new Regex(@"(((?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(:[0-9]+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)");
- MatchCollection mc = re.Matches(url);//获取的是一个数组
- string imgurl = mc[0].ToString() + "://" + mc[1].ToString() + urlP;
- return "{\"callback\":\"" + callback + "\",\"message\":\"success\",\"code\":\"200\",\"status\":true,\"suffix\":\"bmp\",\"data\":\"" + imgurl + "\"}";
+ FileInfo fileInfo = new FileInfo(data);
+ string newdata = Util.CompressPictures(fileInfo);
+ string base64 = Util.ImgToBase64String(data);
+ //Task.Run(async () =>
+ //{
+ // UploadInfoByFile(url, data);
+ //});
+ //@event5.WaitOne();
+ //Regex re = new Regex(@"(((?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(:[0-9]+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)");
+ //MatchCollection mc = re.Matches(url);//获取的是一个数组
+ //string imgurl = mc[0].ToString() + "://" + mc[1].ToString() + urlP;
+ return base64;
}
else
{
data = hScamera.openCamera2();
if (!string.IsNullOrEmpty(data))
{
- // string base64 = Util.ImgToBase64String(data);
- Task.Run(async () =>
- {
- UploadInfoByFile(url, data);
- });
- @event5.WaitOne();
- Regex re = new Regex(@"(((?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(:[0-9]+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)");
- MatchCollection mc = re.Matches(url);//获取的是一个数组
- string imgurl = mc[0].ToString() + "://" + mc[1].ToString() + urlP;
- return "{\"callback\":\"" + callback + "\",\"message\":\"success\",\"code\":\"200\",\"status\":true,\"suffix\":\"bmp\",\"data\":\"" + imgurl + "\"}";
+ string base64 = Util.ImgToBase64String(data);
+ //Task.Run(async () =>
+ //{
+ // UploadInfoByFile(url, data);
+ //});
+ //@event5.WaitOne();
+ //Regex re = new Regex(@"(((?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(:[0-9]+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)");
+ //MatchCollection mc = re.Matches(url);//获取的是一个数组
+ //string imgurl = mc[0].ToString() + "://" + mc[1].ToString() + urlP;
+
+ return base64;
}
else
{
- return "{\"callback\":\"" + callback + "\",\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + "扫描失败" + "\"}";
+ return Util.str2Base64("400");
}
}
}
catch (Exception ex)
{
- return "{\"callback\":\"" + callback + "\",\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + ex.Message + "\"}";
+ Log.Info("扫描仪异常:" + ex.Message);
+ return Util.str2Base64("400");
}
}
@@ -385,24 +387,24 @@ namespace DevicesService.Common
}
Task.Run(async () =>
{
- DateTime dateTime = DateTime.Now;
- string time = DateTime.Now.ToString(
- "yyyyMMddHHmmss", DateTimeFormatInfo.InvariantInfo);
- var dirpath = Path.Combine(Environment.CurrentDirectory, "wwwroot", "PrintFile");
- FileExt.MakeSureDirExist(dirpath);
- var filepath = Path.Combine(dirpath, time);
- string path = dirpath + "\\" + time + "." + ext;
- WebRequest request = WebRequest.Create(url);
- WebResponse response = request.GetResponse();
- using (Stream stream = response.GetResponseStream())
- {
- using (FileStream fileStream = new FileStream(path, FileMode.Create))
- {
- stream.CopyTo(fileStream);
- }
- }
- response.Close();
- Util.Print2(path, fPrintDocument.PrinterSettings.PrinterName);
+ //DateTime dateTime = DateTime.Now;
+ //string time = DateTime.Now.ToString(
+ // "yyyyMMddHHmmss", DateTimeFormatInfo.InvariantInfo);
+ //var dirpath = Path.Combine(Environment.CurrentDirectory, "wwwroot", "PrintFile");
+ //FileExt.MakeSureDirExist(dirpath);
+ //var filepath = Path.Combine(dirpath, time);
+ //string path = dirpath + "\\" + time + "." + ext;
+ //WebRequest request = WebRequest.Create(url);
+ //WebResponse response = request.GetResponse();
+ //using (Stream stream = response.GetResponseStream())
+ //{
+ // using (FileStream fileStream = new FileStream(path, FileMode.Create))
+ // {
+ // stream.CopyTo(fileStream);
+ // }
+ //}
+ //response.Close();
+ Util.Print2(url, fPrintDocument.PrinterSettings.PrinterName);
});
return "{\"callback\":\"" + callback + "\",\"message\":\"success\",\"code\":\"200\",\"status\":true,\"data\":\"" + "打印成功" + "\"}";
@@ -485,15 +487,15 @@ namespace DevicesService.Common
//结束录音上传文件
if (!string.IsNullOrEmpty(url) && !isopen)
{
- Task.Run(async () =>
- {
- UploadInfo(url);
- });
- @event2.WaitOne();
- Regex re = new Regex(@"(((?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(:[0-9]+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)");
- MatchCollection mc = re.Matches(url);//获取的是一个数组
- string reurl = mc[0].ToString() + "://" + mc[1].ToString() + urlpath;
- return "{\"callback\":\"" + callback + "\",\"message\":\"success\",\"code\":\"200\",\"status\":true,\"suffix\":\"wav\",\"data\":\"" + reurl + "\"}";
+ //Task.Run(async () =>
+ //{
+ // UploadInfo(url);
+ //});
+ //@event2.WaitOne();
+ //Regex re = new Regex(@"(((?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(:[0-9]+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)");
+ //MatchCollection mc = re.Matches(url);//获取的是一个数组
+ //string reurl = mc[0].ToString() + "://" + mc[1].ToString() + urlpath;
+ return "{\"callback\":\"" + callback + "\",\"message\":\"success\",\"code\":\"200\",\"status\":true,\"suffix\":\"wav\",\"data\":\"" + srpath + "\"}";
}
else if (isopen)//开始录音
{
@@ -532,6 +534,14 @@ namespace DevicesService.Common
if (player == null)
{
NewMethod(url);
+ if (player != null)
+ {
+ return "{\"callback\":\"" + callback + "\",\"message\":\"success\",\"code\":\"200\",\"status\":true,\"data\":\"" + "音频播放" + "\"}";
+ }
+ else
+ {
+ return "{\"callback\":\"" + callback + "\",\"message\":\"success\",\"code\":\"400\",\"status\":false,\"data\":\"" + "未发现播放文件" + "\"}";
+ }
}
else
{
@@ -539,6 +549,7 @@ namespace DevicesService.Common
{
player.Play();
Log.Info("恢复播放");
+ return "{\"callback\":\"" + callback + "\",\"message\":\"success\",\"code\":\"200\",\"status\":true,\"data\":\"" + "恢复播放" + "\"}";
}
else
{
@@ -550,6 +561,14 @@ namespace DevicesService.Common
audioFileReader.Dispose();
}
NewMethod(url);
+ if (player != null)
+ {
+ return "{\"callback\":\"" + callback + "\",\"message\":\"success\",\"code\":\"200\",\"status\":true,\"data\":\"" + "音频播放" + "\"}";
+ }
+ else
+ {
+ return "{\"callback\":\"" + callback + "\",\"message\":\"success\",\"code\":\"400\",\"status\":false,\"data\":\"" + "未发现播放文件" + "\"}";
+ }
}
}
}
@@ -557,18 +576,29 @@ namespace DevicesService.Common
{
if (player != null)
{
- player.Pause();
- Log.Info("暂停播放");
+ if (string.IsNullOrEmpty(url))
+ {
+ player.Pause();
+ Log.Info("暂停播放");
+ return "{\"callback\":\"" + callback + "\",\"message\":\"success\",\"code\":\"200\",\"status\":true,\"data\":\"" + "暂停播放" + "\"}";
+ }
+ else
+ {
+ player.Stop();
+ // 释放资源
+ player.Dispose();
+ audioFileReader.Dispose();
+ player = null;
+ File.Delete(WaveOutPath);
+ Log.Info("停止播放");
+ return "{\"callback\":\"" + callback + "\",\"message\":\"success\",\"code\":\"200\",\"status\":true,\"data\":\"" + "停止播放" + "\"}";
+ }
+ }
+ else
+ {
+ return "{\"callback\":\"" + callback + "\",\"message\":\"success\",\"code\":\"400\",\"status\":false,\"data\":\"" + "未发现播放文件" + "\"}";
}
}
- if (player != null)
- {
- return "{\"callback\":\"" + callback + "\",\"message\":\"success\",\"code\":\"200\",\"status\":true,\"data\":\"" + "音频播放" + "\"}";
- }
- else
- {
- return "{\"callback\":\"" + callback + "\",\"message\":\"success\",\"code\":\"400\",\"status\":false,\"data\":\"" + "未发现播放文件" + "\"}";
- }
}
catch (Exception ex)
{
@@ -582,28 +612,30 @@ namespace DevicesService.Common
///
private void NewMethod(string url)
{
- Uri uri = new Uri(url);
- //返回 123.xlsx
- var filename = HttpUtility.UrlDecode(uri.Segments.Last());
- //获取文件后缀
- string ext = Path.GetExtension(filename);
- DateTime dateTime = DateTime.Now;
- string time = DateTime.Now.ToString(
- "yyyyMMddHHmmss", DateTimeFormatInfo.InvariantInfo);
- var dirpath = Path.Combine(Environment.CurrentDirectory, "wwwroot", "WaveOutFile");
- FileExt.MakeSureDirExist(dirpath);
- var filepath = Path.Combine(dirpath, time);
- WaveOutPath = dirpath + "\\" + time + ext;
- WebRequest request = WebRequest.Create(url);
- WebResponse response = request.GetResponse();
- using (Stream stream = response.GetResponseStream())
- {
- using (FileStream fileStream = new FileStream(WaveOutPath, FileMode.Create))
- {
- stream.CopyTo(fileStream);
- }
- }
- response.Close();
+ //Uri uri = new Uri(url);
+ ////返回 123.xlsx
+ //var filename = HttpUtility.UrlDecode(uri.Segments.Last());
+ ////获取文件后缀
+ //string ext = Path.GetExtension(filename);
+ //DateTime dateTime = DateTime.Now;
+ //string time = DateTime.Now.ToString(
+ // "yyyyMMddHHmmss", DateTimeFormatInfo.InvariantInfo);
+ //var dirpath = Path.Combine(Environment.CurrentDirectory, "wwwroot", "WaveOutFile");
+ //FileExt.MakeSureDirExist(dirpath);
+ //var filepath = Path.Combine(dirpath, time);
+
+ //WebRequest request = WebRequest.Create(url);
+ //WebResponse response = request.GetResponse();
+ //using (Stream stream = response.GetResponseStream())
+ //{
+ // using (FileStream fileStream = new FileStream(WaveOutPath, FileMode.Create))
+ // {
+ // stream.CopyTo(fileStream);
+ // }
+ //}
+ //response.Close();
+
+ WaveOutPath = url;
using (player = new WaveOutEvent())
{
player.PlaybackStopped += waveOut_PlaybackStopped;
diff --git a/DevicesService/Commen/Util.cs b/DevicesService/Commen/Util.cs
index 7afd431..bd7fd44 100644
--- a/DevicesService/Commen/Util.cs
+++ b/DevicesService/Commen/Util.cs
@@ -1,9 +1,13 @@
-using System;
+using DevicesService.Commen;
+using System;
+using System.Configuration;
using System.Diagnostics;
using System.Drawing;
+using System.Drawing.Imaging;
using System.Drawing.Printing;
using System.IO;
using System.IO.Compression;
+using System.Linq;
using Document = Aspose.Words.Document;
namespace DevicesService.Common
@@ -52,7 +56,7 @@ namespace DevicesService.Common
ms.Read(arr, 0, (int)ms.Length);
ms.Close();
bmp.Dispose();
- File.Delete(fileLocation);
+ //File.Delete(fileLocation);
return Convert.ToBase64String(arr);
}
return "";
@@ -176,5 +180,222 @@ namespace DevicesService.Common
}
return Convert.ToBase64String(decompressedData);
}
+
+ ///
+ /// 压缩图片至200 Kb以下
+ ///
+ /// 图片
+ /// 图片格式
+ /// 压缩后大小
+ /// 原始大小
+ /// 压缩后的图片
+ public static Image ZipImage(Image img, ImageFormat format, long targetLen, long srcLen = 0)
+ {
+ //设置大小偏差幅度 10kb
+ const long nearlyLen = 10240;
+ //内存流 如果参数中原图大小没有传递 则使用内存流读取
+ var ms = new MemoryStream();
+ if (0 == srcLen)
+ {
+ img.Save(ms, format);
+ srcLen = ms.Length;
+ }
+
+ //单位 由Kb转为byte 若目标大小高于原图大小,则满足条件退出
+ targetLen *= 1024;
+ if (targetLen > srcLen)
+ {
+ ms.SetLength(0);
+ ms.Position = 0;
+ img.Save(ms, format);
+ img = Image.FromStream(ms);
+ return img;
+ }
+
+ //获取目标大小最低值
+ var exitLen = targetLen - nearlyLen;
+
+ //初始化质量压缩参数 图像 内存流等
+ var quality = (long)Math.Floor(100.00 * targetLen / srcLen);
+ var parms = new EncoderParameters(1);
+
+ //获取编码器信息
+ ImageCodecInfo formatInfo = null;
+ var encoders = ImageCodecInfo.GetImageEncoders();
+ foreach (ImageCodecInfo icf in encoders)
+ {
+ if (icf.FormatID == format.Guid)
+ {
+ formatInfo = icf;
+ break;
+ }
+ }
+
+ //使用二分法进行查找 最接近的质量参数
+ long startQuality = quality;
+ long endQuality = 100;
+ quality = (startQuality + endQuality) / 2;
+
+ while (true)
+ {
+ //设置质量
+ parms.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
+
+ //清空内存流 然后保存图片
+ ms.SetLength(0);
+ ms.Position = 0;
+ img.Save(ms, formatInfo, parms);
+
+ //若压缩后大小低于目标大小,则满足条件退出
+ if (ms.Length >= exitLen && ms.Length <= targetLen)
+ {
+ break;
+ }
+ else if (startQuality >= endQuality) //区间相等无需再次计算
+ {
+ break;
+ }
+ else if (ms.Length < exitLen) //压缩过小,起始质量右移
+ {
+ startQuality = quality;
+ }
+ else //压缩过大 终止质量左移
+ {
+ endQuality = quality;
+ }
+
+ //重新设置质量参数 如果计算出来的质量没有发生变化,则终止查找。这样是为了避免重复计算情况{start:16,end:18} 和 {start:16,endQuality:17}
+ var newQuality = (startQuality + endQuality) / 2;
+ if (newQuality == quality)
+ {
+ break;
+ }
+ quality = newQuality;
+ //Console.WriteLine("start:{0} end:{1} current:{2}", startQuality, endQuality, quality);
+ }
+ img = Image.FromStream(ms);
+ return img;
+ }
+
+ ///
+ ///获取图片格式
+ ///
+ /// 图片
+ /// 默认返回JPEG
+ public static ImageFormat GetImageFormat(Image img)
+ {
+ if (img.RawFormat.Equals(ImageFormat.Jpeg))
+ {
+ return ImageFormat.Jpeg;
+ }
+ if (img.RawFormat.Equals(ImageFormat.Gif))
+ {
+ return ImageFormat.Gif;
+ }
+ if (img.RawFormat.Equals(ImageFormat.Png))
+ {
+ return ImageFormat.Png;
+ }
+ if (img.RawFormat.Equals(ImageFormat.Bmp))
+ {
+ return ImageFormat.Bmp;
+ }
+ return ImageFormat.Jpeg;//根据实际情况选择返回指定格式还是null
+ }
+
+ ///
+ /// 压缩图片
+ ///
+ ///
+ ///
+
+ public static string CompressPictures(FileInfo file)
+ {
+ Image image = null;
+ try
+ {
+ string fullpath = String.Empty;
+ //获取未压缩的图片进行压缩
+ if (file != null && file.Length > 0)
+ {
+ if (!file.Name.Contains("_compress"))
+ {
+ //压缩图片
+ image =GetPicThumbnail(file.FullName);
+ if (image != null)
+ {
+ //压缩后的图片,图片名称增加_compress
+ string newName = file.Name.Replace(file.Extension, "") + "_compress" + file.Extension;
+ fullpath = file.FullName.Replace(file.Name, newName);
+ image.Save(fullpath);
+ file.Delete();
+ }
+ }
+ else
+ {
+ fullpath = file.FullName;
+ }
+ }
+ return fullpath;
+ }
+ catch (Exception ex)
+ {
+ Log.Error(file.FullName);
+ Log.Error(ex.Message + "MainViewModel.CompressPictures");
+ return "";
+ }
+ finally
+ {
+ if (image != null)
+ image.Dispose();
+ }
+ }
+
+ ///
+ /// 图片压缩
+ ///
+ /// 图片路径
+ /// 压缩比1-100
+ /// 返回图片对象
+ public static Image GetPicThumbnail(string sFile)
+ {
+ int flag = Convert.ToInt32(ConfigurationManager.AppSettings["ysb"].ToString());
+ Image result = null;
+ if (sFile != null)
+ {
+ Image inputImage = Image.FromFile(sFile);
+ try
+ {
+ MemoryStream imgms = new MemoryStream();
+ var arrayICI = ImageCodecInfo.GetImageEncoders();
+ ImageCodecInfo jpegICIinfo = arrayICI.Where(w => w.FormatDescription.Contains("JPEG")).FirstOrDefault();
+ if (jpegICIinfo != null)
+ { //以下代码为保存图片时,设置压缩质量
+ var ep = new EncoderParameters()
+ {
+ Param = new EncoderParameter[]
+ {
+ new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, new long[1]{ flag})
+ }
+ };
+ inputImage.Save(imgms, jpegICIinfo, ep);
+ result = Image.FromStream(imgms);
+ }
+ return result;
+ }
+ catch (Exception ex)
+ {
+ throw ex;
+ }
+ finally
+ {
+ inputImage.Dispose();
+ }
+ }
+ else
+ {
+ return result;
+ }
+ }
}
}
diff --git a/DevicesService/Devices/HScamera.cs b/DevicesService/Devices/HScamera.cs
index de83ebf..323e36e 100644
--- a/DevicesService/Devices/HScamera.cs
+++ b/DevicesService/Devices/HScamera.cs
@@ -111,14 +111,14 @@ namespace DevicesService.Devices
var dirpath = Path.Combine(Environment.CurrentDirectory, "wwwroot", "Camera");
FileExt.MakeSureDirExist(dirpath);
var filepath = Path.Combine(dirpath, time);
- filename = dirpath + "\\" + time + ".jpg";
+ filename = dirpath + "\\" + time + ".jpg";
if (1 == EloamDll.EloamImage_Save(hImg, filename, 0))
{
EloamDll.EloamView_PlayCaptureEffect(m_hView);
}
EloamDll.EloamImage_Release(hImg);
//旋转图片
- filename = ImgToBase64String(filename);
+ //filename = ImgToBase64String(filename);
}
return filename;
}
@@ -154,7 +154,7 @@ namespace DevicesService.Devices
byte[] arr = new byte[ms.Length];
ms.Position = 0;
ms.Read(arr, 0, (int)ms.Length);
- string base64= Convert.ToBase64String(arr);
+ string base64 = Convert.ToBase64String(arr);
DateTime dateTime = DateTime.Now;
string time = DateTime.Now.ToString(
"yyyyMMddHHmmss", DateTimeFormatInfo.InvariantInfo);
@@ -179,7 +179,7 @@ namespace DevicesService.Devices
///
/// 图像翻转,基于图像中心
///
- private void BitmapFlip(int iFlip, ref Bitmap btDes)
+ public void BitmapFlip(int iFlip, ref Bitmap btDes)
{
switch (iFlip)
{
@@ -198,7 +198,7 @@ namespace DevicesService.Devices
}
- private void ConvertFromBase64ToImage(string base64String, string filePath)
+ public void ConvertFromBase64ToImage(string base64String, string filePath)
{
// 将Base64字符串转换为字节数组
byte[] imageBytes = Convert.FromBase64String(base64String);