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 { public class Util { /// /// 文件转Base64码 /// /// /// public static string ConvertImageToBase64(string imagePath) { using (MemoryStream mStream = new MemoryStream()) { System.Drawing.Image image = System.Drawing.Image.FromFile(filename: imagePath); // 保存图片到MemoryStream流中,并用相应的图片格式 image.Save(mStream, image.RawFormat); // 转换图片流为字节数组 byte[] imageBytes = mStream.ToArray(); // 将字节数组转换为Base64字符串 string base64String = Convert.ToBase64String(imageBytes); image.Dispose(); mStream.Close(); return base64String; } } /// /// 文件转Base64码 /// /// /// public static string ImgToBase64String(string fileLocation) { MemoryStream ms = new MemoryStream(); try { if (System.IO.File.Exists(fileLocation)) { Bitmap bmp = new Bitmap(@fileLocation); BitmapFlip(90, ref bmp); bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); byte[] arr = new byte[ms.Length]; ms.Position = 0; ms.Read(arr, 0, (int)ms.Length); ms.Close(); bmp.Dispose(); //File.Delete(fileLocation); return Convert.ToBase64String(arr); } return ""; } catch (Exception ex) { return ex.Message; } finally { ms.Close(); } } /// /// 文件转Base64码 /// /// /// public static string ImgToBase64StringSign(string fileLocation) { MemoryStream ms = new MemoryStream(); try { if (System.IO.File.Exists(fileLocation)) { Bitmap bmp = new Bitmap(@fileLocation); //BitmapFlip(90, ref bmp); bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); byte[] arr = new byte[ms.Length]; ms.Position = 0; ms.Read(arr, 0, (int)ms.Length); ms.Close(); bmp.Dispose(); File.Delete(fileLocation); return Convert.ToBase64String(arr); } return ""; } catch (Exception ex) { return ex.Message; } finally { ms.Close(); } } /// /// 文件转Base64码 /// /// /// public static string ImgToBase64StringBySign(string fileLocation) { MemoryStream ms = new MemoryStream(); try { if (System.IO.File.Exists(fileLocation)) { Bitmap bmp1 = new Bitmap(fileLocation); Bitmap bmp = CutImageWhitePart(bmp1, 10);//new Bitmap(@fileLocation); BitmapFlip(90, ref bmp); bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); byte[] arr = new byte[ms.Length]; ms.Position = 0; ms.Read(arr, 0, (int)ms.Length); ms.Close(); bmp.Dispose(); bmp1.Dispose(); File.Delete(fileLocation); return Convert.ToBase64String(arr); } return ""; } catch (Exception ex) { return ex.Message; } finally { ms.Close(); } } /// /// 图像翻转,基于图像中心 /// public static void BitmapFlip(int iFlip, ref Bitmap btDes) { switch (iFlip) { case 0: break; case 90: btDes.RotateFlip(RotateFlipType.Rotate90FlipNone); break; case 180: btDes.RotateFlip(RotateFlipType.Rotate180FlipNone); break; case 270: btDes.RotateFlip(RotateFlipType.Rotate270FlipNone); break; } } /// /// 调用打印机打印 /// /// PDF文件路径 /// 打印机名称 public static void Print2(string docPath, string PrinterName) { Process p = new Process(); ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.WindowStyle = ProcessWindowStyle.Hidden; startInfo.UseShellExecute = true; startInfo.CreateNoWindow = true; startInfo.FileName = docPath; startInfo.Verb = "print"; startInfo.Arguments = @"/p /h \" + docPath + "\"\"" + PrinterName + "\""; p.StartInfo = startInfo; p.Start(); p.WaitForExit(); } /// /// string 转换为 base64 /// /// public static string str2Base64(string str) { byte[] b = System.Text.Encoding.UTF8.GetBytes(str); string result = Convert.ToBase64String(b); return result; } /// /// base64 转换为 string /// /// public static string Base64str2(string data) { byte[] c = Convert.FromBase64String(data); string result = System.Text.Encoding.UTF8.GetString(c); return result; } /// /// 对base64进行压缩 /// /// /// public static string CompressBase64(string base64Data) { byte[] data = Convert.FromBase64String(base64Data); byte[] compressedData; using (var memoryStream = new MemoryStream()) { using (var gzipStream = new GZipStream(memoryStream, CompressionMode.Compress, true)) { gzipStream.Write(data, 0, data.Length); gzipStream.Flush(); compressedData = memoryStream.ToArray(); } } return Convert.ToBase64String(compressedData); } /// /// 对base64进行解压 /// /// /// public static string DecompressBase64(string compressedBase64Data) { byte[] data = Convert.FromBase64String(compressedBase64Data); byte[] decompressedData; using (var memoryStream = new MemoryStream(data)) { using (var gzipStream = new GZipStream(memoryStream, CompressionMode.Decompress)) { using (var outputStream = new MemoryStream()) { gzipStream.CopyTo(outputStream); decompressedData = outputStream.ToArray(); } } } 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; } } /// /// 文件转base64 /// /// /// public static string FileToBase64(string filePath) { byte[] fileBytes = File.ReadAllBytes(filePath); string base64String = Convert.ToBase64String(fileBytes); return base64String; } /// /// 图片处理成电子签名大小 /// /// /// public static void ResizeImage(string originalImagePath, string resizedImagePath) { int width = 72; int height = 72; using (Image originalImage = Image.FromFile(originalImagePath)) { // 创建一个新的画布,在其上绘制调整大小后的图片 using (Bitmap resizedImage = new Bitmap(width, height)) { using (Graphics graphics = Graphics.FromImage(resizedImage)) { // 设置绘图质量 graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; // 清除背景并填充白色 graphics.Clear(Color.White); graphics.DrawImage(originalImage, new Rectangle(0, 0, width, height), new Rectangle(0, 0, originalImage.Width, originalImage.Height), GraphicsUnit.Pixel); // 保存调整大小后的图片 resizedImage.Save(resizedImagePath, ImageFormat.Png); } } } } /// /// 剪去图片空余白边 /// /// 源文件 /// 保留空白边比例 public static Bitmap CutImageWhitePart(Bitmap bmp, int WhiteBarRate) { int top = 0, left = 0; int right = bmp.Width, bottom = bmp.Height; Color white = Color.White; //寻找最上面的标线,从左(0)到右,从上(0)到下 for (int i = 0; i < bmp.Height; i++)//行 { bool find = false; for (int j = 0; j < bmp.Width; j++)//列 { Color c = bmp.GetPixel(j, i); if (IsWhite(c)) { top = i; find = true; break; } } if (find) break; } //寻找最左边的标线,从上(top位)到下,从左到右 for (int i = 0; i < bmp.Width; i++)//列 { bool find = false; for (int j = top; j < bmp.Height; j++)//行 { Color c = bmp.GetPixel(i, j); if (IsWhite(c)) { left = i; find = true; break; } } if (find) break; ; } //寻找最下边标线,从下到上,从左到右 for (int i = bmp.Height - 1; i >= 0; i--)//行 { bool find = false; for (int j = left; j < bmp.Width; j++)//列 { Color c = bmp.GetPixel(j, i); if (IsWhite(c)) { bottom = i; find = true; break; } } if (find) break; } //寻找最右边的标线,从上到下,从右往左 for (int i = bmp.Width - 1; i >= 0; i--)//列 { bool find = false; for (int j = 0; j <= bottom; j++)//行 { Color c = bmp.GetPixel(i, j); if (IsWhite(c)) { right = i; find = true; break; } } if (find) break; } int iWidth = right - left; int iHeight = bottom - left; int blockWidth = Convert.ToInt32(iWidth * WhiteBarRate / 100); bmp = Cut(bmp, left - blockWidth, top - blockWidth, right - left + 2 * blockWidth, bottom - top + 2 * blockWidth); return bmp; } /// /// 2014.6.13 来源于网络的一个函数 /// /// /// /// /// /// /// public static Bitmap Cut(Bitmap b, int StartX, int StartY, int iWidth, int iHeight) { if (b == null) { return null; } int w = b.Width; int h = b.Height; if (StartX >= w || StartY >= h) { return null; } if (StartX + iWidth > w) { iWidth = w - StartX; } if (StartY + iHeight > h) { iHeight = h - StartY; } try { Bitmap bmpOut = new Bitmap(iWidth, iHeight, PixelFormat.Format24bppRgb); Graphics g = Graphics.FromImage(bmpOut); g.DrawImage(b, new Rectangle(0, 0, iWidth, iHeight), new Rectangle(StartX, StartY, iWidth, iHeight), GraphicsUnit.Pixel); g.Dispose(); return bmpOut; } catch { return null; } } /// /// 2014.6.12 判断白色与否,非纯白色 /// /// /// public static bool IsWhite(Color c) { if (c.R < 245 || c.G < 245 || c.B < 245) return true; else return false; } } }