BOOL BitBlt

BOOL BitBlt( int x, int y, int nWidth, int nHeight, CDC* pSrcDC, int xSrc, int ySrc, DWORD dwRop );

返回值:函数成功,返回非零值,否则为0。

参数: x 指定目标矩形左上角的逻辑x坐标。  
y 指定目标矩形左上角的逻辑y坐标。  
nWidth 指定目标矩形和源位图的宽度(逻辑单位)。  
nHeight 指定目标矩形和源位图的高度(逻辑单位)。  
pSrcDC 指向CDC对象的指针,标识待拷贝位图的设备上下文。如果dwRop指定不包括源的光栅操作,则它必须为NULL。  
xSrc 指定源位图左上角的逻辑X坐标。  
ySrc 指定源位图左上角的逻辑Y坐标。  
dwRop 指定要执行的光栅操作。光栅操作代码定义GDC如何合并输出操作中的颜色,包括当前画刷、可能的源位图和目标位图。
下面对dwRop列出光栅操作代码及其描述:
BLACKNESS 所有输出变黑。  
DSTINVERT 反转目标位图。  
MERGECOPY 使用布尔AND操作符合并特征与源位图。  
MERGEPAINT 使用布尔OR操作符合并特征与源位图。  
NOTSRCCOPY 拷贝反转源位图到目标。  
NOTSRCERASE 反转使用布尔OR操作符合并源和目标位图的结果。  
PATCOPY 拷贝特征到目标位图。  
PATINVERT 使用布尔XOR操作符合并目标位图和特征。  
PATPAINT 使用布尔OR操作符合并反转源位图和特征。用布尔OR操作符合并这项操作结果与目标位图。  
SRCAND 使用布尔AND操作符合并目标像素和源位图。  
SRCCOPY 拷贝源位图到目标位图。  
SRCERASE 反转目标位图并用布尔AND操作符合并这个结果和源位图。  
SRCINVERT 使用布尔XOR操作符合并目标像素和源位图。  
SRCPAINT 使用布尔OR操作符合并目标像素和源位图。  
WHITENESS 所有输出变白。  
有关光栅操作代码的完整列表,请参阅联机文档“Win32 SDK程序员参考”附录节中的“关于光栅操作代码”。  

