笔记本电脑黑屏大佬进来看看

&?xml version=&1.0& encoding=&utf-8&?&&Snippet&&Entry KeyWord=&index,primary key,CONSTRAINT(2011)& ActionWord=& & Tipo=&1& Flag=&0&&USE [Warehouse]
/* BYDBA 1 不建议使用联合主键,而是用自增列配合&创建唯一约束&或&创建唯一索引&
&& &--创建唯一约束的方法
&& &CREATE TABLE tb_test
&& &&& &id&& &INT IDENTITY&& &NOT NULL,
&& &&& &UniqueASNNumber&& &CHAR(10)&& &NOT NULL,
&& &&& &PackageLabel&& &CHAR(12)&& &NOT NULL constraint DF_tb_PackageLabel default(''),&& &
&& &&& &CONSTRAINT PK_TABLE PRIMARY KEY (id),
&& &&& &CONSTRAINT UK_TABLE UNIQUE (PackageLabel, UniqueASNNumber)
&& &--创建唯一索引的方法
&& &CREATE UNIQUE NONCLUSTERED INDEX [IXU_TABLE_CODE1_CODE2] ON dbo.[TABLE]
&& &&& &[Code1],[Code2]
&& &)WITH (FILLFACTOR=90) ON [PRIMARY]
--覆盖索引
create nonclustered index ix_itemRateOfCustomer_item_CountryCode_CompanyCode on& itemRateOfCustomer
(item) include(CountryCode,CompanyCode) WITH (FILLFACTOR=90) ON [PRIMARY]
--添加主键----------
ALTER TABLE 表名
ADD CONSTRAINT [PK_表名] PRIMARY KEY CLUSTERED(ID,Name)
--添加主键已经其他属性
ALTER TABLE ttt WITH NOCHECK
ADD CONSTRAINT PK_TransactionHistoryArchive_TransactionID PRIMARY KEY CLUSTERED (id)
WITH (FILLFACTOR = 75, ONLINE = ON, PAD_INDEX = ON);
---删除主键--------------
ALTER TABLE DropShipPickingShortage
Drop CONSTRAINT PK_DropShipPickingShortage
---创建索引
CREATE NONCLUSTERED INDEX IX_TABLE1_FIELD ON dbo.TABLE1
&& &[FIELD] ASC
)WITH (FILLFACTOR = 90) ON [PRIMARY]
--删除索引----------------
IF EXISTS (
SELECT 1 FROM sys.indexes WITH(NOLOCK)
WHERE object_id = OBJECT_ID(N'[dbo].[arinvt01]') AND [name] = N'IX_arinvt01_filed'
DROP INDEX IX_arinvt01_filed ON [dbo].[arinvt01] WITH ( ONLINE = OFF )
--删除列----------------
alter table& ItemXmlProperties
drop column TransactionNumber
--删除统计信息-----------------
IF EXISTS (
&& &&& &SELECT 1
&& &&& &FROM sys.stats WITH(NOLOCK)
&& &&& &WHERE object_id = OBJECT_ID(N'[dbo].[arinvt01]')
&& &&& &&& &AND [name] = N'Statistic_BEG_ACC')
DROP STATISTICS [dbo].[Arinvt01].[Statistic_BEG_ACC]
---添加默认属性
ALTER TABLE [dbo].[IM_ItemPriceChangeBuffer]
ADD CONSTRAINT DF_IM_ItemPriceChangeBuffer_PromotionDescription
DEFAULT ('') FOR PromotionDescription
---添加默认属性跟新现有行
ALTER TABLE dbo.doc_exf
ADD AddDate smalldatetime NULL
CONSTRAINT DF_doc_exf_AddDate
DEFAULT GETDATE() WITH VALUES ;
-----删除默认属性
if exists(
select 1 from sys.default_constraints
where parent_object_id =object_id('IM_Warranty')
and name='DF_IM_Warranty_WarrantyName'
ALTER TABLE IM_Warranty DROP CONSTRAINT DF_Jobs_JobId
------添加新列,约束
ALTER TABLE dbo.doc_exc
ADD column_b VARCHAR(20) NULL
CONSTRAINT exb_unique UNIQUE ;
---添加约束,将使用WITH NOCHECK 以避免根据现有行验证该约束,从而允许添加该约束。
ALTER TABLE dbo.doc_exd
WITH NOCHECK
ADD CONSTRAINT exd_check CHECK (column_a & 1) ;
----更改列的排序规则
ALTER TABLE T3
ALTER COLUMN C2 varchar(50) COLLATE Latin1_General_BIN
------添加外键---------
ALTER TABLE Person.ContactBackup
ADD CONSTRAINT FK_ContactBacup_Contact FOREIGN KEY (ContactID)
REFERENCES Person.Person (BusinessEntityID) ;
--配置表的更改跟踪
--下面的示例启用AdventureWorks2008R2 数据库中Person.Person 表的更改跟踪。
USE AdventureWorks2008R2;
ALTER TABLE Person.Person
ENABLE CHANGE_TRACKING;
--下面的示例启用更改跟踪,并启用在进行某项更改期间会进行更新的列的跟踪。
USE AdventureWorks2008R2;
ALTER TABLE Person.Person
ENABLE CHANGE_TRACKING
WITH (TRACK_COLUMNS_UPDATED = ON)
--下面的示例禁用AdventureWorks2008R2 数据库中Person.Person 表的更改跟踪。
USE AdventureWorks2008R2;
ALTER TABLE Person.Person
DISABLE CHANGE_TRACKING;
-----下面的三个语句添加名为CS 的列集,然后将列C2 和C3 修改为SPARSE。
ALTER TABLE T2
ADD CS XML COLUMN_SET FOR ALL_SPARSE_COLUMNS ;
ALTER TABLE T2
ALTER COLUMN C2 ADD SPARSE ;
ALTER TABLE T2
ALTER COLUMN C3 ADD SPARSE ;
--------------------------禁用约束,启用约束-------------------
CREATE st_example
(id INT NOT NULL,
&name VARCHAR(10) NOT NULL,
&salary MONEY NOT NULL
&&& CONSTRAINT salary_cap CHECK (salary & 100000)
-- Valid inserts
INSERT st_example VALUES (1,'Joe Brown',65000);
INSERT st_example VALUES (2,'Mary Smith',75000);
-- This insert violates the constraint.
INSERT st_example VALUES (3,'Pat Jones',105000);
-- Disable the constraint and try again.
ALTER st_example NOCHECK CONSTRAINT salary_
INSERT st_example VALUES (3,'Pat Jones',105000);
-- Re-enable the constraint an this will fail.
ALTER st_example CHECK CONSTRAINT salary_
INSERT st_example VALUES (4,'Eric James',110000) ;
&/Entry&&Entry KeyWord=&Query Job
(2011)& ActionWord=& & Tipo=&1& Flag=&0&&--CMD Query Job
select * from dbo.sysjobs a
inner join dbo.sysjobsteps b
on a.job_id = b.job_id
mand like '%UP_EC_InsertRMAExtendedWarrantyItem%'
--CMD Query Job
sp_help_jobschedule @job_id =''
&/Entry&&Entry KeyWord=&_MarkDelete sp_rename(2011)& ActionWord=& & Tipo=&1& Flag=&0&& _MarkDelete__UP_SPNAME
---rename 主键
EXEC sp_rename '[ItemPriceSetting].PK_tmp_ItemPriceSetting','PK_ItemPriceSetting','index'
EXEC sp_rename '[tmp_ItemPriceSetting]','ItemPriceSetting'&/Entry&&Entry KeyWord=&Query Replication(2011)& ActionWord=&#queryRep& Tipo=&1& Flag=&0&&use distribution
select *,(select drop_publication as [*] FOR XML PATH ('root'),TYPE ) from
&&& DISTINCT p.publication
&& ,ss.name AS subscriber
&& ,p.publisher_db
&& ,a.article
&& ,s.Subscriber_DB --,ss.server_id,P.*
&& &,CHAR(10)+CHAR(10)+
'use '+p.publisher_db+CHAR(10)+' go'+CHAR(10)+
'EXEC sp_Dropsubscription @publication = N'''+p.publication+''''+CHAR(10)+
&&& ',@subscriber = N'''+ss.name+''''+CHAR(10)+
&&& ',@destination_db = N'''+Subscriber_DB+''''+CHAR(10)+
&&& ',@article = N'''+a.article+''''+CHAR(10)+
'EXEC sp_DropArticle @publication = N'''+p.publication+''''+CHAR(10)+
&&& ',@article = N'''+a.article+''''+CHAR(10)+CHAR(10)
&as drop_publication
FROM dbo.MSsubscriptions AS s WITH (NOLOCK)
INNER JOIN sys.servers AS ss WITH (NOLOCK)
&&& ON s.subscriber_id =ss.server_id
INNER JOIN dbo.MSpublications AS p WITH (NOLOCK)
&&& ON p.publisher_id=s.publisher_id
&&& AND p.publisher_db=s.publisher_db
&&& AND p.publication_id = s.publication_id
INNER JOIN dbo.MSarticles AS a
&&& ON p.publisher_id=a.publisher_id
&&& AND p.publisher_db=a.publisher_db
&&& AND p.publication_id = a.publication_id
&&& a.article ='SAPSD_MKP_InventoryStorageFee'
) C&/Entry&&Entry KeyWord=&ipaddress(2011)& ActionWord=& & Tipo=&1& Flag=&0&&
select distinct @@SERVERNAME server,local_net_address as ip,local_tcp_port sqlport from sys.dm_exec_connections
where net_transport='tcp' and protocol_type='tsql'
SELECT @@SERVERNAME, name,port FROM master.sys.tcp_endpoints
where [type]=3 and type_desc='SERVICE_BROKER'
&/Entry&&Entry KeyWord=&动态 sp_executesql (2011)& ActionWord=& & Tipo=&1& Flag=&0&&declare @num int,@sql nvarchar(4000),@
set @num=245;
set @sql=N'select @count1=count(*) from dbo.tb_ErrorLog where error_number=@num1';
exec sp_executesql @sql, N'@num1 int,@count1 int output', @num1=@num,@count1=@count output
select @count
--- like 传参数
declare @sql nvarchar(4000)
set @sql='select * from tb where name like @name'
exec sp_executesql @sql ,N'@name varchar(50)',@name='%fs%'
&/Entry&&Entry KeyWord=&job disable&rename(2011)& ActionWord=& & Tipo=&1& Flag=&0&&
EXEC msdb..sp_update_job @job_name = N'job',
&@new_name = N'MarkDelete__job',@enabled=0
&/Entry&&Entry KeyWord=&查看hosts 文件(2011)& ActionWord=& & Tipo=&1& Flag=&0&&declare @t table
id int identity(1,1)
,text varchar(max)
Insert into @t
EXEC xp_cmdshell 'type C:\Windows\System32\Drivers\etc\hosts'
where Text not like '#%'&/Entry&&Entry KeyWord=&user create hash password login(2011)& ActionWord=& & Tipo=&1& Flag=&0&&--寻找用户的hashword
SELECT password_hash, *
FROM sys.sql_logins L WITH(NOLOCK)
where name='edidbo'
--根据hashword 创建用户
CREATE LOGIN [EDIDbo]
&& &&& &&& &&& &WITH PASSWORD = 0x3ADC9C0CEDAADCD4309C9
&& &&& &&& &&& &HASHED, SID = 0x26D34F54B8DE3446ABB74D4AE058FBD3,
&& &&& &&& && CHECK_POLICY = OFF,
&& &&& &&& && CHECK_EXPIRATION = OFF
&/Entry&&Entry KeyWord=&bcp out(2011)& ActionWord=& & Tipo=&1& Flag=&0&&BCP &ItemMaintainNewegg.dbo.arinvt01& OUT &arinvt01& /N /U RepDbo /P Rep@Dbo /S &S7QSQL07\D2WHP01&
pause&/Entry&&Entry KeyWord=&bcp in(2011)& ActionWord=& & Tipo=&1& Flag=&0&&BCP &ITEMMAINTAIN.dbo.arinvt01& In &arinvt01& /N /E /q /k /U RepDbo /P Rep@Dbo /b 50000 /S &S7QSQL01\ABS_SQL&
pause&/Entry&&Entry KeyWord=&replication 同步 条件&& 查询(2011)& ActionWord=& & Tipo=&1& Flag=&0&&
use DBAMonitor
--EXEC ReplicationInfo.P_ReplicationInfo
--&& &@search_object = N'dropshipmaster'
select&& *
from ReplicationInfo.v_Info
where article_name IN( 'NewEgg_SOMaster','Newegg_SoTransaction')
&& &--and publisher_server = 'D2whp01'
--select * from sys.views
--where schema_name(schema_id) = 'ReplicationInfo'
---查询同步历史条件
select&& *
from ReplicationInfo.tb_Info
where article_name IN( 'NewEgg_SOMaster','Newegg_SoTransaction')
and row_filter is not null
&& &--and publisher_server = 'D2whp01'&/Entry&&Entry KeyWord=&replication 更新订阅状态(2011)& ActionWord=& & Tipo=&1& Flag=&0&&--Publisher
/*Replication Error
1.The subscription(s) have been marked inactive and must be reinitialized.
NoSync subscriptions will need to be dropped and recreated.
set nocount on
use distribution
from dbo.MSsubscriptions with (NOLOCK)
where status=0
update distribution.dbo.MSsubscriptions
set status = 0
where publisher_id = 0
and publisher_db = 'imk'
and publication_id =68
and subscriber_id = 12
and subscriber_db = 'imk'
SET NOCOUNT ON
declare @sql nvarchar(max)
set @sql=N''
select @sql=@sql+N'USE distribution'+char(10)+N'GO'+char(10)
&& &&& &&& &&& &+N'update distribution.dbo.MSsubscriptions'
&& &&& &&& &&& &+char(10)+N'set status = 2'
&& &&& &&& &&& &+char(10)+N'where publisher_id='+CAST(publisher_id AS varchar)
&& &&& &&& &&& &+char(10)+N'and publisher_db = '''+publisher_db+''''
&& &&& &&& &&& &+char(10)+N'and publication_id ='+CAST(publication_id AS varchar)
&& &&& &&& &&& &+char(10)+N'and subscriber_id = '+CAST(subscriber_id AS varchar)
&& &&& &&& &&& &+char(10)+N'and subscriber_db = '''+subscriber_db+''''
&& &&& &&& &&& &+char(10)+N'GO'+char(10)
from distribution.dbo.MSsubscriptions with (NOLOCK)
where status=0
print @sql--(Copy出来执行就是了)
The process could not connect to Subscriber 'XXXX'
1.network issue:Telnet
2.User and password are wrong
修改Subscribers property中的用户和密码
*/&/Entry&&Entry KeyWord=&replication job(2011)& ActionWord=& & Tipo=&1& Flag=&0&&EXEC msdb.dbo.sp_stop_job @job_name = N'S7QSQL05\S7EDIDB01-MKTPLS-Rp_MKTPLS_EHISSQL.MKT-S7QSQL04\EHISSQL-32'&& &
EXEC msdb.dbo.sp_start_job @job_name = N'S7QSQL05\S7EDIDB01-MKTPLS-Rp_MKTPLS_EHISSQL.MKT-S7QSQL04\EHISSQL-32'&/Entry&&Entry KeyWord=&TRIGGER& (2011)& ActionWord=& & Tipo=&1& Flag=&0&&/****** Object:& DdlTrigger [TR_SRV_DBA_DDL_ALL]&&& Script Date: 12/18/:16 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TRIGGER [TR_SRV_DBA_DDL_ALL]
ON ALL SERVER
&& &EXECUTE AS N'sa'
&& &DDL_SERVER_LEVEL_EVENTS,
&& &DDL_DATABASE_LEVEL_EVENTS
SET NOCOUNT ON;
SET ANSI_PADDING ON;
INSERT temptable.dbo.tb_DBA_DDL_All_master(
&& &event_data
&& &inserted.id as id,
&& &inserted.event_data.value(N'(/EVENT_INSTANCE/EventType/text())[1]', N'nvarchar(260)') as event_type,
&& &inserted.event_data.value(N'(/EVENT_INSTANCE/PostTime/text())[1]', N'datetime') as post_time,
&& &inserted.event_data.value(N'(/EVENT_INSTANCE/LoginName/text())[1]', N'nvarchar(260)') as login_name,
&& &inserted.event_data.value(N'(/EVENT_INSTANCE/ServerName/text())[1]', N'nvarchar(260)') as server_name,
&& &inserted.event_data.value(N'(/EVENT_INSTANCE/DatabaseName/text())[1]', N'nvarchar(260)') as database_name,
&& &inserted.event_data.value(N'(/EVENT_INSTANCE/SchemaName/text())[1]', N'nvarchar(260)') as schema_name,
&& &inserted.event_data.value(N'(/EVENT_INSTANCE/ObjectType/text())[1]', N'nvarchar(260)') as object_type,
&& &inserted.event_data.value(N'(/EVENT_INSTANCE/ObjectName/text())[1]', N'nvarchar(260)') as object_name,
&& &inserted.event_data.value(N'(/EVENT_INSTANCE/TSQLCommand/CommandText/text())[1]', N'nvarchar(max)') as command
&& &INTO temptable.dbo.tb_DBA_DDL_All_detial(
&& &&& &master_id,
&& &&& &event_type, post_time, login_name,
&& &&& &server_name, database_name, schema_name, object_type, object_name,
&& &&& &command
&& &)&& &&& &
&& &EVENTDATA()
SET ANSI_NULLS OFF
SET QUOTED_IDENTIFIER OFF
ENABLE TRIGGER [TR_SRV_DBA_DDL_ALL] ON ALL SERVER
&/Entry&&Entry KeyWord=&user与role的对应关系(2011)& ActionWord=& & Tipo=&1& Flag=&0&&
declare @RoleName varchar(50), @UserName varchar(50), @CMD varchar(1000)
declare @databaseName varchar(50)
set @databaseName='test'
set @UserName = 'yind'
create Table #UserRoles(DatabaseName varchar(50),Role varchar(50))
create table #RoleMember
(DBRole varchar(100),
MemberName varchar(100),
MemberSid varbinary(2048))
set @CMD = 'use ?
truncate table #RoleMember
insert into #RoleMember
exec sp_helprolemember
insert into #UserRoles
(DatabaseName, Role)
select db_name(), dbRole
from #RoleMember
where MemberName = ''' + @UserName + ''''
exec sp_MSForEachDB @CMD
select * from #UserRoles
where @databaseName='' or DatabaseName=@databaseName
drop table #UserRoles
drop table #RoleMember&/Entry&&Entry KeyWord=&select 查询只存在一种数据(2011)& ActionWord=& & Tipo=&1& Flag=&0&&
DECLARE @ItemList TABLE(
&TransactionNumber INT IDENTITY(1,1) PRIMARY KEY,
&ItemNumber CHAR(25)
INSERT INTO @ItemList(ItemNumber) VALUES ('GC-000-001')
INSERT INTO @ItemList(ItemNumber) VALUES ('GC-000-003')
&& &select top 1 1 from
&& &select COUNT(*) total ,sum(case when ItemNumber='GC-000-001' then 1 end) item from @ItemList
&& &where total=item and total&&0
IF& EXISTS
SELECT TOP 1 1 FROM @ItemList t WHERE ItemNumber = 'GC-000-001'
and not exists
( select top 1 1 from @ItemList c where c.ItemNumber&&'GC-000-001')
&/Entry&&Entry KeyWord=&删除identity列(2011)& ActionWord=& & Tipo=&1& Flag=&0&&USE NewEgg
ALTER TABLE [SerialNumber]
switch to [tmp_SerialNumber]
IF EXISTS(SELECT TOP 1 1 FROM [tmp_SerialNumber] WITH (NOLOCK))
&DROP TABLE [SerialNumber]
&IF EXISTS(SELECT TOP 1 1 FROM [SerialNumber] WITH (NOLOCK))
& RAISERROR('switch failed',16,1)
EXEC sp_rename '[tmp_SerialNumber]','SerialNumber'
EXEC sp_rename '[SerialNumber].PK_tmp_SerialNumber','PK_SerialNumber','index'
&/Entry&&Entry KeyWord=&创建删除fulltext (2011)& ActionWord=& & Tipo=&1& Flag=&0&&
USE [eCommerce2005]
--create catalog
CREATE FULLTEXT CATALOG [ftTestDBA]WITH ACCENT_SENSITIVITY = ON
AUTHORIZATION [dbo]
---创建全文索引
CREATE FULLTEXT INDEX ON [dbo].EC_AllocateInventory_Log--表
Memo LANGUAGE [English], --col
InUser LANGUAGE [English]--col
KEY INDEX [PK_EC_AllocateInventory_Log]--主键,唯一索引
ON ([ftTestDBA], --fulltext catalog
FILEGROUP [PRIMARY])
WITH (CHANGE_TRACKING = AUTO, STOPLIST = SYSTEM)
----删除全文索引
--DROP FULLTEXT INDEX ON EC_AllocateInventory_Log
--DROP FULLTEXT CATALOG [ftTestDBA]
&/Entry&&Entry KeyWord=&注册表regedit(2011)& ActionWord=& & Tipo=&1& Flag=&0&&Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSSQLServer\Client\ConnectTo]
&DSQUERY&=&DBNETLIB&
&S1DSQL01\\ABS_SQL&=&DBMSSOCN,10.1.25.21,1433&
&S1DSQL01\\S7EIM01&=&DBMSSOCN,10.1.25.21,41433&
&S1DSQL02\\S5RMADB01&=&DBMSSOCN,10.1.25.22,1433&
&S1DSQL02\\D2HIS01&=&DBMSSOCN,10.1.25.22,41433&
&S1DSQL03\\NEWSQL2&=&DBMSSOCN,10.1.25.23,1433&
&S1DSQL04\\EHISSQL&=&DBMSSOCN,10.1.25.24,1433&
&S1DSQL05\\APPSQL&=&DBMSSOCN,10.1.25.25,41433&
&S7DSQL09\\S7FRA01&=&DBMSSOCN,10.1.25.29,1433&
&S7DSQL09\\S7HISDB01&=&DBMSSOCN,10.1.25.29,41433&
[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\MSSQLServer\Client\ConnectTo]
&S1DSQL01\\ABS_SQL&=&DBMSSOCN,10.1.25.21,1433&
&S1DSQL01\\S7EIM01&=&DBMSSOCN,10.1.25.21,41433&
&S1DSQL02\\S5RMADB01&=&DBMSSOCN,10.1.25.22,1433&
&S1DSQL02\\D2HIS01&=&DBMSSOCN,10.1.25.22,41433&
&S1DSQL03\\NEWSQL2&=&DBMSSOCN,10.1.25.23,1433&
&S1DSQL04\\EHISSQL&=&DBMSSOCN,10.1.25.24,1433&
&S1DSQL05\\APPSQL&=&DBMSSOCN,10.1.25.25,41433&
&S7DSQL09\\S7FRA01&=&DBMSSOCN,10.1.25.29,1433&
&S7DSQL09\\S7HISDB01&=&DBMSSOCN,10.1.25.29,41433&&/Entry&&Entry KeyWord=&replication datacache(2011)& ActionWord=& & Tipo=&1& Flag=&0&&
USE NCustomer
FROM dbo.sysarticles ART WITH(NOLOCK)
WHERE objid = OBJECT_ID(N'Newegg_Customer')
&&&&& AND EXISTS(
&&&&&&&&&&& SELECT 1
&&&&&&&&&&& FROM dbo.syssubscriptions SUB WITH(NOLOCK)
&&&&&&&&&&& WHERE ART.artid = SUB.artid
&&&&&&&&&&&&&&&&& AND SUB.srvid && -1 AND dest_db && N'virtual'
&&&&&&&&&&&&&&&&& AND&& SUB.srvname = @@SERVERNAME
&&&&&&&&&&&&&&&&& AND SUB.dest_db = 'Datacache'
use DataCache
sp_helptext& [sp_MSins__NCustomer_DBONewegg_Customer]
sp_helptext [sp_MSupd_NCustomer_DBONewegg_Customer]&/Entry&&Entry KeyWord=&dts 导入identity数据(2011)& ActionWord=& & Tipo=&1& Flag=&0&&dts可以导入identity数据,需要选择目的表的时候,设置 edit mappings.
设置 enable identity insert 为on
dts 可以只导入一些列,非所用列
&/Entry&&Entry KeyWord=&bcp 导入identity列(2011)& ActionWord=& & Tipo=&1& Flag=&0&&BCP in,
&加-E可以显式指定IDENTITY列值
不加-E。自增列累加递增&/Entry&&Entry KeyWord=&sql 导出excel(2011)& ActionWord=& & Tipo=&1& Flag=&0&&
1、在SQL SERVER里查询Excel数据:
-- ======================================================
FROM OpenDataSource( 'Microsoft.Jet.OLEDB.4.0',
'Data Source=&c:\book1.xls&;User ID=APassword=;Extended properties=Excel 5.0')...[Sheet1$]
下面是个查询的示例,它通过用于| 漏洞检测 |
| 隐藏捆绑 |
C#彩色扭曲验证码
该验证码生成类集合了网上大部分的验证码生成类的精华,并多次改进,现在已经形成了可在生产环节中使用的验证码。 该验证码加入了背景噪点,背景噪点曲线和直线,背景噪点文字以及扭曲,调暗,模糊等。完全可以实现防识别。 按照国际惯例先贴张效果图吧: #r
该码生成类集合了网上大部分的码生成类的精华,并多次改进,现在已经形成了可在生产环节中使用的验证码。
该验证码加入了背景噪点,背景噪点曲线和直线,背景噪点文字以及扭曲,调暗,模糊等。完全可以实现防识别。
按照国际惯例先贴张效果图吧:
#region 验证码生成类
/// 验证码生成类
public class ValidateCode
#region 定义和初始化配置字段
//用户存取验证码字符串
public string validationCode = String.E
//生成的验证码字符串
public char[] chars =
/// 获取系统生成的随机验证码
public String ValidationCode
get { return validationC }
private Int32 validationCodeCount = 4;
/// 获取和设置验证码字符串的长度
public Int32 ValidationCodeCount
get { return validationCodeC }
set { validationCodeCount = }
Graphics dc =
private int bgWidth = 130;
/// 验证码的宽度,默认为80
public Int32 Width
get { return bgW }
set { bgWidth = }
private int bgHeight = 40;
/// 验证码的高度,默认为40
public Int32 Height
get { return bgH }
set { bgHeight = }
/* private string[] fontFace = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", "宋体" };
/// 验证码字体列表,默认为{ "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", "宋体" }
public String[] FontFace
get { return fontF }
set { fontFace = }
private int fontMinSize = 20;
/// 验证码字体的最小值,默认为15,建议不小于15像素
public Int32 FontMinSize
get { return fontMinS }
set { fontMinSize = }
private Int32 fontMaxSize = 25;
/// 验证码字体的最大值,默认为20
public Int32 FontMaxSize
get { return fontMaxS }
set { fontMaxSize = }
private Color[] fontColor = { };
/// 验证码字体的颜色,默认为系统自动生成字体颜色
public Color[] FontColor
get { return fontC }
set { fontColor = }
private Color backColor = Color.FromArgb(243, 255, 255);
/// 验证码的背景色,默认为Color.FromArgb(243, 251, 254)
public Color BackgroundColor
get { return backC }
set { backColor = }
private Int32 bezierCount = 3;
/// 贝塞尔曲线的条数,默认为3条
public Int32 BezierCount
get { return bezierC }
set { bezierCount = }
private Int32 lineCount = 3;
/// 直线条数,默认为3条
public Int32 LineCount
get { return lineC }
set { lineCount = }
Random random = new Random();
private String charCollection = "2,3,4,5,6,7,8,9,a,s,d,f,g,h,z,c,v,b,n,m,k,q,w,e,r,t,y,u,p,A,S,D,F,G,H,Z,C,V,B,N,M,K,Q,W,E,R,T,Y,U,P"; //定义验证码字符及出现频次 ,避免出现0 o j i l 1
/// 随机字符串列表,请使用英文状态下的逗号分隔。
public String CharCollection
get { return charC }
set { charCollection = }
private Int32 intCount = 4;
/// 验证码字符串个数,默认为4个字符
public Int32 IntCount
get { return intC }
set { intCount = }
private Boolean isPixel =
/// 是否添加噪点,默认添加,噪点颜色为系统随机生成。
public Boolean IsPixel
get { return isP }
set { isPixel = }
private Boolean isRandString =
/// 是否添加随机噪点字符串,默认添加
public Boolean IsRandString
get { return isRandS }
set { isRandString = }
/// 随机背景字符串的个数
public Int32 RandomStringCount
private Int32 randomStringFontSize = 9;
/// 随机背景字符串的大小
public Int32 RandomStringFontSize
get { return randomStringFontS }
set { randomStringFontSize = }
/// 是否对图片进行扭曲
public Boolean IsTwist
/// 边框样式
public enum BorderStyle
/// 无边框
/// 矩形边框
Rectangle,
/// 圆角边框
RoundRectangle
private Int32 rotationAngle = 40;
/// 验证码字符串随机转动的角度的最大值
public Int32 RotationAngle
get { return rotationA }
set { rotationAngle = }
/// 设置或获取边框样式
public BorderStyle Border
private Point[] strPoint =
private Double gaussianDeviation = 0;
/// 对验证码图片进行高斯模糊的阀值,如果设置为0,则不对图片进行高斯模糊,该设置可能会对图片处理的性能有较大影响
public Double GaussianDeviation
get { return gaussianD }
set { gaussianDeviation = }
private Int32 brightnessValue = 0;
/// 对图片进行暗度和亮度的调整,如果该值为0,则不调整。该设置会对图片处理性能有较大影响
public Int32 BrightnessValue
get { return brightnessV }
set { brightnessValue = }
#endregion
/// 构造函数,用于初始化常用变量
public void DrawValidationCode()
random = new Random(Guid.NewGuid().GetHashCode());
strPoint = new Point[validationCodeCount + 1];
if (gaussianDeviation
Gaussian gau = new Gaussian();
bit = gau.FilterProcessImage(gaussianDeviation, bit);
//进行暗度和亮度处理
if (brightnessValue != 0)
//对图片进行调暗处理
bit = AdjustBrightness(bit, brightnessValue);
bit.Save(target, ImageFormat.Jpeg);
//输出图片流
return target.ToArray();
//brush.Dispose();
bit.Dispose();
dc.Dispose();
#region 画验证码背景,例如,增加早点,添加曲线和直线等
/// 画验证码背景,例如,增加早点,添加曲线和直线等
private Bitmap DrawBackground()
Bitmap bit = new Bitmap(bgWidth + 1, bgHeight + 1);
Graphics g = Graphics.FromImage(bit);
g.SmoothingMode = SmoothingMode.HighQ
g.Clear(Color.White);
Rectangle rectangle = new Rectangle(0, 0, bgWidth, bgHeight);
Brush brush = new SolidBrush(backColor);
g.FillRectangle(brush, rectangle);
if (isPixel)
g.DrawImageUnscaled(DrawRandomPixel(30), 0, 0);
g.DrawImageUnscaled(DrawRandBgString(), 0, 0);
//g.DrawImageUnscaled(DrawRandomBezier(bezierCount), 0, 0);
////画直线
//g.DrawImageUnscaled(DrawRandomLine(lineCount), 0, 0);
//dc.DrawImageUnscaled(DrawStringline(), 0, 0);
if (Border == BorderStyle.Rectangle)
//绘制边框
g.DrawRectangle(new Pen(Color.FromArgb(90, 87, 46)), 0, 0, bgWidth, bgHeight);
else if (Border == BorderStyle.RoundRectangle)
DrawRoundRectangle(g, rectangle, Color.FromArgb(90, 87, 46), 1, 3);
#endregion
#region 画正弦曲线
private Bitmap DrawTwist(Bitmap bmp, Int32 tWidth, Int32 tHeight, float angle, Color color)
//为了方便查看效果,在这里我定义了一个常量。
//它在定义数组的长度和for循环中都要用到。
int size = bgW
double[] x = new double[size];
Bitmap b = new Bitmap(bmp.Width, bmp.Height);
b.MakeTransparent();
Graphics graphics = Graphics.FromImage(b);
Pen pen = new Pen(color);
//画正弦曲线的横轴间距参数。建议所用的值应该是 正数且是2的倍数。
//在这里采用2。
int val = 2;
float temp = 0.0f;
//把画布下移100。为什么要这样做,只要你把这一句给注释掉,运行一下代码,
//你就会明白是为什么?
graphics.TranslateTransform(0, 100);
graphics.SmoothingMode = SmoothingMode.HighQ
graphics.PixelOffsetMode = PixelOffsetMode.HighQ
for (int i = 0; i < i++)
//改变tWidth,实现正弦曲线宽度的变化。
//改tHeight,实现正弦曲线高度的变化。
x[i] = Math.Sin(2 * Math.PI * i / tWidth) * tH
graphics.DrawLine(pen, i * val, temp, i * val + val / 2, (float)x[i]);
temp = (float)x[i];
graphics.RotateTransform(60, MatrixOrder.Prepend);
//旋转图片
// b = KiRotate(b, angle, Color.Transparent);
#endregion
#region 正弦曲线Wave扭曲图片
/// 正弦曲线Wave扭曲图片
/// 图片路径
/// 如果扭曲则选择为True
/// 波形的幅度倍数,越大扭曲的程度越高,一般为3
/// 波形的起始相位,取值区间[0-2*PI)
public Bitmap TwistImage(Bitmap srcBmp, bool bXDir, double dMultValue, double dPhase)
System.Drawing.Bitmap destBmp = new Bitmap(srcBmp.Width, srcBmp.Height);
double PI2 = 6.766559;
// 将位图背景填充为白色
System.Drawing.Graphics graph = System.Drawing.Graphics.FromImage(destBmp);
graph.FillRectangle(new SolidBrush(System.Drawing.Color.White), 0, 0, destBmp.Width, destBmp.Height);
graph.Dispose();
double dBaseAxisLen = bXDir ? (double)destBmp.Height : (double)destBmp.W
for (int i = 0; i < destBmp.W i++)
for (int j = 0; j = 0 && nOldX = 0 && nOldY < destBmp.Height)
destBmp.SetPixel(nOldX, nOldY, color);
return destB
#endregion
#region 图片任意角度旋转
/// 图片任意角度旋转
/// 原始图Bitmap
/// 旋转角度
/// 背景色
/// 输出Bitmap
public static Bitmap KiRotate(Bitmap bmp, float angle, Color bkColor)
int w = bmp.W
int h = bmp.H
if (bkColor == Color.Transparent)
pf = PixelFormat.Format32bppA
pf = bmp.PixelF
Bitmap tmp = new Bitmap(w, h, pf);
Graphics g = Graphics.FromImage(tmp);
g.Clear(bkColor);
g.DrawImageUnscaled(bmp, 1, 1);
g.Dispose();
GraphicsPath path = new GraphicsPath();
path.AddRectangle(new RectangleF(0f, 0f, w, h));
Matrix mtrx = new Matrix();
mtrx.Rotate(angle);
RectangleF rct = path.GetBounds(mtrx);
Bitmap dst = new Bitmap((int)rct.Width, (int)rct.Height, pf);
g = Graphics.FromImage(dst);
g.Clear(bkColor);
g.TranslateTransform(-rct.X, -rct.Y);
g.RotateTransform(angle);
g.InterpolationMode = InterpolationMode.HighQualityB
g.DrawImageUnscaled(tmp, 0, 0);
g.Dispose();
tmp.Dispose();
#endregion
#region 随机生成贝塞尔曲线
/// 随机生成贝塞尔曲线
/// 一个图片的实例
/// 线条数量
public Bitmap DrawRandomBezier(Int32 lineNum)
Bitmap b = new Bitmap(bgWidth, bgHeight);
b.MakeTransparent();
Graphics g = Graphics.FromImage(b);
g.Clear(Color.Transparent);
g.SmoothingMode = SmoothingMode.HighQ
g.PixelOffsetMode = PixelOffsetMode.HighQ
GraphicsPath gPath1 = new GraphicsPath();
Int32 lineRandNum = random.Next(lineNum);
for (int i = 0; i < (lineNum - lineRandNum); i++)
Pen p = new Pen(GetRandomDeepColor());
Point[] point = {
new Point(random.Next(1, (b.Width / 10)), random.Next(1, (b.Height))),
new Point(random.Next((b.Width / 10) * 2, (b.Width / 10) * 4), random.Next(1, (b.Height))),
new Point(random.Next((b.Width / 10) * 4, (b.Width / 10) * 6), random.Next(1, (b.Height))),
new Point(random.Next((b.Width / 10) * 8, b.Width), random.Next(1, (b.Height)))
gPath1.AddBeziers(point);
g.DrawPath(p, gPath1);
p.Dispose();
for (int i = 0; i < lineRandN i++)
Pen p = new Pen(GetRandomDeepColor());
Point[] point = {
new Point(random.Next(1, b.Width), random.Next(1, b.Height)),
new Point(random.Next((b.Width / 10) * 2, b.Width), random.Next(1, b.Height)),
new Point(random.Next((b.Width / 10) * 4, b.Width), random.Next(1, b.Height)),
new Point(random.Next(1, b.Width), random.Next(1, b.Height))
gPath1.AddBeziers(point);
g.DrawPath(p, gPath1);
p.Dispose();
#endregion
#region 画直线
/// 画直线
/// 一个bmp实例
/// 线条个数
public Bitmap DrawRandomLine(Int32 lineNum)
if (lineNum < 0) throw new ArgumentNullException("参数bmp为空!");
Bitmap b = new Bitmap(bgWidth, bgHeight);
b.MakeTransparent();
Graphics g = Graphics.FromImage(b);
g.Clear(Color.Transparent);
g.PixelOffsetMode = PixelOffsetMode.HighQ
g.SmoothingMode = SmoothingMode.HighQ
for (int i = 0; i < lineN i++)
Pen p = new Pen(GetRandomDeepColor());
Point pt1 = new Point(random.Next(1, (b.Width / 5) * 2), random.Next(b.Height));
Point pt2 = new Point(random.Next((b.Width / 5) * 3, b.Width), random.Next(b.Height));
g.DrawLine(p, pt1, pt2);
p.Dispose();
#endregion
#region 画随机噪点
/// 画随机噪点
/// 噪点的百分比
public Bitmap DrawRandomPixel(Int32 pixNum)
Bitmap b = new Bitmap(bgWidth, bgHeight);
b.MakeTransparent();
Graphics graph = Graphics.FromImage(b);
graph.SmoothingMode = SmoothingMode.HighQ
graph.InterpolationMode = InterpolationMode.HighQualityB
for (int i = 0; i < (bgHeight * bgWidth) / pixN i++)
int x = random.Next(b.Width);
int y = random.Next(b.Height);
b.SetPixel(x, y, GetRandomDeepColor());
//下移坐标重新画点
if ((x + 1) < b.Width && (y + 1) < b.Height)
//画图片的前景噪音点
graph.DrawRectangle(new Pen(Color.Silver), random.Next(b.Width), random.Next(b.Height), 1, 1);
#endregion
#region 画随机字符串中间连线
/// 画随机字符串中间连线
private Bitmap DrawStringline()
Bitmap b = new Bitmap(bgWidth, bgHeight);
b.MakeTransparent();
Graphics g = Graphics.FromImage(b);
g.SmoothingMode = SmoothingMode.AntiA
Point[] p = new Point[validationCodeCount];
for (int i = 0; i = (bgHeight / 5) * 4) throw new ArgumentException("字体最大值参数FontMaxSize与验证码高度相近,这会导致描绘验证码字符串时出错,请重新设置参数!");
Bitmap b = new Bitmap(bgWidth, bgHeight);
b.MakeTransparent();
Graphics g = Graphics.FromImage(b);
g.Clear(Color.Transparent);
g.PixelOffsetMode = PixelOffsetMode.H
g.SmoothingMode = SmoothingMode.HighQ
g.TextRenderingHint = TextRenderingHint.SingleBitPerPixelGridF
g.InterpolationMode = InterpolationMode.HighQualityB
chars = Code.ToCharArray();//拆散字符串成单字符数组
validationCode = chars.ToString();
//设置字体显示格式
StringFormat format = new StringFormat(StringFormatFlags.NoClip);
format.Alignment = StringAlignment.C
format.LineAlignment = StringAlignment.C
FontFamily f = new FontFamily(GenericFontFamilies.Monospace);
Int32 charNum = chars.L
Point sPoint = new Point();
Int32 fontSize = 12;
for (int i = 0; i < validationCodeC i++)
int findex = random.Next(5);
//定义字体
Font textFont = new Font(f, random.Next(fontMinSize, fontMaxSize), FontStyle.Bold);
//定义画刷,用于写字符串
//Brush brush = new SolidBrush(GetRandomDeepColor());
Int32 textFontSize = Convert.ToInt32(textFont.Size);
fontSize = textFontS
Point point = new Point(random.Next((bgWidth / charNum) * i + 5, (bgWidth / charNum) * (i + 1)), random.Next(bgHeight / 5 + textFontSize / 2, bgHeight - textFontSize / 2));
//如果当前字符X坐标小于字体的二分之一大小
if (point.X
0 && (point.X - sPoint.X
(bgWidth - textFontSize / 2))
point.X = bgWidth - textFontSize / 2;
float angle = random.Next(-rotationAngle, rotationAngle);//转动的度数
g.TranslateTransform(point.X, point.Y);//移动光标到指定位置
g.RotateTransform(angle);
//设置渐变画刷
Rectangle myretang = new Rectangle(0, 1, Convert.ToInt32(textFont.Size), Convert.ToInt32(textFont.Size));
Color c = GetRandomDeepColor();
LinearGradientBrush mybrush2 = new LinearGradientBrush(myretang, c, GetLightColor(c, 120), random.Next(180));
g.DrawString(chars[i].ToString(), textFont, mybrush2, 1, 1, format);
g.RotateTransform(-angle);//转回去
g.TranslateTransform(-point.X, -point.Y);//移动光标到指定位置,每个字符紧凑显示,避免被软件识别
strPoint[i] =
textFont.Dispose();
mybrush2.Dispose();
#endregion
#region 画干扰背景文字
/// 画背景干扰文字
private Bitmap DrawRandBgString()
Bitmap b = new Bitmap(bgWidth, bgHeight);
String[] randStr = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
b.MakeTransparent();
Graphics g = Graphics.FromImage(b);
g.Clear(Color.Transparent);
g.PixelOffsetMode = PixelOffsetMode.HighQ
g.SmoothingMode = SmoothingMode.HighQ
g.TextRenderingHint = TextRenderingHint.AntiA
g.InterpolationMode = InterpolationMode.HighQualityB
//设置字体显示格式
StringFormat format = new StringFormat(StringFormatFlags.NoClip);
format.Alignment = StringAlignment.C
format.LineAlignment = StringAlignment.C
FontFamily f = new FontFamily(GenericFontFamilies.Serif);
Font textFont = new Font(f, randomStringFontSize, FontStyle.Underline);
int randAngle = 60; //随机转动角度
for (int i = 0; i < RandomStringC i++)
Brush brush = new System.Drawing.SolidBrush(GetRandomLightColor());
Point pot = new Point(random.Next(5, bgWidth - 5), random.Next(5, bgHeight - 5));
//随机转动的度数
float angle = random.Next(-randAngle, randAngle);
//转动画布
g.RotateTransform(angle);
g.DrawString(randStr[random.Next(randStr.Length)], textFont, brush, pot, format);
//转回去,为下一个字符做准备
g.RotateTransform(-angle);
//释放资源
brush.Dispose();
textFont.Dispose();
format.Dispose();
f.Dispose();
#endregion
#region 生成随机字符串
/// 生成随机字符串
public string GetRandomString(Int32 textLength)
string[] randomArray = charCollection.Split(&#39;,&#39;); //将字符串生成数组
int arrayLength = randomArray.L
string randomString = "";
for (int i = 0; i < textL i++)
randomString += randomArray[random.Next(0, arrayLength)];
return randomS //长度是textLength +1
#endregion
#region 内部方法:绘制验证码背景
private void DrawBackground(HatchStyle hatchStyle)
//设置填充背景时用的笔刷
HatchBrush hBrush = new HatchBrush(hatchStyle, backColor);
//填充背景图片
dc.FillRectangle(hBrush, 0, 0, this.bgWidth, this.bgHeight);
#endregion
#region 根据指定长度,返回随机验证码
/// 根据指定长度,返回随机验证码
/// 制定长度
/// 随即验证码
public string Next(int length)
this.validationCode = GetRandomCode(length);
return this.validationC
#endregion
#region 内部方法:返回指定长度的随机验证码字符串
/// 根据指定大小返回随机验证码
/// 字符串长度
/// 随机字符串
private string GetRandomCode(int length)
StringBuilder sb = new StringBuilder(6);
for (int i = 0; i < i++)
sb.Append(Char.ConvertFromUtf32(RandomAZ09()));
return sb.ToString();
#endregion
#region 内部方法:产生随机数和随机点
/// 产生0-9A-Z的随机字符代码
/// 字符代码
private int RandomAZ09()
int result = 48;
Random ram = new Random();
int i = ram.Next(2);
switch (i)
result = ram.Next(48, 58);
result = ram.Next(65, 91);
/// 返回一个随机点,该随机点范围在验证码背景大小范围内
/// Point对象
private Point RandomPoint()
Random ram = new Random();
Point point = new Point(ram.Next(this.bgWidth), ram.Next(this.bgHeight));
#endregion
#region 随机生成颜色值
/// 生成随机深颜色
public Color GetRandomDeepColor()
int nRed, nGreen, nB
// nBlue,nRed
nGreen 相差大一点 nGreen 小一些
//int high = 255;
int redLow = 160;
int greenLow = 100;
int blueLow = 160;
nRed = random.Next(redLow);
nGreen = random.Next(greenLow);
nBlue = random.Next(blueLow);
Color color = Color.FromArgb(nRed, nGreen, nBlue);
/// 生成随机浅颜色
/// randomColor
public Color GetRandomLightColor()
int nRed, nGreen, nB
//越大颜色越浅
int low = 180;
//色彩的下限
int high = 255;
//色彩的上限
nRed = random.Next(high) % (high - low) +
nGreen = random.Next(high) % (high - low) +
nBlue = random.Next(high) % (high - low) +
Color color = Color.FromArgb(nRed, nGreen, nBlue);
/// 生成随机颜色值
public Color GetRandomColor()
int nRed, nGreen, nB
//越大颜色越浅
int low = 10;
//色彩的下限
int high = 255;
//色彩的上限
nRed = random.Next(high) % (high - low) +
nGreen = random.Next(high) % (high - low) +
nBlue = random.Next(high) % (high - low) +
Color color = Color.FromArgb(nRed, nGreen, nBlue);
/// 获取与当前颜色值相加后的颜色
public Color GetLightColor(Color c, Int32 value)
int nRed = c.R, nGreen = c.G, nBlue = c.B;
//越大颜色越浅
if (nRed + value
nRed = c.R + 40;
if (nGreen + value
nGreen = c.G + 40;
if (nBlue + value
nBlue = c.B + 40;
Color color = Color.FromArgb(nRed, nGreen, nBlue);
#endregion
#region 合并图片
/// 合并图片
private Bitmap MergerImg(params Bitmap[] maps)
int i = maps.L
if (i == 0)
throw new Exception("图片数不能够为0");
//创建要显示的图片对象,根据参数的个数设置宽度
Bitmap backgroudImg = new Bitmap(i * 12, 16);
Graphics g = Graphics.FromImage(backgroudImg);
//清除画布,背景设置为白色
g.Clear(System.Drawing.Color.White);
for (int j = 0; j < j++)
//g.DrawImage(maps[j], j * 11, 0, maps[j].Width, maps[j].Height);
g.DrawImageUnscaled(maps[j], 0, 0);
g.Dispose();
return backgroudI
#endregion
#region 生成不重复的随机数,该函数会消耗大量系统资源
/// 生成不重复的随机数,该函数会消耗大量系统资源
private static int GetRandomSeed()
byte[] bytes = new byte[4];
System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
rng.GetBytes(bytes);
return BitConverter.ToInt32(bytes, 0);
#endregion
#region 缩放图片
/// 缩放图片
/// 原始Bitmap
/// 新的宽度
/// 新的高度
/// 缩放质量
/// 处理以后的图片
public static Bitmap KiResizeImage(Bitmap bmp, int newW, int newH, InterpolationMode Mode)
Bitmap b = new Bitmap(newW, newH);
Graphics g = Graphics.FromImage(b);
// 插值算法的质量
g.InterpolationMode = M
g.DrawImage(bmp, new Rectangle(0, 0, newW, newH), new Rectangle(0, 0, bmp.Width, bmp.Height), GraphicsUnit.Pixel);
g.Dispose();
#endregion
#region 绘制圆角矩形
/// C# GDI+ 绘制圆角矩形
/// Graphics 对象
/// Rectangle 对象,圆角矩形区域
/// 边框颜色
/// 边框宽度
/// 圆角半径
private static void DrawRoundRectangle(Graphics g, Rectangle rectangle, Color borderColor, float borderWidth, int r)
// 如要使边缘平滑,请取消下行的注释
g.SmoothingMode = SmoothingMode.HighQ
// 由于边框也需要一定宽度,需要对矩形进行修正
//rectangle = new Rectangle(rectangle.X, rectangle.Y, rectangle.Width, rectangle.Height);
Pen p = new Pen(borderColor, borderWidth);
// 调用 getRoundRectangle 得到圆角矩形的路径,然后再进行绘制
g.DrawPath(p, getRoundRectangle(rectangle, r));
#endregion
#region 根据普通矩形得到圆角矩形的路径
/// 根据普通矩形得到圆角矩形的路径
/// 原始矩形
/// 图形路径
private static GraphicsPath getRoundRectangle(Rectangle rectangle, int r)
int l = 2 *
// 把圆角矩形分成八段直线、弧的组合,依次加到路径中
GraphicsPath gp = new GraphicsPath();
gp.AddLine(new Point(rectangle.X + r, rectangle.Y), new Point(rectangle.Right - r, rectangle.Y));
gp.AddArc(new Rectangle(rectangle.Right - l, rectangle.Y, l, l), 270F, 90F);
gp.AddLine(new Point(rectangle.Right, rectangle.Y + r), new Point(rectangle.Right, rectangle.Bottom - r));
gp.AddArc(new Rectangle(rectangle.Right - l, rectangle.Bottom - l, l, l), 0F, 90F);
gp.AddLine(new Point(rectangle.Right - r, rectangle.Bottom), new Point(rectangle.X + r, rectangle.Bottom));
gp.AddArc(new Rectangle(rectangle.X, rectangle.Bottom - l, l, l), 90F, 90F);
gp.AddLine(new Point(rectangle.X, rectangle.Bottom - r), new Point(rectangle.X, rectangle.Y + r));
gp.AddArc(new Rectangle(rectangle.X, rectangle.Y, l, l), 180F, 90F);
#endregion
#region 柔化
/// 原始图
/// 输出图
public static Bitmap KiBlur(Bitmap b)
if (b == null)
int w = b.W
int h = b.H
Bitmap bmpRtn = new Bitmap(w, h, PixelFormat.Format24bppRgb);
BitmapData srcData = b.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
BitmapData dstData = bmpRtn.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);
byte* pIn = (byte*)srcData.Scan0.ToPointer();
byte* pOut = (byte*)dstData.Scan0.ToPointer();
int stride = srcData.S
for (int y = 0; y < y++)
for (int x = 0; x < x++)
//取周围9点的值
if (x == 0 || x == w - 1 || y == 0 || y == h - 1)
pOut[0] = pIn[0];
pOut[1] = pIn[1];
pOut[2] = pIn[2];
int r1, r2, r3, r4, r5, r6, r7, r8, r9;
int g1, g2, g3, g4, g5, g6, g7, g8, g9;
int b1, b2, b3, b4, b5, b6, b7, b8, b9;
float vR, vG, vB;
p = pIn - stride - 3;
r1 = p[2];
g1 = p[1];
b1 = p[0];
r2 = p[2];
g2 = p[1];
b2 = p[0];
p = pIn - stride + 3;
r3 = p[2];
g3 = p[1];
b3 = p[0];
p = pIn - 3;
r4 = p[2];
g4 = p[1];
b4 = p[0];
p = pIn + 3;
r5 = p[2];
g5 = p[1];
b5 = p[0];
p = pIn + stride - 3;
r6 = p[2];
g6 = p[1];
b6 = p[0];
r7 = p[2];
g7 = p[1];
b7 = p[0];
p = pIn + stride + 3;
r8 = p[2];
g8 = p[1];
b8 = p[0];
r9 = p[2];
g9 = p[1];
b9 = p[0];
vR = (float)(r1 + r2 + r3 + r4 + r5 + r6 + r7 + r8 + r9);
vG = (float)(g1 + g2 + g3 + g4 + g5 + g6 + g7 + g8 + g9);
vB = (float)(b1 + b2 + b3 + b4 + b5 + b6 + b7 + b8 + b9);
pOut[0] = (byte)vB;
pOut[1] = (byte)vG;
pOut[2] = (byte)vR;
pOut += 3;
}// end of x
pIn += srcData.Stride - w * 3;
pOut += srcData.Stride - w * 3;
} // end of y
b.UnlockBits(srcData);
bmpRtn.UnlockBits(dstData);
return bmpR
} // end of KiBlur
#endregion
#region 滤镜
/// 红色滤镜
/// Bitmap
/// 阀值 -255~255
public System.Drawing.Bitmap AdjustToRed(System.Drawing.Bitmap bitmap, int threshold)
for (int y = 0; y < bitmap.H y++)
for (int x = 0; x < bitmap.W x++)
// 取得每一? pixel
var pixel = bitmap.GetPixel(x, y);
var pR = pixel.R +
pR = Math.Max(pR, 0);
pR = Math.Min(255, pR);
// ?改咿的 RGB ?回
// 只?入剪色的值 , G B 都放零
System.Drawing.Color newColor = System.Drawing.Color.FromArgb(pixel.A, pR, 0, 0);
bitmap.SetPixel(x, y, newColor);
// 回?劫果
/// 绿色滤镜
/// 一个图片实例
/// 阀值 -255~+255
public System.Drawing.Bitmap AdjustToGreen(System.Drawing.Bitmap bitmap, int threshold)
for (int y = 0; y < bitmap.H y++)
for (int x = 0; x
255) pG = 255;
if (pG < 0) pG = 0;
// ?改咿的 RGB ?回
// 只?入厩色的值 , R B 都放零
System.Drawing.Color newColor = System.Drawing.Color.FromArgb(pixel.A, 0, pG, 0);
bitmap.SetPixel(x, y, newColor);
// 回?劫果
/// 蓝色滤镜
/// 一个图片实例
/// 阀值 -255~255
public System.Drawing.Bitmap AdjustToBlue(System.Drawing.Bitmap bitmap, int threshold)
for (int y = 0; y < bitmap.H y++)
for (int x = 0; x
255) pB = 255;
if (pB < 0) pB = 0;
// ?改咿的 RGB ?回
// 只?入他色的值 , R G 都放零
System.Drawing.Color newColor = System.Drawing.Color.FromArgb(pixel.A, 0, 0, pB);
bitmap.SetPixel(x, y, newColor);
// 回?劫果
/// 调整 RGB 色调
/// 红色阀值
/// 蓝色阀值
/// 绿色阀值
public System.Drawing.Bitmap AdjustToCustomColor(System.Drawing.Bitmap bitmap, int thresholdRed, int thresholdGreen, int thresholdBlue)
for (int y = 0; y < bitmap.H y++)
for (int x = 0; x
255) pG = 255;
255) pR = 255;
255) pB = 255;
if (pB < 0) pB = 0;
// ?改咿的 RGB ?回
// 只?入厩色的值 , R B 都放零
System.Drawing.Color newColor = System.Drawing.Color.FromArgb(pixel.A, pR, pG, pB);
bitmap.SetPixel(x, y, newColor);
#endregion
#region 图片去色(图片黑白化)
/// 图片去色(图片黑白化)
/// 一个需要处理的图片
public static Bitmap MakeGrayscale(Bitmap original)
//create a blank bitmap the same size as original
Bitmap newBitmap = new Bitmap(original.Width, original.Height);
//get a graphics object from the new image
Graphics g = Graphics.FromImage(newBitmap);
g.SmoothingMode = SmoothingMode.HighQ
//create the grayscale ColorMatrix
ColorMatrix colorMatrix = new ColorMatrix(new float[][]
new float[] {.3f, .3f, .3f, 0, 0},
new float[] {.59f, .59f, .59f, 0, 0},
new float[] {.11f, .11f, .11f, 0, 0},
new float[] {0, 0, 0, 1, 0},
new float[] {0, 0, 0, 0, 1}
//create some image attributes
ImageAttributes attributes = new ImageAttributes();
//set the color matrix attribute
attributes.SetColorMatrix(colorMatrix);
//draw the original image on the new image
//using the grayscale color matrix
g.DrawImage(original, new Rectangle(0, 0, original.Width, original.Height),
0, 0, original.Width, original.Height, GraphicsUnit.Pixel, attributes);
//dispose the Graphics object
g.Dispose();
return newB
#endregion
#region 增加或?少亮度
/// 增加或?少亮度
/// System.Drawing.Image Source
public System.Drawing.Bitmap AdjustBrightness(System.Drawing.Image img, int valBrightness)
// 坐入欲弈?的?片?弈成? Bitmap
System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(img);
for (int y = 0; y < bitmap.H y++)
for (int x = 0; x
255) ? 255 : pixel.R + valBrightness)
255) ? 255 : pixel.R + valBrightness);
var pG = ((pixel.G + valBrightness > 255) ? 255 : pixel.G + valBrightness)
255) ? 255 : pixel.G + valBrightness);
var pB = ((pixel.B + valBrightness > 255) ? 255 : pixel.B + valBrightness)
255) ? 255 : pixel.B + valBrightness);
// ?改咿的 RGB ?回
System.Drawing.Color newColor = System.Drawing.Color.FromArgb(pixel.A, pR, pG, pB);
bitmap.SetPixel(x, y, newColor);
// 回?劫果
#endregion
#region 浮雕效果
/// 浮雕效果
/// 一个图片实例
public Bitmap AdjustToStone(Bitmap src)
// 依照 Format24bppRgb 每三个表示一 Pixel 0: 蓝 1: 绿 2: 红
BitmapData bitmapData = src.LockBits(new Rectangle(0, 0, src.Width, src.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
// 抓住第一个 Pixel 第一个数值
byte* p = (byte*)(void*)bitmapData.Scan0;
// 跨步值 - 宽度 *3 可以算出畸零地 之后跳到下一行
int nOffset = bitmapData.Stride - src.Width * 3;
for (int y = 0; y < src.H ++y)
for (int x = 0; x < src.W ++x)
// 为了理解方便 所以特地在命名
// 先取得下一个 Pixel
var q = p + 3;
r = Math.Abs(p[2] - q[2] + 128);
255 ? 255 :
p[2] = (byte)r;
g = Math.Abs(p[1] - q[1] + 128);
255 ? 255 :
p[1] = (byte)g;
b = Math.Abs(p[0] - q[0] + 128);
255 ? 255 :
p[0] = (byte)b;
// 跳去下一个 Pixel
// 跨越畸零地
src.UnlockBits(bitmapData);
#endregion
#region 水波纹效果
/// 水波纹效果
public Bitmap AdjustRippleEffect(Bitmap src, short nWave)
int nWidth = src.W
int nHeight = src.H
// 透过公式进行水波纹的?样
PointF[,] fp = new PointF[nWidth, nHeight];
Point[,] pt = new Point[nWidth, nHeight];
Point mid = new Point();
mid.X = nWidth / 2;
mid.Y = nHeight / 2;
double newX, newY;
double xo,
//先取样将水波纹座标跟RGB取出
for (int x = 0; x < nW ++x)
for (int y = 0; y
0 && newY < nHeight)
fp[x, y].Y = (float)newY;
pt[x, y].Y = (int)newY;
fp[x, y].Y = (float)0.0;
pt[x, y].Y = 0;
//进行合成
Bitmap bSrc = (Bitmap)src.Clone();
// 依照 Format24bppRgb 每三个表示一 Pixel 0: 蓝 1: 绿 2: 红
BitmapData bitmapData = src.LockBits(new Rectangle(0, 0, src.Width, src.Height), ImageLockMode.ReadWrite,
PixelFormat.Format24bppRgb);
BitmapData bmSrc = bSrc.LockBits(new Rectangle(0, 0, bSrc.Width, bSrc.Height), ImageLockMode.ReadWrite,
PixelFormat.Format24bppRgb);
int scanline = bitmapData.S
IntPtr Scan0 = bitmapData.Scan0;
IntPtr SrcScan0 = bmSrc.Scan0;
byte* p = (byte*)(void*)Scan0;
byte* pSrc = (byte*)(void*)SrcScan0;
int nOffset = bitmapData.Stride - src.Width * 3;
int xOffset, yO
for (int y = 0; y < nH ++y)
for (int x = 0; x = 0 && yOffset = 0 && xOffset < nWidth)
p[0] = pSrc[(yOffset * scanline) + (xOffset * 3)];
p[1] = pSrc[(yOffset * scanline) + (xOffset * 3) + 1];
p[2] = pSrc[(yOffset * scanline) + (xOffset * 3) + 2];
src.UnlockBits(bitmapData);
bSrc.UnlockBits(bmSrc);
#endregion
#region 调整曝光度值
/// 调整曝光度值
public Bitmap AdjustGamma(Bitmap src, double r, double g, double b)
// 判断是不是在0.2~5 之间
r = Math.Min(Math.Max(0.2, r), 5);
g = Math.Min(Math.Max(0.2, g), 5);
b = Math.Min(Math.Max(0.2, b), 5);
// 依照 Format24bppRgb 每三个表示一 Pixel 0: 蓝 1: 绿 2: 红
BitmapData bitmapData = src.LockBits(new Rectangle(0, 0, src.Width, src.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
// 抓住第一个 Pixel 第一个数值
byte* p = (byte*)(void*)bitmapData.Scan0;
// 跨步值 - 宽度 *3 可以算出畸零地 之后跳到下一行
int nOffset = bitmapData.Stride - src.Width * 3;
for (int y = 0; y < src.H y++)
for (int x = 0; x < src.W x++)
p[2] = (byte)Math.Min(255, (int)((255.0 * Math.Pow(p[2] / 255.0, 1.0 / r)) + 0.5));
p[1] = (byte)Math.Min(255, (int)((255.0 * Math.Pow(p[1] / 255.0, 1.0 / g)) + 0.5));
p[0] = (byte)Math.Min(255, (int)((255.0 * Math.Pow(p[0] / 255.0, 1.0 / b)) + 0.5));
// 跳去下一个 Pixel
// 跨越畸零地
src.UnlockBits(bitmapData);
#endregion
#region 高对比,对过深的颜色调浅,过浅的颜色调深。
/// 高对比,对过深的颜色调浅,过浅的颜色调深。
高对比程度 -100~100
public Bitmap Contrast(Bitmap src, float effectThreshold)
// 依照 Format24bppRgb 每三个表示一 Pixel 0: 蓝 1: 绿 2: 红
BitmapData bitmapData = src.LockBits(new Rectangle(0, 0, src.Width, src.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
// 判断是否在 -100~100
effectThreshold = effectThreshold
100 ? 100 : effectT
effectThreshold = (float)((100.0 + effectThreshold) / 100.0);
effectThreshold *= effectT
// 抓住第一个 Pixel 第一个数值
byte* p = (byte*)(void*)bitmapData.Scan0;
// 跨步值 - 宽度 *3 可以算出畸零地 之后跳到下一行
int nOffset = bitmapData.Stride - src.Width * 3;
for (int y = 0; y < src.H y++)
for (int x = 0; x
255 ? 255 :
buffer = buffer
255 ? 255 :
buffer = buffer
255 ? 255 :
buffer = buffer < 0 ? 0 :
p[0] = (byte)
// 跳去下一个 Pixel
// 跨越畸零地
src.UnlockBits(bitmapData);
#endregion
#region 对图片进行雾化效果
/// 对图片进行雾化效果
public Bitmap Atomization(Bitmap bmp)
int Height = bmp.H
int Width = bmp.W
Bitmap newBitmap = new Bitmap(Width, Height);
Bitmap oldBitmap =
for (int x = 1; x < Width - 1; x++)
for (int y = 1; y = Width)
dx = Width - 1;
if (dy >= Height)
dy = Height - 1;
pixel = oldBitmap.GetPixel(dx, dy);
newBitmap.SetPixel(x, y, pixel);
return newB
#endregion
} //END Class DrawValidationCode
#endregion
#region 高斯模糊算法
/// 高斯模糊算法
public class Gaussian
public static double[,] Calculate1DSampleKernel(double deviation, int size)
double[,] ret = new double[size, 1];
double sum = 0;
int half = size / 2;
for (int i = 0; i < i++)
ret[i, 0] = 1 / (Math.Sqrt(2 * Math.PI) * deviation) * Math.Exp(-(i - half) * (i - half) / (2 * deviation * deviation));
sum += ret[i, 0];
public static double[,] Calculate1DSampleKernel(double deviation)
int size = (int)Math.Ceiling(deviation * 3) * 2 + 1;
return Calculate1DSampleKernel(deviation, size);
public static double[,] CalculateNormalized1DSampleKernel(double deviation)
return NormalizeMatrix(Calculate1DSampleKernel(deviation));
public static double[,] NormalizeMatrix(double[,] matrix)
double[,] ret = new double[matrix.GetLength(0), matrix.GetLength(1)];
double sum = 0;
for (int i = 0; i < ret.GetLength(0); i++)
for (int j = 0; j < ret.GetLength(1); j++)
sum += matrix[i, j];
if (sum != 0)
for (int i = 0; i < ret.GetLength(0); i++)
for (int j = 0; j < ret.GetLength(1); j++)
ret[i, j] = matrix[i, j] /
public static double[,] GaussianConvolution(double[,] matrix, double deviation)
double[,] kernel = CalculateNormalized1DSampleKernel(deviation);
double[,] res1 = new double[matrix.GetLength(0), matrix.GetLength(1)];
double[,] res2 = new double[matrix.GetLength(0), matrix.GetLength(1)];
//x-direction
for (int i = 0; i < matrix.GetLength(0); i++)
for (int j = 0; j < matrix.GetLength(1); j++)
res1[i, j] = processPoint(matrix, i, j, kernel, 0);
//y-direction
for (int i = 0; i < matrix.GetLength(0); i++)
for (int j = 0; j < matrix.GetLength(1); j++)
res2[i, j] = processPoint(res1, i, j, kernel, 1);
return res2;
private static double processPoint(double[,] matrix, int x, int y, double[,] kernel, int direction)
double res = 0;
int half = kernel.GetLength(0) / 2;
for (int i = 0; i = 0 && cox = 0 && coy < matrix.GetLength(1))
res += matrix[cox, coy] * kernel[i, 0];
/// 对颜色值进行灰色处理
private Color grayscale(Color cr)
return Color.FromArgb(cr.A, (int)(cr.R * .3 + cr.G * .59 + cr.B * 0.11),
(int)(cr.R * .3 + cr.G * .59 + cr.B * 0.11),
(int)(cr.R * .3 + cr.G * .59 + cr.B * 0.11));
/// 对图片进行高斯模糊
/// 模糊数值,数值越大模糊越很
/// 一个需要处理的图片
public Bitmap FilterProcessImage(double d, Bitmap image)
Bitmap ret = new Bitmap(image.Width, image.Height);
Double[,] matrixR = new Double[image.Width, image.Height];
Double[,] matrixG = new Double[image.Width, image.Height];
Double[,] matrixB = new Double[image.Width, image.Height];
for (int i = 0; i < image.W i++)
for (int j = 0; j < image.H j++)
//matrix[i, j] = grayscale(image.GetPixel(i, j)).R;
matrixR[i, j] = image.GetPixel(i, j).R;
matrixG[i, j] = image.GetPixel(i, j).G;
matrixB[i, j] = image.GetPixel(i, j).B;
matrixR = Gaussian.GaussianConvolution(matrixR, d);
matrixG = Gaussian.GaussianConvolution(matrixG, d);
matrixB = Gaussian.GaussianConvolution(matrixB, d);
for (int i = 0; i < image.W i++)
for (int j = 0; j < image.H j++)
Int32 R = (int)Math.Min(255, matrixR[i, j]);
Int32 G = (int)Math.Min(255, matrixG[i, j]);
Int32 B = (int)Math.Min(255, matrixB[i, j]);
ret.SetPixel(i, j, Color.FromArgb(R, G, B));
#endregion
关于如何调用这个类,我举一个ASP.Net MVC中的例子:
//首先实例化验证码的类
ValidateCode validateCode = new ValidateCode();
//生成验证码指定的长度
string code = validateCode.GetRandomString(4);
//创建验证码的图片
byte[] bytes = validateCode.CreateImage(code);
//最后将验证码返回
return File(bytes, @"image/jpeg");
这样就可以了:
作者:胡孝林
本页版权归作者和CSDN博客所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利
(责任编辑:幽灵学院)
------分隔线----------------------------
c 代码实现打开文件 文件夹以及选择文件功能...
1、C 变量命名可以以邮件符@开头2、C 中字符串可以@开头,如...
xmal文件使用声明性语言,“”表示声明一个窗体对象。 对象存...
在进行软件开发,尤其是开发WinForm程序时,有时为了实现界...
菜单创建格式: {button: [{type: click,name: 今日歌曲,key...
错误和异常的总结 因为总结吗,,可能概念啥的比较多,大家要学...
工作日:9:00-21:00
周 六:9:00-18:00
&&扫一扫关注幽灵学院

我要回帖

更多关于 笔记本电脑黑屏 的文章

 

随机推荐