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(); } } /// /// 图像翻转,基于图像中心 /// 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; } } }