说明:
从源设备上下文拷贝位图到这个当前设备上下文。
应用可以在字节边界上对齐窗口或客户区域,保证BitBlt操作发生在以字节对齐的矩形上(登记窗口类时设置设备CS_BYTEALLGNWINDOW或CS_BYTEALIGHCLIENT标记)。
在字节对齐矩形上的BitBlt操作比未经字节对齐的矩形上的BitBlt操作快许多。如果想对自己的设备上下文指定字节对齐类风格,必须登记窗口类而不要依赖Microsoft基本类。可使用全局函数AfxRegisterWndClass。
一旦使用目标设备上下文和使用源设备上下文,GDI变形nWidth和nHeight。如果结果延伸不匹配,必要时GDI使用Windows StretchBlt函数压缩或拉伸源位图。
如果目标、源和特征位图颜色格式不同,BitBlt转换源和特征位图以匹配目标。转换中使用目标位图的前景和背景色。
BitBlt函数把单色位图转换为彩色时,它设置白色(1)为背景色,黑色(0)作为前景色。使用目标设备上下文的背景和前景色。要把彩色转换为单色,BitBlt把与背景色匹配的像素设置为白色,其余所有像素设置为黑色。在从彩色到单色的转换中,BitBlt使用彩色设备上下文的前景和背景色。
注意,并非所有的设备上下文都支持BitBlt。为检查给定设备上下文是否支持BitBlt,使用GetDeviceCaps成员函数并指定RASTERCAPS索引。
using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using System.Runtime.InteropServices; using System.Drawing; using System.Collections; using System.IO; using System.Drawing.Imaging; using System.IO.Compression; using System.Diagnostics; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using Newtonsoft.Json; namespace Util { #region EnumStringAttribute [AttributeUsage(AttributeTargets.Field, AllowMultiple = false, Inherited = false)] public class EnumStringAttribute : System.Attribute { public EnumStringAttribute(string str) { this.enumStr = str; } public string GetEnumString() { return this.enumStr; } private string enumStr; } #endregion public class Util { /// <summary> /// 得到可执行程序所在的目录,最后具有分隔符“\\”。 /// </summary> /// <returns></returns> public static string GetApplicationPath() { return AppDomain.CurrentDomain.BaseDirectory; } /// <summary> /// 填充并显示窗体到Panel中 /// </summary> /// <param name="panel"></param> /// <param name="frm"></param> public static void fillShowFrmToPanel(Panel panel, Form frm) { if (panel.Controls.Contains(frm)) { return; } panel.Controls.Clear(); frm.TopLevel = false; panel.Controls.Add(frm); frm.FormBorderStyle = FormBorderStyle.None; frm.Dock = DockStyle.Fill; frm.Show(); } /// <summary> /// 将文件名中的非法字符替换为'_',得到有效的文件名 /// </summary> /// <param name="filename"></param> /// <returns></returns> public static string GetValidFileName(string filename) { string newname = filename; newname = newname.Replace('/', '_'); newname = newname.Replace('\\', '_'); newname = newname.Replace(':', '_'); newname = newname.Replace('*', '_'); newname = newname.Replace('?', '_'); newname = newname.Replace('"', '_'); newname = newname.Replace('<', '_'); newname = newname.Replace('>', '_'); newname = newname.Replace('|', '_'); newname = newname.Replace((char)0xA, ' '); return newname; } /// <summary> /// 将字符串转化为整数 /// </summary> /// <param name="val"></param> /// <param name="defVal"></param> /// <returns></returns> public static int ToInt(string val, int defVal) { if (string.IsNullOrEmpty(val)) return defVal; try { if (val.StartsWith("0x") || val.StartsWith("0X")) { return int.Parse(val.Substring(2, val.Length - 2), System.Globalization.NumberStyles.HexNumber); } else { return int.Parse(val); } } catch (Exception e) { Console.WriteLine("数据转换格式错误:val: {0} {1}", val, e.Message); return defVal; } } /// <summary> /// 将字符串转换为长整数。 /// </summary> /// <param name="val"></param> /// <param name="defVal"></param> /// <returns></returns> public static long ToLong(string val, long defVal) { if (string.IsNullOrEmpty(val)) return defVal; try { if (val.StartsWith("0x") || val.StartsWith("0X")) { return long.Parse(val.Substring(2, val.Length - 2), System.Globalization.NumberStyles.HexNumber); } else { return long.Parse(val); } } catch (Exception e) { Console.WriteLine("数据转换格式错误:val: {0} {1}", val, e.Message); return defVal; } } /// <summary> /// 将二进制转化为16进制字符串。 /// </summary> /// <param name="buf"></param> /// <returns></returns> public static string BinaryToString(byte[] buf, int maxLen) { if (buf == null) return ""; int count = Math.Min(buf.Length, maxLen); bool bOmit = count < buf.Length; StringBuilder sb = new StringBuilder(count * 2 + 30); for (int i = 0; i < count; ++i) { sb.Append(buf[i].ToString("X2")); } if (bOmit) sb.Append(string.Format(" ... Total {0} Bytes", buf.Length)); return sb.ToString(); } /// <summary> /// 将二进制转化为16进制字符串。 /// </summary> /// <param name="buf"></param> /// <param name="cntPerRow">每行显示几个字节</param> /// <returns></returns> public static string BinaryToStringFormat(byte[] buf, int cntPerRow) { if (buf == null) return ""; StringBuilder sb = new StringBuilder(buf.Length * 2); int cnt = 0; int cntall = 0; foreach (byte b in buf) { cnt++; cntall++; if (cnt == 1) { sb.Append((cntall - 1).ToString("d4")).Append(" : "); } sb.Append(b.ToString("X2")).Append(" "); if (cnt >= cntPerRow) { sb.AppendLine(); cnt = 0; } } return sb.ToString(); } /// <summary> /// 将字符串转化为二进制数据数组 /// </summary> /// <param name="str"></param> /// <returns></returns> public static byte[] BinaryFromString(string str) { if (string.IsNullOrEmpty(str)) return new byte[0]; str = str.Trim(); int len = str.Length / 2; byte[] buf = new byte[len + (str.Length % 2)]; for (int i = 0; i < len; ++i) { buf[i] = byte.Parse(str.Substring(i * 2, 2), System.Globalization.NumberStyles.HexNumber); } if ((str.Length % 2) > 0) { // 最后一个字符 buf[buf.Length - 1] = byte.Parse(str.Substring(str.Length - 1, 1), System.Globalization.NumberStyles.HexNumber); } return buf; } /// <summary> /// byte数组格式化为十六进制的字符串 /// </summary> /// <param name="buffer"></param> /// <param name="len">长度</param> /// <param name="spliter">分割符</param> /// <returns></returns> public static string BufferFormat(byte[] buffer, int len, char spliter) { StringBuilder sb = new StringBuilder(""); if (buffer == null) return sb.ToString(); for (int i = 0; i < len; ++i) { sb.Append(buffer[i].ToString("X2")).Append(spliter); } return sb.ToString(); } public static uint ColorToInt(Color color) { return (uint)(((uint)color.B << 16) | (ushort)(((ushort)color.G << 8) | color.R)); } public static Color IntToColor(int color) { int r = 0xFF & color; int g = 0xFF00 & color; g >>= 8; int b = 0xFF0000 & color; b >>= 16; return Color.FromArgb(r, g, b); } #region DllImport 把窗体导出为图片使用 [DllImport("user32.dll")] public static extern IntPtr GetWindowRect(IntPtr hWnd, ref Rectangle rect); [DllImport("gdi32.dll")] public static extern IntPtr CreateCompatibleDC(IntPtr hdc); [DllImport("gdi32.dll")] public static extern IntPtr CreateCompatibleBitmap(IntPtr hdc, int nWidth, int nHeight); [DllImport("gdi32.dll")] public static extern IntPtr SelectObject(IntPtr hdc, IntPtr hgdiobj); [DllImport("gdi32.dll")] public static extern int DeleteDC(IntPtr hdc); [DllImport("gdi32.dll")] public static extern bool BitBlt( IntPtr hdcDest, // 目的 DC的句柄 int nXDest, int nYDest, int nWidth, int nHeight, IntPtr hdcSrc, // 源DC的句柄 int nXSrc, int nYSrc, System.Int32 dwRop // 光栅的处置数值 ); [DllImport("user32.dll")] public static extern bool PrintWindow(IntPtr hwnd, IntPtr hdcBlt, UInt32 nFlags); [DllImport("user32.dll")] public static extern IntPtr GetWindowDC(IntPtr hwnd); #endregion /// <summary> /// 根据窗口句柄,把窗口显示导出图片(.bmp) /// </summary> /// <param name="hWnd"></param> /// <returns></returns> public static Bitmap GetWindowCapture(IntPtr hWnd) { IntPtr hscrdc = GetWindowDC(hWnd); Rectangle windowRect = new Rectangle(); GetWindowRect(hWnd, ref windowRect); int width = windowRect.Right - windowRect.Left; int height = windowRect.Bottom - windowRect.Top; IntPtr hbitmap = CreateCompatibleBitmap(hscrdc, width, height); IntPtr hmemdc = CreateCompatibleDC(hscrdc); SelectObject(hmemdc, hbitmap); PrintWindow(hWnd, hmemdc, 0); Bitmap bmp = Bitmap.FromHbitmap(hbitmap); DeleteDC(hscrdc);//删除用过的对象 DeleteDC(hmemdc);//删除用过的对象 return bmp; } public static string BufferFormatSimple(byte[] buffer) { return Util.BufferFormat(buffer, buffer.Length, ' '); } static Dictionary<string, List<string>> typeHash = new Dictionary<string, List<string>>(); /// <summary> /// 得到与枚举类型值相关联的字符串 /// </summary> /// <param name="type"></param> /// <returns></returns> public static List<string> GetEnumString(Type type) { if (typeHash.ContainsKey(type.ToString())) { return typeHash[type.ToString()]; } else { List<string> list = new List<string>(); System.Reflection.MemberInfo[] mis = type.GetMembers(); foreach (System.Reflection.MemberInfo mi in mis) { Attribute[] attrs = System.Attribute.GetCustomAttributes(mi); foreach (Attribute at in attrs) { if (at is EnumStringAttribute) { list.Add(((EnumStringAttribute)at).GetEnumString()); } } } typeHash[type.ToString()] = list; return list; } } static Hashtable enumValueHash = new Hashtable(); /// <summary> /// 由枚举类型及枚举显示字符串得到枚举数值。 /// 如 由 SexType "男" 得到 (int)SexType.Male /// </summary> /// <param name="enumType"></param> /// <param name="enumDisStr"></param> /// <returns></returns> public static int GetEnumValue(Type enumType, string enumDisStr) { string key = enumType.ToString() + enumDisStr; if (enumValueHash.Contains(key)) { return (int)enumValueHash[key]; } else { int ret = -1; System.Reflection.MemberInfo[] mis = enumType.GetMembers(); foreach (System.Reflection.MemberInfo mi in mis) { Attribute[] attrs = System.Attribute.GetCustomAttributes(mi); foreach (Attribute at in attrs) { if (at is EnumStringAttribute) { EnumStringAttribute esr = (EnumStringAttribute)at; if (esr.GetEnumString() == enumDisStr) { ret = (int)System.Enum.Parse(enumType, mi.Name); break; } } } if (ret != -1) break; } enumValueHash[key] = ret; return ret; } } static Hashtable enumStringHash = new Hashtable(); /// <summary> /// 有枚举类型及枚举值得到显示字符串。 /// 如 由 SexType (int)SexType.Male 得到 "男" /// </summary> /// <param name="enumType"></param> /// <param name="enumVal"></param> /// <returns></returns> public static string GetEnumDisString(Type enumType, int enumVal) { string key = enumType.ToString() + enumVal.ToString(); if (enumStringHash.Contains(key)) { return (string)enumStringHash[key]; } else { string ret = ""; System.Reflection.MemberInfo[] mis = enumType.GetMembers(); foreach (System.Reflection.MemberInfo mi in mis) { Attribute[] attrs = System.Attribute.GetCustomAttributes(mi); foreach (Attribute at in attrs) { if (at is EnumStringAttribute) { EnumStringAttribute esr = (EnumStringAttribute)at; //object obj = System.Enum.Parse(enumType, mi.Name); if ((int)System.Enum.Parse(enumType, mi.Name) == enumVal) { ret = esr.GetEnumString(); break; } } } if (ret != "") break; } enumStringHash[key] = ret; return ret; } } private static ImageCodecInfo GetEncoderInfo(string mimeType) { // Get image codecs for all image formats ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders(); // Find the correct image codec for (int i = 0; i < codecs.Length; i++) if (codecs[i].MimeType == mimeType) return codecs[i]; return null; } public static byte[] ConvertToJpgBuff(Image bmp, long quality) { // Encoder parameter for image quality EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality); // JPEG image codec ImageCodecInfo jpegCodec = GetEncoderInfo("image/jpeg"); EncoderParameters encoderParams = new EncoderParameters(1); encoderParams.Param[0] = qualityParam; MemoryStream msJpg = new MemoryStream(); bmp.Save(msJpg, jpegCodec, encoderParams); bmp.Dispose(); return msJpg.ToArray(); } /// <summary> /// Convert Image to Byte[] /// </summary> /// <param name="image"></param> /// <returns></returns> public static byte[] ImageToBytes(Image image) { ImageFormat format = image.RawFormat; using (MemoryStream ms = new MemoryStream()) { if (format.Equals(ImageFormat.Jpeg)) { image.Save(ms, ImageFormat.Jpeg); } else if (format.Equals(ImageFormat.Png)) { image.Save(ms, ImageFormat.Png); } else if (format.Equals(ImageFormat.Bmp)) { image.Save(ms, ImageFormat.Bmp); } else if (format.Equals(ImageFormat.Gif)) { image.Save(ms, ImageFormat.Gif); } else if (format.Equals(ImageFormat.Icon)) { image.Save(ms, ImageFormat.Icon); } else image.Save(ms, ImageFormat.Jpeg); byte[] buffer = new byte[ms.Length]; //Image.Save()会改变MemoryStream的Position,需要重新Seek到Begin ms.Seek(0, SeekOrigin.Begin); ms.Read(buffer, 0, buffer.Length); return buffer; } } /// <summary> /// Convert Byte[] to Image /// </summary> /// <param name="buffer"></param> /// <returns></returns> public static Image BytesToImage(byte[] buffer) { MemoryStream ms = new MemoryStream(buffer); Image image = System.Drawing.Image.FromStream(ms); return image; } /// <summary> /// Convert Byte[] to a picture and Store it in file /// </summary> /// <param name="fileName"></param> /// <param name="buffer"></param> /// <returns></returns> public static string CreateImageFromBytes(string fileName, byte[] buffer) { string file = fileName; Image image = BytesToImage(buffer); ImageFormat format = image.RawFormat; if (format.Equals(ImageFormat.Jpeg)) { file += ".jpeg"; } else if (format.Equals(ImageFormat.Png)) { file += ".png"; } else if (format.Equals(ImageFormat.Bmp)) { file += ".bmp"; } else if (format.Equals(ImageFormat.Gif)) { file += ".gif"; } else if (format.Equals(ImageFormat.Icon)) { file += ".icon"; } System.IO.FileInfo info = new System.IO.FileInfo(file); System.IO.Directory.CreateDirectory(info.Directory.FullName); File.WriteAllBytes(file, buffer); return file; } public static System.DateTime ConvertIntDateTime(long d) { System.DateTime time = System.DateTime.MinValue; System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); time = startTime.AddMilliseconds(d); return time; } public static long ConvertDateTimeInt(System.DateTime time) { //double intResult = 0; System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0)); long t = (time.Ticks - startTime.Ticks) / 10000; //除10000调整为13位 return t; } /// <summary> /// 压缩缓冲区 /// </summary> /// <param name="inBuff">输入待压缩缓冲区</param> /// <param name="outBuff">输出压缩后缓冲区</param> /// <returns></returns> public static Boolean CompressBuffer(byte[] inBuff, ref byte[] outBuff) { Boolean bLess = false; using (MemoryStream destination = new MemoryStream()) { using (GZipStream output = new GZipStream(destination, CompressionMode.Compress)) { output.Write(inBuff, 0, inBuff.Length); } destination.Flush(); outBuff = destination.ToArray(); bLess = (outBuff.Length < inBuff.Length); if (!bLess) outBuff = inBuff; } return bLess; } /// <summary> /// 解压缩缓冲区 /// </summary> /// <param name="inBuff">待解压缓冲区</param> /// <param name="outBuff">解压后缓冲区</param> /// <returns></returns> public static Boolean DecompressBuffer(byte[] inBuff, ref byte[] outBuff) { Stream source = new MemoryStream(inBuff); using (MemoryStream destination = new MemoryStream()) { using (GZipStream input = new GZipStream(source, CompressionMode.Decompress, true)) { byte[] bytes = new byte[4096]; int n; while ((n = input.Read(bytes, 0, bytes.Length)) != 0) { destination.Write(bytes, 0, n); } } destination.Flush(); destination.Position = 0; outBuff = destination.ToArray(); } return true; } /// <summary> /// 从指定目录获取指定扩展名的文件 /// </summary> /// <param name="path"></param> /// <param name="extNameArr"></param> /// <returns></returns> public static List<FileInfo> GetDirFiles(string path, params string[] extNameArr) { List<FileInfo> lst = new List<FileInfo>(); try { string[] dir = Directory.GetDirectories(path); //文件夹列表 DirectoryInfo fdir = new DirectoryInfo(path); FileInfo[] file = fdir.GetFiles(); if (file.Length != 0 || dir.Length != 0) //当前目录文件或文件夹不为空 { foreach (FileInfo f in file) //显示当前目录所有文件 { foreach(string extName in extNameArr) { if (extName.ToLower().IndexOf(f.Extension.ToLower()) >= 0) { lst.Add(f); break; } } } foreach (string d in dir) { GetDirFiles(d, extNameArr);//递归 } } } catch (Exception ex) { Console.WriteLine(ex.Message); } return lst; } public static int DBM2Int(string dbm) { if (string.IsNullOrEmpty(dbm) || dbm.Length != 3) { Debug.Assert(false, "节点DBM不能为空,且长度必须为3," + dbm); } int id = 0; char[] arr = dbm.ToCharArray(); for (int i = 0; i < arr.Length; i++) { id <<= 8; id |= (byte)arr[i]; } return id; } public static string Int2DBM(int id) { char[] arr = new char[3]; for (int i = 2; i >= 0; i--) { arr[i] = (char)(id & 0xFF); id >>= 8; } return new string(arr); } #region 将类和结构序列化和反序列化的方法 /// <summary> /// 序列化(把类和结构序列化) /// </summary> /// <param name="msg">结构信息</param> /// <returns></returns> //public static byte[] Serialize(object obj) //{ // try // { // string json = JsonConvert.SerializeObject(obj); // byte[] buffer = Encoding.UTF8.GetBytes(json); // return buffer; // } // catch (Exception e) // { // Console.WriteLine(e.Message); // //OutPutLog.WriteLog(LogLevel.Error, "Util.Serialize()错误 " + e.Message, LogObjType.Util.ToString()); // } // return null; //} public static byte[] Serialize(object obj) { try { IFormatter inFormatter = new BinaryFormatter(); MemoryStream stm = new MemoryStream(); inFormatter.Serialize(stm, obj); byte[] buffer = stm.ToArray(); stm.Close(); stm.Dispose(); return buffer; } catch (Exception e) { Console.WriteLine(e.Message); //OutPutLog.WriteLog(LogLevel.Error, "Util.Serialize()错误 " + e.Message, LogObjType.Util.ToString()); } return null; } /// <summary> /// 反序列化(类和结构的反序列化) /// </summary> /// <param name="buffer">串行数据</param> /// <returns></returns> //public static object Deserialize(byte[] buffer) //{ // try // { // string json = Encoding.UTF8.GetString(buffer); // return JsonConvert.DeserializeObject(json) ?? null; // } // catch (Exception e) // { // Console.WriteLine(e.Message); // //OutPutLog.WriteLog(LogLevel.Error, "Util.Deserialize() " + e.Message, LogObjType.Util.ToString()); // } // return null; //} public static object Deserialize(byte[] buffer) { try { MemoryStream stream = new MemoryStream(buffer); BinaryFormatter outFormatter = new BinaryFormatter(); object obj = outFormatter.Deserialize(stream); stream.Close(); stream.Dispose(); return obj; } catch (Exception e) { Console.WriteLine(e.Message); //OutPutLog.WriteLog(LogLevel.Error, "Util.Deserialize() " + e.Message, LogObjType.Util.ToString()); } return null; } #endregion } } 转换.net8.0
最新发布
08-20
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值