123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938 |
- using System;
- using System.Drawing;
- using System.Drawing.Imaging;
- using System.IO;
- using System.Text;
- using System.Threading;
- using System.Windows;
- using System.Windows.Media;
- using System.Windows.Media.Imaging;
-
- namespace Common.system
- {
- /// <summary>
- /// 图片帮助类
- /// 创建人:赵耀
- /// 创建时间:2018年11月1日
- /// </summary>
- public class ImageHelper
- {
- /// <summary>
- /// 通过FileStream 来打开文件,这样就可以实现不锁定Image文件,到时可以让多用户同时访问Image文件
- /// </summary>
- /// <param name="path">图片位置</param>
- /// <returns></returns>
- public static Bitmap ReadBitmapFile(string path)
- {
- try
- {
- if (File.Exists(path))
- {
- FileStream fs = File.OpenRead(path); //OpenRead
- int filelength = 0;
- filelength = (int)fs.Length; //获得文件长度
- byte[] image = new byte[filelength]; //建立一个字节数组
- fs.Read(image, 0, filelength); //按字节流读取
- System.Drawing.Image result = System.Drawing.Image.FromStream(fs);
- fs.Close();
- Bitmap bit = new Bitmap(result);
- return bit;
- }
- else
- {
- return null;
- }
- }
- catch (Exception)
- {
- return null;
- }
- }
- /// <summary>
- /// 通过FileStream 来打开文件,这样就可以实现不锁定Image文件,到时可以让多用户同时访问Image文件
- /// </summary>
- /// <param name="path">图片位置</param>
- /// <returns></returns>
- public static Image ReadImageFile(string path)
- {
- try
- {
- if (File.Exists(path))
- {
- FileStream fs = File.OpenRead(path); //OpenRead
- int filelength = 0;
- filelength = (int)fs.Length; //获得文件长度
- byte[] image = new byte[filelength]; //建立一个字节数组
- fs.Read(image, 0, filelength); //按字节流读取
- System.Drawing.Image result = System.Drawing.Image.FromStream(fs);
- fs.Close();
- return result;
- }
- else
- {
- return null;
- }
- }
- catch (Exception)
- {
- return null;
- }
- }
- /// <summary>
- /// 通过FileStream 来打开文件,这样就可以实现不锁定Image文件,到时可以让多用户同时访问Image文件
- /// </summary>
- /// <param name="path">图片位置</param>
- /// <returns></returns>
- public static BitmapImage ReadBitmapImageFile(string path)
- {
- BitmapImage bitmap = new BitmapImage();
- try
- {
- using (MemoryStream ms = new MemoryStream(File.ReadAllBytes(path)))
- {
- bitmap = new BitmapImage
- {
- DecodePixelHeight = 100
- };
- bitmap.BeginInit();
- bitmap.CacheOption = BitmapCacheOption.OnLoad;//设置缓存模式
- bitmap.StreamSource = ms;//通过StreamSource加载图片
- bitmap.EndInit();
- bitmap.Freeze();
- }
- return bitmap;
- }
- catch (Exception)
- {
- return null;
- }
- }
- #region 获取RGB
-
- private static Bitmap _Bitmap = null;
- private static StringBuilder sb = new StringBuilder();
-
- public static string GetRGB(int x, int y)
- {
- sb = new StringBuilder();
- try
- {
- System.Drawing.Color color = _Bitmap.GetPixel(x, y);
-
- sb.Append("RGB:(");
- sb.Append(color.R.ToString());
- sb.Append(",");
- sb.Append(color.G.ToString());
- sb.Append(",");
- sb.Append(color.B.ToString());
- sb.Append(")");
- }
- catch (Exception ex)
- {
- LogHelper.WriteErrLog("ImageHelper(GetRGB)" + ex.Message, ex);
- }
-
- return sb.ToString();
- }
-
- #endregion 获取RGB
-
- #region 截图统一方法
- /// <summary>
- /// 截图通用方法 创建人:赵耀 创建时间:2020年8月11日
- /// </summary>
- /// <param name="ScreenSize">截图的区域,设置new Rectangle(0, 0, 0, 0)为截全屏</param>
- /// <param name="ImageSavePath">图片存储路径,为空或null则保存到临时文件夹</param>
- /// <param name="IsRetImg">是否返回图片</param>
- /// <param name="bitmapimg">图片</param>
- /// <param name="level">压缩等级,0到100,0 最差质量,100 最佳</param>
- /// <returns></returns>
- public static bool GetScreenshot(Rectangle ScreenSize, string ImageSavePath, bool IsRetImg, out BitmapImage bitmapimg, long level = -1)
- {
- bitmapimg = null;
- try
- {
- System.Drawing.Size bounds = PrimaryScreen.DESKTOP;
- if (string.IsNullOrEmpty(ImageSavePath))
- {
- ImageSavePath = GetTempImagePath();//如果为空则指定临时存储路径
- }
- double scaleWidth = (bounds.Width * 1.0) / SystemParameters.PrimaryScreenWidth;
- double scaleHeight = (bounds.Height * 1.0) / SystemParameters.PrimaryScreenHeight;
- int width = bounds.Width;
- int height = bounds.Height;
- if (ScreenSize.Size != new System.Drawing.Size(0, 0))
- {
- width = (int)(ScreenSize.Size.Width * scaleWidth);
- height = (int)(ScreenSize.Size.Height * scaleHeight);
- }
- int l = (int)(ScreenSize.X * scaleWidth);
- int t = (int)(ScreenSize.Y * scaleHeight);
- if (_Bitmap != null)
- {
- _Bitmap.Dispose();
- }
- _Bitmap = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
- using (Graphics g = Graphics.FromImage(_Bitmap))
- {
- g.CopyFromScreen(l, t, 0, 0, _Bitmap.Size, CopyPixelOperation.SourceCopy);
- Compress(_Bitmap, ImageSavePath, level);
- }
- if (IsRetImg)
- {
-
- Uri uri = new Uri(ImageSavePath, UriKind.Absolute);
- bitmapimg = new BitmapImage(uri);
- }
- GC.Collect();
- return true;
- }
- catch (Exception ex)
- {
- LogHelper.WriteErrLog("【截图】(GetBitmapSource)截图失败," + ex.Message, ex);
- return false;
- }
- }
- /// <summary>
- /// 获取临时图片保存位置
- /// </summary>
- /// <returns></returns>
- public static string GetTempImagePath()
- {
- TimeSpan ts = DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0);
-
- string TempPath = FileToolsCommon.GetFileAbsolutePath("/temp/Screenshot/");
- FileToolsCommon.CreateDirectory(TempPath);
- TempPath += Convert.ToInt64(ts.TotalMilliseconds).ToString() + ".jpg";
- return TempPath;
- }
- #endregion 截图统一方法
-
- #region 图片压缩
-
- /// <summary>
- /// 图片压缩(降低质量以减小文件的大小) 创建人:赵耀 创建时间:2020年8月11日
- /// </summary>
- /// <param name="srcBitMap">传入的Bitmap对象</param>
- /// <param name="destFile">压缩后的图片保存路径</param>
- /// <param name="level">压缩等级,-1为config配置的值,0到100,0 最差质量,100 最佳</param>
- public static void Compress(Bitmap srcBitMap, string destFile, long level)
- {
- if (level <= -1)
- {
- int ImageCompressionLevel = int.Parse(FileToolsCommon.GetConfigValue("ImageCompressionLevel"));
- level = ImageCompressionLevel;
- }
- Stream s = new FileStream(destFile, FileMode.Create);
- Compress(srcBitMap, s, level);
- s.Close();
- }
-
- /// <summary>
- /// 图片压缩(降低质量以减小文件的大小) 创建人:赵耀 创建时间:2020年8月11日
- /// </summary>
- /// <param name="srcBitmap">传入的Bitmap对象</param>
- /// <param name="destStream">压缩后的Stream对象</param>
- /// <param name="level">压缩等级,0到100,0 最差质量,100 最佳</param>
- public static void Compress(Bitmap srcBitmap, Stream destStream, long level)
- {
- ImageCodecInfo myImageCodecInfo;
- System.Drawing.Imaging.Encoder myEncoder;
- EncoderParameter myEncoderParameter;
- EncoderParameters myEncoderParameters;
-
- //获取表示jpeg编解码器的imagecodecinfo对象
- myImageCodecInfo = GetEncoderInfo("image/jpeg");
-
- myEncoder = System.Drawing.Imaging.Encoder.Quality;
-
- myEncoderParameters = new EncoderParameters(1);
-
- myEncoderParameter = new EncoderParameter(myEncoder, level);
- myEncoderParameters.Param[0] = myEncoderParameter;
- srcBitmap.Save(destStream, myImageCodecInfo, myEncoderParameters);
- }
-
- /// <summary>
- /// 获取解码器 创建人:赵耀 创建时间2020年8月11日
- /// </summary>
- /// <param name="mimeType"></param>
- /// <returns></returns>
- private static ImageCodecInfo GetEncoderInfo(string mimeType)
- {
- int j;
- ImageCodecInfo[] encoders;
- encoders = ImageCodecInfo.GetImageEncoders();
- for (j = 0; j < encoders.Length; ++j)
- {
- if (encoders[j].MimeType == mimeType)
- {
- return encoders[j];
- }
- }
- return null;
- }
-
- /// <summary>
- /// 压缩图片 -测试方法 待完善 暂无用
- /// </summary>
- /// <param name="_bitmap">原图片</param>
- /// <param name="dFile">压缩后保存图片地址</param>
- /// <param name="flag">压缩质量(数字越小压缩率越高)1-100</param>
- /// <param name="size">压缩后图片的最大大小</param>
- /// <param name="sfsc">是否是第一次调用</param>
- /// <returns></returns>
- public static bool CompressImage(Bitmap _bitmap, string dFile, int flag = 90, int size = 300)
- {
- ////如果是第一次调用,原始图像的大小小于要压缩的大小,则直接复制文件,并且返回true
- //FileInfo firstFileInfo = new FileInfo(sFile);
- //if (sfsc == true && firstFileInfo.Length < size * 1024)
- //{
- // firstFileInfo.CopyTo(dFile);
- // return true;
- //}
- //Image iSource = Image.FromFile(sFile);
- Image iSource = _bitmap;
- ImageFormat tFormat = iSource.RawFormat;
- int dHeight = iSource.Height / 2;
- int dWidth = iSource.Width / 2;
- int sW, sH;
- //按比例缩放
- System.Drawing.Size tem_size = new System.Drawing.Size(iSource.Width, iSource.Height);
- if (tem_size.Width > dHeight || tem_size.Width > dWidth)
- {
- if ((tem_size.Width * dHeight) > (tem_size.Width * dWidth))
- {
- sW = dWidth;
- sH = (dWidth * tem_size.Height) / tem_size.Width;
- }
- else
- {
- sH = dHeight;
- sW = (tem_size.Width * dHeight) / tem_size.Height;
- }
- }
- else
- {
- sW = tem_size.Width;
- sH = tem_size.Height;
- }
-
- Bitmap ob = new Bitmap(dWidth, dHeight);
- Graphics g = Graphics.FromImage(ob);
-
- g.Clear(System.Drawing.Color.WhiteSmoke);
- g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
- g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
- g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
-
- g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);
-
- g.Dispose();
-
- //以下代码为保存图片时,设置压缩质量
- EncoderParameters ep = new EncoderParameters();
- long[] qy = new long[1];
- qy[0] = flag;//设置压缩的比例1-100
- EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
- ep.Param[0] = eParam;
-
- try
- {
- ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
- ImageCodecInfo jpegICIinfo = null;
- for (int x = 0; x < arrayICI.Length; x++)
- {
- if (arrayICI[x].FormatDescription.Equals("JPEG"))
- {
- jpegICIinfo = arrayICI[x];
- break;
- }
- }
- if (jpegICIinfo != null)
- {
- if (flag > 0)
- {
- ob.Save(dFile, jpegICIinfo, ep);//dFile是压缩后的新路径
- FileInfo fi = new FileInfo(dFile);
- if (fi.Length > 1024 * size)
- {
- flag -= 10;
- CompressImage(_bitmap, dFile, flag, size);
- }
- }
- //ob.Save(dFile, jpegICIinfo, ep);
- //FileInfo fi = new FileInfo(dFile);
- //bool IsAgain = false;
- //if (fi.Length > 1024 * size)
- //{
- // fi.CopyTo(dFile + fi.Length);
- // fi.Delete();
- // Bitmap newbitmap = ReadImageFile(dFile + fi.Length);
- // CompressImage(newbitmap, dFile, flag, size);
- // FileToolsCommon.DeleteFile(dFile + fi.Length);
- //}
- }
- else
- {
- ob.Save(dFile, tFormat);
- }
- return true;
- }
- catch
- {
- return false;
- }
- finally
- {
- iSource.Dispose();
- ob.Dispose();
- }
- }
- #endregion 图片压缩
-
- #region 截屏指定UI控件
- /// <summary>
- /// 保存图片
- /// </summary>
- /// <param name="ui">需要截图的UI控件</param>
- /// <param name="filePathName">图片保存地址 命名 1.png</param>
- /// <param name="width">图片宽</param>
- /// <param name="height">图片高</param>
- /// <param name="ImgWidth">转换后高</param>
- /// <param name="ImgHeight">转换后高</param>
- public static void SaveUI(FrameworkElement ui, string filePathName, int width, int height, int ImgWidth, int ImgHeight)
- {
- try
- {
- //在位图中呈现UI元素
- RenderTargetBitmap bmp = new RenderTargetBitmap(width, height, PrimaryScreen.DpiX, PrimaryScreen.DpiY, PixelFormats.Pbgra32);
- bmp.Render(ui);
-
- //定义切割矩形
- var cut = new Int32Rect(0, 0, width, height);
- //计算Stride
- var stride = bmp.Format.BitsPerPixel * cut.Width / 8;
- //声明字节数组
- byte[] data = new byte[cut.Height * stride];
-
- //调用CopyPixels
- bmp.CopyPixels(cut, data, stride, 0);
- new Thread(new ThreadStart(new Action(() =>
- {
- BitmapSource bitmapSource = BitmapSource.Create(width, height, PrimaryScreen.DpiX, PrimaryScreen.DpiY, PixelFormats.Bgr32, null, data, stride);
-
- BitmapEncoder encoder = new PngBitmapEncoder();
- encoder.Frames.Add(BitmapFrame.Create(bitmapSource));
- if (ImgWidth > 0)
- {
- Bitmap Img = new Bitmap(ImgWidth, ImgHeight);
- try
- {
- //MemoryStream memoryStream = new MemoryStream(data);
- //Bitmap bit = (Bitmap)Image.FromStream(memoryStream);
-
- MemoryStream memoryStream = new MemoryStream();
- encoder.Save(memoryStream);
- Bitmap bit = new Bitmap(memoryStream,true);
- if (ImgWidth - 2 < bit.Width)
- {
- try
- {
- Graphics g = Graphics.FromImage(Img);
- g.DrawImage(bit, new Rectangle(0, 0, ImgWidth, ImgHeight), new Rectangle(0, 0, bit.Width, bit.Height), GraphicsUnit.Pixel);
- g.Dispose();
- }
- catch
- {
- Img = bit;
- }
- }
- else
- {
- Img = bit;
- }
- Img.Save(filePathName);
- memoryStream.Dispose();
- Img.Dispose();
- bit.Dispose();
- }
- catch (Exception ex)
- {
- using (var stream = new FileStream(filePathName, FileMode.Create))
- {
- encoder.Save(stream);
- }
- }
- }
- else
- {
- using (var stream = new FileStream(filePathName, FileMode.Create))
- {
- encoder.Save(stream);
- }
- }
- }))).Start();
- }
- catch (Exception ex)
- {
-
- }
- }
-
- /// <summary>
- /// 保存图片
- /// </summary>
- /// <param name="ui">需要截图的UI控件</param>
- /// <param name="filePathName">图片保存地址 命名 1.png</param>
- /// <param name="width">窗口宽</param>
- /// <param name="height">窗口高</param>
- /// <param name="ImgWidth">图片高</param>
- /// <param name="ImgHeight">图片高</param>
- public static void SaveUIToImage(FrameworkElement ui, string filePathName, int width, int height, int ImgWidth, int ImgHeight)
- {
- try
- {
- //在位图中呈现UI元素
- RenderTargetBitmap bmp = new RenderTargetBitmap(width, height, PrimaryScreen.DpiX, PrimaryScreen.DpiY, PixelFormats.Pbgra32);
- bmp.Render(ui);
- BitmapEncoder encoder = new PngBitmapEncoder();
- encoder.Frames.Add(BitmapFrame.Create(bmp));
- if (ImgWidth > 0)
- {
- Bitmap Img = new Bitmap(ImgWidth, ImgHeight);
- try
- {
- MemoryStream memoryStream = new MemoryStream();
- encoder.Save(memoryStream);
- new Thread(new ThreadStart(new Action(() =>
- {
- //System.Drawing.Image img = System.Drawing.Image.FromStream(memoryStream);
- Bitmap bit = new Bitmap(memoryStream);
- if (ImgWidth - 2 < bit.Width)
- {
- try
- {
- Graphics g = Graphics.FromImage(Img);
- //g.InterpolationMode = InterpolationMode.HighQualityBicubic;
- g.DrawImage(bit, new Rectangle(0, 0, ImgWidth, ImgHeight), new Rectangle(0, 0, bit.Width, bit.Height), GraphicsUnit.Pixel);
- g.Dispose();
- }
- catch
- {
- Img = bit;
- }
- }
- else
- {
- Img = bit;
- }
- Img.Save(filePathName);
- //Bitmap bitmap = CutImageWhitePart(Img);
- //FileToolsCommon.DeleteFile(filePathName);
- //bitmap.Save(filePathName);
- //bitmap.Dispose();
- memoryStream.Dispose();
- Img.Dispose();
- bit.Dispose();
- }))).Start();
- }
- catch (Exception)
- {
-
- }
- }
- else
- {
- //SaveImageModel sim = new SaveImageModel();
- //sim.encoder = new PngBitmapEncoder();
- //sim.encoder = new PngBitmapEncoder();
- //BitmapFrame test= encoder.Frames[0];
- //sim.encoder.Frames.Add(BitmapFrame.Create(test));
- ////sim.encoder.Frames[0].CopyTo(encoder.Frames[0]);
- ////sim.encoder.CopyTo(encoder);
- ////encoder.CopyTo(sim.encoder);
- //sim.FilePath = filePathName;
- ////sim.bmp = new RenderTargetBitmap(width, height, PrimaryScreen.DpiX, PrimaryScreen.DpiY, PixelFormats.Pbgra32);
- ////bmp.CopyTo(sim.bmp);
- //Thread t1 = new Thread(SaveImage);
- //t1.Start(sim);
-
- System.IO.FileStream fs = new System.IO.FileStream(filePathName, System.IO.FileMode.Create);
- encoder.Save(fs);
- fs.Close();
- }
- }
- catch (Exception ex)
- {
- LogHelper.WriteErrLog("【UI生成图片】(SaveUIToImage)" + ex.Message, ex);
- //Console.WriteLine(ex.Message);
- }
- }
- public static void SaveUI1(FrameworkElement ui, string filePathName, int width, int height, int ImgWidth, int ImgHeight)
- {
- try
- {
- //在位图中呈现UI元素
- RenderTargetBitmap bmp = new RenderTargetBitmap(width, height, PrimaryScreen.DpiX, PrimaryScreen.DpiY, PixelFormats.Pbgra32);
- bmp.Render(ui);
-
- //BitmapEncoder encoder = new PngBitmapEncoder();
- //encoder.Frames.Add(BitmapFrame.Create(bmp));
-
- //BitmapSource bitmapSource= bmp.Clone();
-
-
-
- //定义切割矩形
- var cut = new Int32Rect(0, 0, width, height);
- //计算Stride
- var stride = bmp.Format.BitsPerPixel * cut.Width / 8;
- //声明字节数组
- byte[] data = new byte[cut.Height * stride];
-
- //调用CopyPixels
- bmp.CopyPixels(cut, data, stride, 0);
- new Thread(new ThreadStart(new Action(() =>
- {
- BitmapSource bitmapSource = BitmapSource.Create(width, height, PrimaryScreen.DpiX, PrimaryScreen.DpiY, PixelFormats.Bgr32, null, data, stride);
-
- BitmapEncoder encoder = new PngBitmapEncoder();
- encoder.Frames.Add(BitmapFrame.Create(bitmapSource));
-
- using (var stream = new FileStream(filePathName, FileMode.Create))
- {
- encoder.Save(stream);
- }
- }))).Start();
- //SaveModel saveModel = new SaveModel();
- //saveModel.ImgWidth = ImgWidth;
- //saveModel.ImgHeight = ImgHeight;
- //saveModel.filePathName = filePathName;
- //saveModel.bmp = bmp;
- //saveModel.encoder =new PngBitmapEncoder();
- //foreach (BitmapFrame eitem in encoder.Frames)
- //{
- // saveModel.encoder = new PngBitmapEncoder();
- // saveModel.encoder.Frames.Add( eitem );
- //}
-
- //Thread myThread = new Thread(SaveImage);
- //myThread.Start(saveModel);
- }
- catch (Exception ex)
- {
-
- }
-
- }
- public static void SaveImage(object model)
- {
- try
- {
- SaveModel saveModel = (SaveModel)model;
- int ImgWidth = saveModel.ImgWidth;
- int ImgHeight = saveModel.ImgHeight;
- //BitmapEncoder encoder = saveModel.encoder;
- RenderTargetBitmap bmp = saveModel.bmp;
- BitmapEncoder encoder = new PngBitmapEncoder();
- encoder.Frames.Add(BitmapFrame.Create(bmp));
- string filePathName = saveModel.filePathName;
- if (ImgWidth > 0)
- {
- Bitmap Img = new Bitmap(ImgWidth, ImgHeight);
- try
- {
- MemoryStream memoryStream = new MemoryStream();
- encoder.Save(memoryStream);
- new Thread(new ThreadStart(new Action(() =>
- {
- //System.Drawing.Image img = System.Drawing.Image.FromStream(memoryStream);
- Bitmap bit = new Bitmap(memoryStream);
- if (ImgWidth - 2 < bit.Width)
- {
- try
- {
- Graphics g = Graphics.FromImage(Img);
- //g.InterpolationMode = InterpolationMode.HighQualityBicubic;
- g.DrawImage(bit, new Rectangle(0, 0, ImgWidth, ImgHeight), new Rectangle(0, 0, bit.Width, bit.Height), GraphicsUnit.Pixel);
- g.Dispose();
- }
- catch
- {
- Img = bit;
- }
- }
- else
- {
- Img = bit;
- }
- Img.Save(filePathName);
- //Bitmap bitmap = CutImageWhitePart(Img);
- //FileToolsCommon.DeleteFile(filePathName);
- //bitmap.Save(filePathName);
- //bitmap.Dispose();
- memoryStream.Dispose();
- Img.Dispose();
- bit.Dispose();
- }))).Start();
- }
- catch (Exception ex)
- {
-
- }
- }
- else
- {
- //SaveImageModel sim = new SaveImageModel();
- //sim.encoder = new PngBitmapEncoder();
- //sim.encoder = new PngBitmapEncoder();
- //BitmapFrame test= encoder.Frames[0];
- //sim.encoder.Frames.Add(BitmapFrame.Create(test));
- ////sim.encoder.Frames[0].CopyTo(encoder.Frames[0]);
- ////sim.encoder.CopyTo(encoder);
- ////encoder.CopyTo(sim.encoder);
- //sim.FilePath = filePathName;
- ////sim.bmp = new RenderTargetBitmap(width, height, PrimaryScreen.DpiX, PrimaryScreen.DpiY, PixelFormats.Pbgra32);
- ////bmp.CopyTo(sim.bmp);
- //Thread t1 = new Thread(SaveImage);
- //t1.Start(sim);
-
- System.IO.FileStream fs = new System.IO.FileStream(filePathName, System.IO.FileMode.Create);
- encoder.Save(fs);
- fs.Close();
- }
- }
- catch (Exception ex)
- {
-
- }
- }
- /// <summary>
- /// 截图转换成bitmap
- /// </summary>
- /// <param name="element"></param>
- /// <param name="width">默认控件宽度</param>
- /// <param name="height">默认控件高度</param>
- /// <param name="x">默认0</param>
- /// <param name="y">默认0</param>
- /// <returns></returns>
- public static Bitmap ToBitmap(FrameworkElement element, string filePathName, int width = 0, int height = 0, int x = 0, int y = 0)
- {
- if (width == 0) width = (int)element.ActualWidth;
- if (height == 0) height = (int)element.ActualHeight;
-
- var rtb = new RenderTargetBitmap(width, height, x, y, System.Windows.Media.PixelFormats.Default);
- rtb.Render(element);
- var bit = BitmapSourceToBitmap(rtb);
-
- //测试代码
- DirectoryInfo d = new DirectoryInfo(System.IO.Path.Combine(Directory.GetCurrentDirectory(), "Cache"));
- if (!d.Exists) d.Create();
- bit.Save(System.IO.Path.Combine(d.FullName, "控件截图.png"));
-
- return bit;
- }
-
- /// <summary>
- /// BitmapSource转Bitmap
- /// </summary>
- /// <param name="source"></param>
- /// <returns></returns>
- public static Bitmap BitmapSourceToBitmap(BitmapSource source)
- {
- return BitmapSourceToBitmap(source, source.PixelWidth, source.PixelHeight);
- }
-
- /// <summary>
- /// Convert BitmapSource to Bitmap
- /// </summary>
- /// <param name="source"></param>
- /// <returns></returns>
- public static Bitmap BitmapSourceToBitmap(BitmapSource source, int width, int height)
- {
- Bitmap bmp = null;
- try
- {
- System.Drawing.Imaging.PixelFormat format = System.Drawing.Imaging.PixelFormat.Format24bppRgb;
- /*set the translate type according to the in param(source)*/
- switch (source.Format.ToString())
- {
- case "Rgb24":
- case "Bgr24": format = System.Drawing.Imaging.PixelFormat.Format24bppRgb; break;
- case "Bgra32": format = System.Drawing.Imaging.PixelFormat.Format32bppPArgb; break;
- case "Bgr32": format = System.Drawing.Imaging.PixelFormat.Format32bppRgb; break;
- case "Pbgra32": format = System.Drawing.Imaging.PixelFormat.Format32bppArgb; break;
- }
- bmp = new Bitmap(width, height, format);
- BitmapData data = bmp.LockBits(new System.Drawing.Rectangle(System.Drawing.Point.Empty, bmp.Size),
- ImageLockMode.WriteOnly,
- format);
- source.CopyPixels(Int32Rect.Empty, data.Scan0, data.Height * data.Stride, data.Stride);
- bmp.UnlockBits(data);
- }
- catch
- {
- if (bmp != null)
- {
- bmp.Dispose();
- bmp = null;
- }
- }
-
- return bmp;
- }
- private static void SaveImage1(object obj)
- {
- SaveImageModel sim = (SaveImageModel)obj;
- //RenderTargetBitmap bmp = sim.bmp;
- //BitmapEncoder encoder = new PngBitmapEncoder();
- //encoder.Frames.Add(BitmapFrame.Create(bmp));
- BitmapEncoder encoder = sim.encoder;
- string filePathName = sim.FilePath;
- System.IO.FileStream fs = new System.IO.FileStream(filePathName, System.IO.FileMode.Create);
- encoder.Save(fs);
- fs.Close();
- }
-
- #endregion
-
- #region 去掉白边
- /// <summary>
- /// 裁剪图片(去掉白边)
- /// </summary>
- /// <param name="FilePath"></param>
- public static Bitmap CutImageWhitePart(Bitmap bmp)
- {
- //Bitmap bmp = new Bitmap(FilePath);
- //上左右下
- int top = 0, left = 0, right = bmp.Width, bottom = bmp.Height;
-
- //寻找最上面的标线,从左(0)到右,从上(0)到下
- for (int i = 0; i < bmp.Height; i++)//行
- {
- bool find = false;
- for (int j = 0; j < bmp.Width; j++)//列
- {
- System.Drawing.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++)//行
- {
- System.Drawing.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++)//列
- {
- System.Drawing.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++)//行
- {
- System.Drawing.Color c = bmp.GetPixel(i, j);
- if (!IsWhite(c))
- {
- right = i;
- find = true;
- break;
- }
- }
- if (find)
- {
- break;
- }
- }
-
- if (right - left <= 0)//zxyceshi
- {
- //克隆位图对象的一部分。
- System.Drawing.Rectangle cloneRect = new System.Drawing.Rectangle(left, top, 1, bottom - top);
- Bitmap cloneBitmap = bmp.Clone(cloneRect, bmp.PixelFormat);
- bmp.Dispose();
- //cloneBitmap.Save(@"d:\123.png", ImageFormat.Png);
- return cloneBitmap;
- }
- else
- {
- //克隆位图对象的一部分。
- System.Drawing.Rectangle cloneRect = new System.Drawing.Rectangle(left, top, right - left, bottom - top);
- Bitmap cloneBitmap = bmp.Clone(cloneRect, bmp.PixelFormat);
- bmp.Dispose();
- //cloneBitmap.Save(@"d:\123.png", ImageFormat.Png);
- return cloneBitmap;
- }
-
- }
-
- /// <summary>
- /// 判断是否白色和纯透明色(10点的容差)
- /// </summary>
- public static bool IsWhite(System.Drawing.Color c)
- {
- //纯透明也是白色,RGB都为255为纯白
- if (c.A < 10 || (c.R > 245 && c.G > 245 && c.B > 245))
- {
- return true;
- }
-
- return false;
- }
- #endregion
- }
- public class SaveImageModel
- {
- public string FilePath { get; set; }
- public BitmapEncoder encoder { get; set; }
- //public RenderTargetBitmap bmp { get; set; }
- }
- public class SaveModel
- {
- public int ImgWidth { get; set; }
- public int ImgHeight { get; set; }
- public BitmapEncoder encoder { get; set; }
- public string filePathName { get; set; }
- public RenderTargetBitmap bmp { get; set; }
- }
- }
|