1 Star 0 Fork 27

amtech/tianruoocr

forked from ZZK-1989/tianruoocr 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
FmMain.cs 144.45 KB
一键复制 编辑 原始数据 按行查看 历史
zhang-zk 提交于 2021-08-07 13:56 . 添加个人需求:
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Web;
using System.Windows.Forms;
using Emgu.CV;
using Emgu.CV.CvEnum;
using Emgu.CV.Structure;
using Emgu.CV.Util;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using ShareX.ScreenCaptureLib;
using TrOCR.Helper;
using ZXing;
using ZXing.Common;
using ZXing.QrCode;
using Timer = System.Windows.Forms.Timer;
// ReSharper disable StringLiteralTypo
namespace TrOCR
{
public sealed partial class FmMain
{
public FmMain()
{
set_merge = false;
set_split = false;
set_split = false;
StaticValue.IsCapture = false;
pinyin_flag = false;
tranclick = false;
are = new AutoResetEvent(false);
imagelist = new List<Image>();
StaticValue.NoteCount = Convert.ToInt32(IniHelper.GetValue("配置", "记录数目"));
baidu_flags = "";
esc = "";
voice_count = 0;
fmNote = new FmNote();
pubnote = new string[StaticValue.NoteCount];
for (var i = 0; i < StaticValue.NoteCount; i++)
{
pubnote[i] = "";
}
StaticValue.v_note = pubnote;
StaticValue.mainHandle = Handle;
Font = new Font(Font.Name, 9f / StaticValue.DpiFactor, Font.Style, Font.Unit, Font.GdiCharSet, Font.GdiVerticalFont);
googleTranslate_txt = "";
num_ok = 0;
F_factor = Program.Factor;
components = null;
InitializeComponent();
nextClipboardViewer = (IntPtr)HelpWin32.SetClipboardViewer((int)Handle);
InitMinimize();
InitConfig();
WindowState = FormWindowState.Minimized;
Visible = false;
split_txt = "";
MinimumSize = new Size((int)font_base.Width * 23, (int)font_base.Height * 24);
speak_copy = false;
OCR_foreach("");
}
private void Load_Click(object sender, EventArgs e)
{
WindowState = FormWindowState.Minimized;
Visible = false;
}
protected override void WndProc(ref Message m)
{
if (m.Msg == 953)
{
speaking = false;
}
if (m.Msg == 274 && (int)m.WParam == 61536)
{
WindowState = FormWindowState.Minimized;
Visible = false;
return;
}
if (m.Msg == 600 && (int)m.WParam == 725)
{
if (IniHelper.GetValue("工具栏", "顶置") == "True")
{
TopMost = true;
return;
}
TopMost = false;
return;
}
if (m.Msg == 786 && m.WParam.ToInt32() == 530 && RichBoxBody.Text != null)
{
p_note(RichBoxBody.Text);
StaticValue.v_note = pubnote;
if (fmNote.Created)
{
fmNote.TextNote = "";
}
}
if (m.Msg == 786 && m.WParam.ToInt32() == 520)
{
fmNote.Show();
fmNote.Focus();
fmNote.Location = new Point(Screen.PrimaryScreen.WorkingArea.Width - fmNote.Width, Screen.PrimaryScreen.WorkingArea.Height - fmNote.Height);
fmNote.WindowState = FormWindowState.Normal;
return;
}
if (m.Msg == 786 && m.WParam.ToInt32() == 580)
{
HelpWin32.UnregisterHotKey(Handle, 205);
change_QQ_screenshot = false;
FormBorderStyle = FormBorderStyle.None;
Hide();
if (transtalate_fla == "开启")
{
form_width = Width / 2;
}
else
{
form_width = Width;
}
form_height = Height;
minico.Visible = false;
minico.Visible = true;
menu.Close();
menu_copy.Close();
auto_fla = "开启";
split_txt = "";
RichBoxBody.Text = "***该区域未发现文本***";
RichBoxBody_T.Text = "";
typeset_txt = "";
transtalate_fla = "关闭";
Trans_close.PerformClick();
Size = new Size((int)font_base.Width * 23, (int)font_base.Height * 24);
FormBorderStyle = FormBorderStyle.Sizable;
StaticValue.IsCapture = true;
image_screen = StaticValue.image_OCR;
if (IniHelper.GetValue("工具栏", "分栏") == "True")
{
minico.Visible = true;
thread = new Thread(ShowLoading);
thread.Start();
ts = new TimeSpan(DateTime.Now.Ticks);
var image = image_screen;
var image2 = new Bitmap(image.Width, image.Height);
var graphics = Graphics.FromImage(image2);
graphics.DrawImage(image, 0, 0, image.Width, image.Height);
graphics.Save();
graphics.Dispose();
image_ori = image2;
((Bitmap)FindBoundingBoxFences((Bitmap)image)).Save("Data\\分栏预览图.jpg");
}
else
{
minico.Visible = true;
thread = new Thread(ShowLoading);
thread.Start();
ts = new TimeSpan(DateTime.Now.Ticks);
var messageLoad = new Messageload();
messageLoad.ShowDialog();
if (messageLoad.DialogResult == DialogResult.OK)
{
esc_thread = new Thread(Main_OCR_Thread);
esc_thread.Start();
}
}
}
if (m.Msg == 786 && m.WParam.ToInt32() == 590 && speak_copyb == "朗读")
{
TTS();
return;
}
if (m.Msg == 786 && m.WParam.ToInt32() == 511)
{
MinimumSize = new Size((int)font_base.Width * 23, (int)font_base.Height * 24);
transtalate_fla = "关闭";
RichBoxBody.Dock = DockStyle.Fill;
RichBoxBody_T.Visible = false;
PictureBox1.Visible = false;
RichBoxBody_T.Text = "";
if (WindowState == FormWindowState.Maximized)
{
WindowState = FormWindowState.Normal;
}
Size = new Size((int)font_base.Width * 23, (int)font_base.Height * 24);
}
if (m.Msg == 786 && m.WParam.ToInt32() == 512)
{
TransClick();
}
if (m.Msg == 786 && m.WParam.ToInt32() == 518)
{
if (ActiveControl.Name == "htmlTextBoxBody")
{
htmltxt = RichBoxBody.Text;
}
if (ActiveControl.Name == "rich_trans")
{
htmltxt = RichBoxBody_T.Text;
}
if (htmltxt == "")
{
return;
}
TTS();
}
if (m.Msg == 161)
{
HelpWin32.SetForegroundWindow(Handle);
base.WndProc(ref m);
return;
}
if (m.Msg != 163)
{
if (m.Msg == 786 && m.WParam.ToInt32() == 222)
{
try
{
StaticValue.IsCapture = false;
esc = "退出";
fmloading.FmlClose = "窗体已关闭";
esc_thread.Abort();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
FormBorderStyle = FormBorderStyle.Sizable;
Visible = true;
Show();
WindowState = FormWindowState.Normal;
if (IniHelper.GetValue("快捷键", "翻译文本") != "请按下快捷键")
{
var value = IniHelper.GetValue("快捷键", "翻译文本");
var text = "None";
var text2 = "F9";
SetHotkey(text, text2, value, 205);
}
HelpWin32.UnregisterHotKey(Handle, 222);
}
if (m.Msg == 786 && m.WParam.ToInt32() == 200)
{
HelpWin32.UnregisterHotKey(Handle, 205);
menu.Hide();
RichBoxBody.Hide = "";
RichBoxBody_T.Hide = "";
MainOCRQuickScreenShots();
}
if (m.Msg == 786 && m.WParam.ToInt32() == 206)
{
if (!fmNote.Visible || Focused)
{
fmNote.Show();
fmNote.WindowState = FormWindowState.Normal;
fmNote.Visible = true;
}
else
{
fmNote.Hide();
fmNote.WindowState = FormWindowState.Minimized;
fmNote.Visible = false;
}
}
if (m.Msg == 786 && m.WParam.ToInt32() == 235)
{
if (!Visible)
{
TopMost = true;
Show();
WindowState = FormWindowState.Normal;
Visible = true;
Thread.Sleep(100);
if (IniHelper.GetValue("工具栏", "顶置") == "False")
{
TopMost = false;
return;
}
}
else
{
Hide();
Visible = false;
}
}
if (m.Msg == 786 && m.WParam.ToInt32() == 205)
{
翻译文本();
}
base.WndProc(ref m);
return;
}
if (transtalate_fla == "开启")
{
WindowState = FormWindowState.Normal;
Size = new Size((int)font_base.Width * 23 * 2, (int)font_base.Height * 24);
Location = (Point)new Size(Screen.PrimaryScreen.Bounds.Width / 2 - Screen.PrimaryScreen.Bounds.Width / 10 * 2, Screen.PrimaryScreen.Bounds.Height / 2 - Screen.PrimaryScreen.Bounds.Height / 6);
return;
}
WindowState = FormWindowState.Normal;
Location = (Point)new Size(Screen.PrimaryScreen.Bounds.Width / 2 - Screen.PrimaryScreen.Bounds.Width / 10, Screen.PrimaryScreen.Bounds.Height / 2 - Screen.PrimaryScreen.Bounds.Height / 6);
Size = new Size((int)font_base.Width * 23, (int)font_base.Height * 24);
}
public void InitMinimize()
{
try
{
var menuItems = new[]
{
new MenuItem("显示", trayShowClick),
new MenuItem("设置", tray_Set_Click),
//new MenuItem("更新", tray_update_Click),
new MenuItem("帮助", tray_help_Click),
new MenuItem("退出", trayExitClick)
};
minico.ContextMenu = new ContextMenu(menuItems);
}
catch (Exception ex)
{
MessageBox.Show("InitMinimize()" + ex.Message);
}
}
private void trayShowClick(object sender, EventArgs e)
{
Show();
Activate();
Visible = true;
WindowState = FormWindowState.Normal;
TopMost = IniHelper.GetValue("工具栏", "顶置") == "True";
}
private void trayExitClick(object sender, EventArgs e)
{
minico.Dispose();
saveIniFile();
Process.GetCurrentProcess().Kill();
}
private void MainCopyClick(object sender, EventArgs e)
{
RichBoxBody.Focus();
RichBoxBody.richTextBox1.Copy();
}
private void Main_SelectAll_Click(object sender, EventArgs e)
{
RichBoxBody.Focus();
RichBoxBody.richTextBox1.SelectAll();
}
private void Main_paste_Click(object sender, EventArgs e)
{
RichBoxBody.Focus();
RichBoxBody.richTextBox1.Paste();
}
public void OCR_Tencent()
{
try
{
split_txt = "";
var image = image_screen;
if (image.Width > 90 && image.Height < 90)
{
var bitmap = new Bitmap(image.Width, 300);
var graphics = Graphics.FromImage(bitmap);
graphics.DrawImage(image, 5, 0, image.Width, image.Height);
graphics.Save();
graphics.Dispose();
image = new Bitmap(bitmap);
}
else if (image.Width <= 90 && image.Height >= 90)
{
var bitmap2 = new Bitmap(300, image.Height);
var graphics2 = Graphics.FromImage(bitmap2);
graphics2.DrawImage(image, 0, 5, image.Width, image.Height);
graphics2.Save();
graphics2.Dispose();
image = new Bitmap(bitmap2);
}
else if (image.Width < 90 && image.Height < 90)
{
var bitmap3 = new Bitmap(300, 300);
var graphics3 = Graphics.FromImage(bitmap3);
graphics3.DrawImage(image, 5, 5, image.Width, image.Height);
graphics3.Save();
graphics3.Dispose();
image = new Bitmap(bitmap3);
}
else
{
image = image_screen;
}
var value = OcrHelper.TxOcr(image);
var jArray = JArray.Parse(((JObject)JsonConvert.DeserializeObject(value))["data"]["item_list"].ToString());
checked_txt(jArray, 1, "itemstring");
}
catch
{
if (esc != "退出")
{
RichBoxBody.Text = "***该区域未发现文本***";
}
else
{
RichBoxBody.Text = "***该区域未发现文本***";
esc = "";
}
}
}
public void OCR_baidu_bak()
{
split_txt = "";
try
{
var str = "CHN_ENG";
split_txt = "";
var image = image_screen;
var array = OcrHelper.ImgToBytes(image);
switch (interface_flag)
{
case "中英":
str = "CHN_ENG";
break;
case "日语":
str = "JAP";
break;
case "韩语":
str = "KOR";
break;
}
var data = "type=general_location&image=data" + HttpUtility.UrlEncode(":image/jpeg;base64," + Convert.ToBase64String(array)) + "&language_type=" + str;
var value = CommonHelper.PostStrData("http://ai.baidu.com/tech/ocr/general", data);
var jArray = JArray.Parse(((JObject)JsonConvert.DeserializeObject(value))["data"]["words_result"].ToString());
var str2 = "";
var str3 = "";
foreach (var arr in jArray)
{
var jObject = JObject.Parse(arr.ToString());
var array2 = jObject["words"].ToString().ToCharArray();
if (!char.IsPunctuation(array2[array2.Length - 1]))
{
if (!contain_ch(jObject["words"].ToString()))
{
str3 = str3 + jObject["words"].ToString().Trim() + " ";
}
else
{
str3 += jObject["words"].ToString();
}
}
else if (own_punctuation(array2[array2.Length - 1].ToString()))
{
if (!contain_ch(jObject["words"].ToString()))
{
str3 = str3 + jObject["words"].ToString().Trim() + " ";
}
else
{
str3 += jObject["words"].ToString();
}
}
else
{
str3 = str3 + jObject["words"] + "\r\n";
}
str2 = str2 + jObject["words"] + "\r\n";
}
split_txt = str2;
typeset_txt = str3;
}
catch
{
if (esc != "退出")
{
RichBoxBody.Text = "***该区域未发现文本***";
}
else
{
RichBoxBody.Text = "***该区域未发现文本***";
esc = "";
}
}
}
private void OCR_sougou_Click(object sender, EventArgs e)
{
OCR_foreach("搜狗");
}
private void OCR_tencent_Click(object sender, EventArgs e)
{
OCR_foreach("腾讯");
}
private void OCR_baidu_Click(object sender, EventArgs e)
{
}
public void OCR_youdao()
{
try
{
split_txt = "";
var image = image_screen;
if (image.Width > 90 && image.Height < 90)
{
var bitmap = new Bitmap(image.Width, 200);
var graphics = Graphics.FromImage(bitmap);
graphics.DrawImage(image, 5, 0, image.Width, image.Height);
graphics.Save();
graphics.Dispose();
image = new Bitmap(bitmap);
}
else if (image.Width <= 90 && image.Height >= 90)
{
var bitmap2 = new Bitmap(200, image.Height);
var graphics2 = Graphics.FromImage(bitmap2);
graphics2.DrawImage(image, 0, 5, image.Width, image.Height);
graphics2.Save();
graphics2.Dispose();
image = new Bitmap(bitmap2);
}
else if (image.Width < 90 && image.Height < 90)
{
var bitmap3 = new Bitmap(200, 200);
var graphics3 = Graphics.FromImage(bitmap3);
graphics3.DrawImage(image, 5, 5, image.Width, image.Height);
graphics3.Save();
graphics3.Dispose();
image = new Bitmap(bitmap3);
}
else
{
image = image_screen;
}
var i = image.Width;
var j = image.Height;
if (i < 600)
{
while (i < 600)
{
j *= 2;
i *= 2;
}
}
if (j < 120)
{
while (j < 120)
{
j *= 2;
i *= 2;
}
}
var bitmap4 = new Bitmap(i, j);
var graphics4 = Graphics.FromImage(bitmap4);
graphics4.DrawImage(image, 0, 0, i, j);
graphics4.Save();
graphics4.Dispose();
image = new Bitmap(bitmap4);
var inArray = OcrHelper.ImgToBytes(image);
var data = "imgBase=data" + HttpUtility.UrlEncode(":image/jpeg;base64," + Convert.ToBase64String(inArray)) + "&lang=auto&company=";
var value = CommonHelper.PostStrData("http://aidemo.youdao.com/ocrapi1", data, "",
"http://aidemo.youdao.com/ocrdemo");
var jArray = JArray.Parse(((JObject)JsonConvert.DeserializeObject(value))["lines"].ToString());
checked_txt(jArray, 1, "words");
image.Dispose();
}
catch
{
if (esc != "退出")
{
RichBoxBody.Text = "***该区域未发现文本***";
}
else
{
RichBoxBody.Text = "***该区域未发现文本***";
esc = "";
}
}
}
public void OCR_youdao_Click(object sender, EventArgs e)
{
OCR_foreach("有道");
}
public void change_Chinese_Click(object sender, EventArgs e)
{
language = "中文标点";
if (typeset_txt != "")
{
RichBoxBody.Text = punctuation_en_ch_x(RichBoxBody.Text);
RichBoxBody.Text = punctuation_quotation(RichBoxBody.Text);
}
}
public void change_English_Click(object sender, EventArgs e)
{
language = "英文标点";
if (typeset_txt != "")
{
RichBoxBody.Text = punctuation_ch_en(RichBoxBody.Text);
}
}
public static string punctuation_ch_en(string text)
{
var array = text.ToCharArray();
for (var i = 0; i < array.Length; i++)
{
var num = ":。;,?!“”‘’【】()".IndexOf(array[i]);
if (num != -1)
{
array[i] = ":.;,?!\"\"''[]()"[num];
}
}
return new string(array);
}
public void saveIniFile()
{
IniHelper.SetValue("配置", "接口", interface_flag);
}
private void InitConfig()
{
interface_flag = IniHelper.GetValue("配置", "接口");
if (interface_flag == "发生错误")
{
IniHelper.SetValue("配置", "接口", "搜狗");
OCR_foreach("搜狗");
}
else
{
OCR_foreach(interface_flag);
}
var filePath = AppDomain.CurrentDomain.BaseDirectory + "Data\\config.ini";
if (IniHelper.GetValue("快捷键", "文字识别") != "请按下快捷键")
{
var value = IniHelper.GetValue("快捷键", "文字识别");
var text = "None";
var text2 = "F4";
SetHotkey(text, text2, value, 200);
}
if (IniHelper.GetValue("快捷键", "翻译文本") != "请按下快捷键")
{
var value2 = IniHelper.GetValue("快捷键", "翻译文本");
var text3 = "None";
var text4 = "F7";
SetHotkey(text3, text4, value2, 205);
}
if (IniHelper.GetValue("快捷键", "记录界面") != "请按下快捷键")
{
var value3 = IniHelper.GetValue("快捷键", "记录界面");
var text5 = "None";
var text6 = "F8";
SetHotkey(text5, text6, value3, 206);
}
if (IniHelper.GetValue("快捷键", "识别界面") != "请按下快捷键")
{
var value4 = IniHelper.GetValue("快捷键", "识别界面");
var text7 = "None";
var text8 = "F11";
SetHotkey(text7, text8, value4, 235);
}
StaticValue.BD_API_ID = HelpWin32.IniFileHelper.GetValue("密钥_百度", "secret_id", filePath);
if (HelpWin32.IniFileHelper.GetValue("密钥_百度", "secret_id", filePath) == "发生错误")
{
StaticValue.BD_API_ID = "请输入secret_id";
}
StaticValue.BD_API_KEY = HelpWin32.IniFileHelper.GetValue("密钥_百度", "secret_key", filePath);
if (HelpWin32.IniFileHelper.GetValue("密钥_百度", "secret_key", filePath) == "发生错误")
{
StaticValue.BD_API_KEY = "请输入secret_key";
}
}
public static string check_ch_en(string text)
{
var array = text.ToCharArray();
for (var i = 0; i < array.Length; i++)
{
var num = ":".IndexOf(array[i]);
if (num != -1 && i - 1 >= 0 && i + 1 < array.Length && contain_en(array[i - 1].ToString()) && contain_en(array[i + 1].ToString()))
{
array[i] = ":"[num];
}
if (num != -1 && i - 1 >= 0 && i + 1 < array.Length && contain_en(array[i - 1].ToString()) && contain_punctuation(array[i + 1].ToString()))
{
array[i] = ":"[num];
}
}
return new string(array);
}
public void tray_Set_Click(object sender, EventArgs e)
{
HelpWin32.UnregisterHotKey(Handle, 200);
HelpWin32.UnregisterHotKey(Handle, 205);
HelpWin32.UnregisterHotKey(Handle, 206);
HelpWin32.UnregisterHotKey(Handle, 235);
WindowState = FormWindowState.Minimized;
var fmSetting = new FmSetting();
fmSetting.TopMost = true;
fmSetting.ShowDialog();
if (fmSetting.DialogResult == DialogResult.OK)
{
var filePath = AppDomain.CurrentDomain.BaseDirectory + "Data\\config.ini";
StaticValue.NoteCount = Convert.ToInt32(HelpWin32.IniFileHelper.GetValue("配置", "记录数目", filePath));
pubnote = new string[StaticValue.NoteCount];
for (var i = 0; i < StaticValue.NoteCount; i++)
{
pubnote[i] = "";
}
StaticValue.v_note = pubnote;
fmNote.TextNoteChange = "";
fmNote.Location = new Point(Screen.AllScreens[0].WorkingArea.Width - fmNote.Width, Screen.AllScreens[0].WorkingArea.Height - fmNote.Height);
if (IniHelper.GetValue("快捷键", "文字识别") != "请按下快捷键")
{
var value = IniHelper.GetValue("快捷键", "文字识别");
var text = "None";
var text2 = "F4";
SetHotkey(text, text2, value, 200);
}
if (IniHelper.GetValue("快捷键", "翻译文本") != "请按下快捷键")
{
var value2 = IniHelper.GetValue("快捷键", "翻译文本");
var text3 = "None";
var text4 = "F9";
SetHotkey(text3, text4, value2, 205);
}
if (IniHelper.GetValue("快捷键", "记录界面") != "请按下快捷键")
{
var value3 = IniHelper.GetValue("快捷键", "记录界面");
var text5 = "None";
var text6 = "F8";
SetHotkey(text5, text6, value3, 206);
}
if (IniHelper.GetValue("快捷键", "识别界面") != "请按下快捷键")
{
var value4 = IniHelper.GetValue("快捷键", "识别界面");
var text7 = "None";
var text8 = "F11";
SetHotkey(text7, text8, value4, 235);
}
StaticValue.BD_API_ID = IniHelper.GetValue("密钥_百度", "secret_id");
StaticValue.BD_API_KEY = IniHelper.GetValue("密钥_百度", "secret_key");
}
}
public static bool IsNum(string str)
{
return Regex.IsMatch(str, "^\\d+$");
}
public bool own_punctuation(string text)
{
return ",;,、<>《》()-().。".IndexOf(text, StringComparison.Ordinal) != -1;
}
public static string punctuation_Del_space(string text)
{
var pattern = "(?<=.)([^\\*]+)(?=.)";
string result;
if (Regex.Match(text, pattern).ToString().IndexOf(" ", StringComparison.Ordinal) >= 0)
{
text = Regex.Replace(text, "(?<=[\\p{P}*])([a-zA-Z])(?=[a-zA-Z])", " $1");
text = text.TrimEnd(null).Replace("- ", "-").Replace("_ ", "_").Replace("( ", "(").Replace("/ ", "/").Replace("\" ", "\"");
result = text;
}
else
{
result = text;
}
return result;
}
public static bool contain_ch(string str)
{
return Regex.IsMatch(str, "[\\u4e00-\\u9fa5]");
}
public void TransClick()
{
typeset_txt = RichBoxBody.Text;
RichBoxBody_T.Visible = true;
WindowState = FormWindowState.Normal;
transtalate_fla = "开启";
RichBoxBody.Dock = DockStyle.None;
RichBoxBody_T.Dock = DockStyle.None;
RichBoxBody_T.BorderStyle = BorderStyle.Fixed3D;
RichBoxBody_T.Text = "";
RichBoxBody.Focus();
if (num_ok == 0)
{
RichBoxBody.Size = new Size(ClientRectangle.Width, ClientRectangle.Height);
Size = new Size(RichBoxBody.Width * 2, RichBoxBody.Height);
RichBoxBody_T.Size = new Size(RichBoxBody.Width, RichBoxBody.Height);
RichBoxBody_T.Location = (Point)new Size(RichBoxBody.Width, 0);
RichBoxBody_T.Name = "rich_trans";
RichBoxBody_T.TabIndex = 1;
RichBoxBody_T.Text_flag = "我是翻译文本框";
RichBoxBody_T.ImeMode = ImeMode.On;
}
num_ok++;
PictureBox1.Visible = true;
PictureBox1.BringToFront();
MinimumSize = new Size((int)font_base.Width * 23 * 2, (int)font_base.Height * 24);
Size = new Size((int)font_base.Width * 23 * 2, (int)font_base.Height * 24);
CheckForIllegalCrossThreadCalls = false;
new Thread(trans_Calculate).Start();
}
private void Form_Resize(object sender, EventArgs e)
{
if (RichBoxBody.Dock != DockStyle.Fill)
{
RichBoxBody.Size = new Size(ClientRectangle.Width / 2, ClientRectangle.Height);
RichBoxBody_T.Size = new Size(RichBoxBody.Width, ClientRectangle.Height);
RichBoxBody_T.Location = (Point)new Size(RichBoxBody.Width, 0);
}
}
public void Trans_copy_Click(object sender, EventArgs e)
{
RichBoxBody_T.Focus();
RichBoxBody_T.richTextBox1.Copy();
}
public void Trans_paste_Click(object sender, EventArgs e)
{
RichBoxBody_T.Focus();
RichBoxBody_T.richTextBox1.Paste();
}
public void Trans_SelectAll_Click(object sender, EventArgs e)
{
RichBoxBody_T.Focus();
RichBoxBody_T.richTextBox1.SelectAll();
}
public void trans_Calculate()
{
if (pinyin_flag)
{
googleTranslate_txt = HanToPinyin.GetFullPinyin(typeset_txt);
}
else if (typeset_txt == "")
{
googleTranslate_txt = "";
}
else
{
if (interface_flag == "韩语")
{
StaticValue.ZH2EN = false;
StaticValue.ZH2JP = false;
StaticValue.ZH2KO = true;
RichBoxBody_T.set_language = "韩语";
}
if (interface_flag == "日语")
{
StaticValue.ZH2EN = false;
StaticValue.ZH2JP = true;
StaticValue.ZH2KO = false;
RichBoxBody_T.set_language = "日语";
}
if (interface_flag == "中英")
{
StaticValue.ZH2EN = true;
StaticValue.ZH2JP = false;
StaticValue.ZH2KO = false;
RichBoxBody_T.set_language = "中英";
}
if (IniHelper.GetValue("配置", "翻译接口") == "谷歌")
{
googleTranslate_txt = Translate_Google(typeset_txt);
}
if (IniHelper.GetValue("配置", "翻译接口") == "百度")
{
googleTranslate_txt = TranslateBaidu(typeset_txt);
}
if (IniHelper.GetValue("配置", "翻译接口") == "腾讯")
{
googleTranslate_txt = Translate_Tencent(typeset_txt);
}
}
PictureBox1.Visible = false;
PictureBox1.SendToBack();
Invoke(new Translate(translate_child));
pinyin_flag = false;
}
public void Trans_close_Click(object sender, EventArgs e)
{
MinimumSize = new Size((int)font_base.Width * 23, (int)font_base.Height * 24);
transtalate_fla = "关闭";
RichBoxBody.Dock = DockStyle.Fill;
RichBoxBody_T.Visible = false;
PictureBox1.Visible = false;
RichBoxBody_T.Text = "";
if (WindowState == FormWindowState.Maximized)
{
WindowState = FormWindowState.Normal;
}
Size = new Size((int)font_base.Width * 23, (int)font_base.Height * 24);
}
private void ShowLoading()
{
try
{
fmloading = new FmLoading();
Application.Run(fmloading);
}
catch (ThreadAbortException)
{
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
thread.Abort();
}
}
public bool contain(string text, string subStr)
{
return text.Contains(subStr);
}
public static bool contain_en(string str)
{
return Regex.IsMatch(str, "[a-zA-Z]");
}
public static bool punctuation_has_punctuation(string str)
{
var pattern = contain_ch(str) ? "[\\;\\,\\。\\!\\?]" : "[\\;\\,\\.\\!\\?]";
return Regex.IsMatch(str, pattern);
}
private string punctuation_quotation(string pStr)
{
pStr = pStr.Replace("“", "\"").Replace("”", "\"");
var array = pStr.Split('"');
var text = "";
for (var i = 1; i <= array.Length; i++)
{
if (i % 2 == 0)
{
text = text + array[i - 1] + "”";
}
else
{
text = text + array[i - 1] + "“";
}
}
return text.Substring(0, text.Length - 1);
}
public static bool HasenPunctuation(string str)
{
var pattern = "[\\;\\,\\.\\!\\?]";
return Regex.IsMatch(str, pattern);
}
public static string Del_Space(string text)
{
text = Regex.Replace(text, "([\\p{P}]+)", "**&&**$1**&&**");
text = text.TrimEnd(null).Replace(" **&&**", "").Replace("**&&** ", "").Replace("**&&**", "");
return text;
}
public void TTS()
{
new Thread(TTS_thread).Start();
}
private void translate_child()
{
RichBoxBody_T.Text = googleTranslate_txt;
googleTranslate_txt = "";
}
public void TTS_thread()
{
try
{
var text = htmltxt.Replace("***", "");
var lang = CommonHelper.LangDetect(text);
// var url = "https://fanyi.baidu.com/gettts?lan=" + lang + "&text=" + HttpUtility.UrlEncode(text) +
// "&vol=9&per=0&spd=6&pit=4&source=web&ctp=1";
var url = TranslateHelper.BdTts(text, lang, 5);
ttsData = new WebClient().DownloadData(url);
if (speak_copyb == "朗读" || voice_count == 0)
{
Invoke(new Translate(Speak_child));
speak_copyb = "";
}
else
{
Invoke(new Translate(TTS_child));
}
voice_count++;
}
catch (Exception)
{
MessageBox.Show("文本过长,请使用右键菜单中的选中朗读!", "提醒");
}
}
public void TTS_child()
{
if (RichBoxBody.Text != null || RichBoxBody_T.Text != "")
{
if (speaking)
{
HelpWin32.mciSendString("close media", null, 0, IntPtr.Zero);
speaking = false;
return;
}
var tempPath = Path.GetTempPath();
var text = tempPath + "\\声音.mp3";
try
{
File.WriteAllBytes(text, ttsData);
}
catch
{
text = tempPath + "\\声音1.mp3";
File.WriteAllBytes(text, ttsData);
}
PlaySong(text);
speaking = true;
}
}
protected override CreateParams CreateParams
{
get
{
var createParams = base.CreateParams;
createParams.ExStyle |= 134217728;
return createParams;
}
}
public string Translate_Google(string text)
{
var text2 = "";
try
{
var text3 = "zh-CN";
var text4 = "en";
if (StaticValue.ZH2EN)
{
if (ch_count(text.Trim()) > en_count(text.Trim()) || (en_count(text.Trim()) == 1 && ch_count(text.Trim()) == 1))
{
text3 = "zh-CN";
text4 = "en";
}
else
{
text3 = "en";
text4 = "zh-CN";
}
}
if (StaticValue.ZH2JP)
{
if (contain_jap(replaceStr(Del_ch(text.Trim()))))
{
text3 = "ja";
text4 = "zh-CN";
}
else
{
text3 = "zh-CN";
text4 = "ja";
}
}
if (StaticValue.ZH2KO)
{
if (contain_kor(text.Trim()))
{
text3 = "ko";
text4 = "zh-CN";
}
else
{
text3 = "zh-CN";
text4 = "ko";
}
}
var data = string.Concat("client=gtx&sl=", text3, "&tl=", text4, "&dt=t&q=",
HttpUtility.UrlEncode(text)?.Replace("+", "%20"));
var html = CommonHelper.PostStrData("https://translate.google.cn/translate_a/single", data);
var jArray = (JArray)JsonConvert.DeserializeObject(html);
var count = ((JArray)jArray[0]).Count;
for (var i = 0; i < count; i++)
{
text2 += jArray[0][i][0].ToString();
}
}
catch (Exception)
{
text2 = "[谷歌接口报错]:\r\n1.网络错误或者文本过长。\r\n2.谷歌接口可能对于某些网络不能用,具体不清楚。可以尝试挂VPN试试。\r\n3.这个问题我没办法修复,请右键菜单更换百度、腾讯翻译接口。";
}
return text2;
}
public static string CookieCollectionToStrCookie(CookieCollection cookie)
{
string result;
if (cookie == null)
{
result = string.Empty;
}
else
{
var text = string.Empty;
foreach (var obj in cookie)
{
var cookie2 = (Cookie)obj;
text += string.Format("{0}={1};", cookie2.Name, cookie2.Value);
}
result = text;
}
return result;
}
public string ScanQRCode()
{
var result = "";
try
{
var image = new BinaryBitmap(new HybridBinarizer(new BitmapLuminanceSource((Bitmap)image_screen)));
var result2 = new QRCodeReader().decode(image);
if (result2 != null)
{
result = result2.Text;
}
}
catch
{
}
return result;
}
public void SearchSelText(object sender, EventArgs e)
{
Process.Start("https://www.baidu.com/s?wd=" + RichBoxBody.SelectText);
}
public void tray_update_Click(object sender, EventArgs e)
{
Program.CheckUpdate();
}
public static bool contain_jap(string str)
{
return Regex.IsMatch(str, "[\\u3040-\\u309F]") || Regex.IsMatch(str, "[\\u30A0-\\u30FF]");
}
public static bool contain_kor(string str)
{
return Regex.IsMatch(str, "[\\uac00-\\ud7ff]");
}
public static string Del_ch(string str)
{
var text = str;
if (Regex.IsMatch(str, "[\\u4e00-\\u9fa5]"))
{
text = string.Empty;
var array = str.ToCharArray();
for (var i = 0; i < array.Length; i++)
{
if (array[i] < '一' || array[i] > '龥')
{
text += array[i].ToString();
}
}
}
return text;
}
private static string replaceStr(string hexData)
{
return Regex.Replace(hexData, "[\\p{P}+~$`^=|<>~`$^+=|<>¥×┊ ]", "").ToUpper();
}
public static string RemovePunctuation(string str)
{
str = str.Replace(",", "").Replace(",", "").Replace(".", "").Replace("。", "").Replace("!", "").Replace("!", "").Replace("?", "").Replace("?", "").Replace(":", "").Replace(":", "").Replace(";", "").Replace(";", "").Replace("~", "").Replace("-", "").Replace("_", "").Replace("——", "").Replace("—", "").Replace("--", "").Replace("【", "").Replace("】", "").Replace("\\", "").Replace("(", "").Replace(")", "").Replace("(", "").Replace(")", "").Replace("#", "").Replace("$", "").Replace("、", "").Replace("‘", "").Replace("’", "").Replace("“", "").Replace("”", "");
return str;
}
public static string GetUniqueFileName(string fullName)
{
string result;
if (!File.Exists(fullName))
{
result = fullName;
}
else
{
var directoryName = Path.GetDirectoryName(fullName);
var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fullName);
var extension = Path.GetExtension(fullName);
var num = 1;
string text;
do
{
text = Path.Combine(directoryName, string.Format("{0}[{1}].{2}", fileNameWithoutExtension, num++, extension));
}
while (File.Exists(text));
result = text;
}
return result;
}
public static string ReFileName(string strFolderPath, string strFileName)
{
var text = strFolderPath + "\\" + strFileName;
var startIndex = text.LastIndexOf('.');
text = text.Insert(startIndex, "_{0}");
var num = 1;
var path = string.Format(text, num);
while (File.Exists(path))
{
path = string.Format(text, num);
num++;
}
return Path.GetFileName(path);
}
public void PlaySong(string file)
{
HelpWin32.mciSendString("close media", null, 0, IntPtr.Zero);
HelpWin32.mciSendString("open \"" + file + "\" type mpegvideo alias media", null, 0, IntPtr.Zero);
HelpWin32.mciSendString("play media notify", null, 0, Handle);
}
public void Main_Voice_Click(object sender, EventArgs e)
{
RichBoxBody.Focus();
speak_copyb = "朗读";
htmltxt = RichBoxBody.SelectText;
HelpWin32.SendMessage(Handle, 786, 590);
}
public void Trans_Voice_Click(object sender, EventArgs e)
{
RichBoxBody_T.Focus();
speak_copyb = "朗读";
htmltxt = RichBoxBody_T.SelectText;
HelpWin32.SendMessage(Handle, 786, 590);
}
public void Speak_child()
{
if (RichBoxBody.Text != null || RichBoxBody_T.Text != "")
{
var tempPath = Path.GetTempPath();
var text = tempPath + "\\声音.mp3";
try
{
File.WriteAllBytes(text, ttsData);
}
catch
{
text = tempPath + "\\声音1.mp3";
File.WriteAllBytes(text, ttsData);
}
PlaySong(text);
speaking = true;
}
}
public static string ToSimplified(string source)
{
var text = new string(' ', source.Length);
HelpWin32.LCMapString(2048, 33554432, source, source.Length, text, source.Length);
return text;
}
public static string ToTraditional(string source)
{
var text = new string(' ', source.Length);
HelpWin32.LCMapString(2048, 67108864, source, source.Length, text, source.Length);
return text;
}
public void change_zh_tra_Click(object sender, EventArgs e)
{
if (RichBoxBody.Text != null)
{
RichBoxBody.Text = ToTraditional(RichBoxBody.Text);
}
}
public void change_tra_zh_Click(object sender, EventArgs e)
{
if (RichBoxBody.Text != null)
{
RichBoxBody.Text = ToSimplified(RichBoxBody.Text);
}
}
public void change_str_Upper_Click(object sender, EventArgs e)
{
if (RichBoxBody.Text != null)
{
RichBoxBody.Text = RichBoxBody.Text.ToUpper();
}
}
public void change_Upper_str_Click(object sender, EventArgs e)
{
if (RichBoxBody.Text != null)
{
RichBoxBody.Text = RichBoxBody.Text.ToLower();
}
}
public string[] hotkey(string text, string text2, string value)
{
var array = (value + "+").Split('+');
if (array.Length == 3)
{
text = array[0];
text2 = array[1];
}
if (array.Length == 2)
{
text = "None";
text2 = value;
}
return new[]
{
text,
text2
};
}
public void SetHotkey(string text, string text2, string value, int flag)
{
var array = (value + "+").Split('+');
if (array.Length == 3)
{
text = array[0];
text2 = array[1];
}
if (array.Length == 2)
{
text = "None";
text2 = value;
}
var array2 = new[]
{
text,
text2
};
if (!HelpWin32.RegisterHotKey(Handle, flag, (HelpWin32.KeyModifiers)Enum.Parse(typeof(HelpWin32.KeyModifiers), array2[0].Trim()), (Keys)Enum.Parse(typeof(Keys), array2[1].Trim())))
{
CommonHelper.ShowHelpMsg("快捷键冲突,请更换!");
}
HelpWin32.RegisterHotKey(Handle, flag, (HelpWin32.KeyModifiers)Enum.Parse(typeof(HelpWin32.KeyModifiers), array2[0].Trim()), (Keys)Enum.Parse(typeof(Keys), array2[1].Trim()));
}
public void p_note(string a)
{
for (var i = 0; i < StaticValue.NoteCount; i++)
{
if (i == StaticValue.NoteCount - 1)
{
pubnote[StaticValue.NoteCount - 1] = a;
}
else
{
pubnote[i] = pubnote[i + 1];
}
}
}
private string GetTextFromClipboard()
{
if (Thread.CurrentThread.GetApartmentState() > ApartmentState.STA)
{
var thread = new Thread(delegate()
{
SendKeys.SendWait("^c");
SendKeys.Flush();
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();
}
else
{
SendKeys.SendWait("^c");
SendKeys.Flush();
}
var text = Clipboard.GetText();
text = (string.IsNullOrWhiteSpace(text) ? null : text);
if (text != null)
{
Clipboard.Clear();
}
return text;
}
public void MainOCRQuickScreenShots()
{
if (StaticValue.IsCapture) return;
try
{
change_QQ_screenshot = false;
FormBorderStyle = FormBorderStyle.None;
Visible = false;
Thread.Sleep(100);
if (transtalate_fla == "开启")
{
form_width = Width / 2;
}
else
{
form_width = Width;
}
shupai_Right_txt = "";
shupai_Left_txt = "";
form_height = Height;
minico.Visible = false;
minico.Visible = true;
menu.Close();
menu_copy.Close();
auto_fla = "开启";
split_txt = "";
RichBoxBody.Text = "***该区域未发现文本***";
RichBoxBody_T.Text = "";
typeset_txt = "";
transtalate_fla = "关闭";
if (IniHelper.GetValue("工具栏", "翻译") == "False")
{
Trans_close.PerformClick();
}
Size = new Size((int)font_base.Width * 23, (int)font_base.Height * 24);
FormBorderStyle = FormBorderStyle.Sizable;
StaticValue.IsCapture = true;
image_screen = RegionCaptureTasks.GetRegionImage_Mo(new RegionCaptureOptions
{
ShowMagnifier = false,
UseSquareMagnifier = false,
MagnifierPixelCount = 15,
MagnifierPixelSize = 10
}, out var modeFlag, out var point, out var buildRects);
if (modeFlag == "高级截图")
{
var mode = RegionCaptureMode.Annotation;
var options = new RegionCaptureOptions();
using (var regionCaptureForm = new RegionCaptureForm(mode, options))
{
regionCaptureForm.Image_get = false;
regionCaptureForm.Prepare(image_screen);
regionCaptureForm.ShowDialog();
image_screen = null;
image_screen = regionCaptureForm.GetResultImage();
modeFlag = regionCaptureForm.Mode_flag;
}
}
HelpWin32.RegisterHotKey(Handle, 222, HelpWin32.KeyModifiers.None, Keys.Escape);
switch (modeFlag)
{
case "贴图":
{
var locationPoint = new Point(point.X, point.Y);
new FmScreenPaste(image_screen, locationPoint).Show();
if (IniHelper.GetValue("快捷键", "翻译文本") != "请按下快捷键")
{
var value = IniHelper.GetValue("快捷键", "翻译文本");
var text = "None";
var text2 = "F9";
SetHotkey(text, text2, value, 205);
}
HelpWin32.UnregisterHotKey(Handle, 222);
StaticValue.IsCapture = false;
break;
}
case "区域多选" when image_screen == null:
{
if (IniHelper.GetValue("快捷键", "翻译文本") != "请按下快捷键")
{
var value2 = IniHelper.GetValue("快捷键", "翻译文本");
var text3 = "None";
var text4 = "F9";
SetHotkey(text3, text4, value2, 205);
}
HelpWin32.UnregisterHotKey(Handle, 222);
StaticValue.IsCapture = false;
break;
}
case "区域多选":
minico.Visible = true;
thread = new Thread(ShowLoading);
thread.Start();
ts = new TimeSpan(DateTime.Now.Ticks);
getSubPics_ocr(image_screen, buildRects);
break;
case "取色":
{
if (IniHelper.GetValue("快捷键", "翻译文本") != "请按下快捷键")
{
var value3 = IniHelper.GetValue("快捷键", "翻译文本");
var text5 = "None";
var text6 = "F9";
SetHotkey(text5, text6, value3, 205);
}
HelpWin32.UnregisterHotKey(Handle, 222);
StaticValue.IsCapture = false;
CommonHelper.ShowHelpMsg("已复制颜色");
break;
}
default:
{
if (image_screen == null)
{
if (IniHelper.GetValue("快捷键", "翻译文本") != "请按下快捷键")
{
var value4 = IniHelper.GetValue("快捷键", "翻译文本");
var text7 = "None";
var text8 = "F9";
SetHotkey(text7, text8, value4, 205);
}
HelpWin32.UnregisterHotKey(Handle, 222);
StaticValue.IsCapture = false;
}
else
{
if (modeFlag == "百度")
{
baidu_flags = "百度";
}
if (modeFlag == "拆分")
{
set_merge = false;
set_split = true;
}
if (modeFlag == "合并")
{
set_merge = true;
set_split = false;
}
if (modeFlag == "截图")
{
Clipboard.SetImage(image_screen);
if (IniHelper.GetValue("快捷键", "翻译文本") != "请按下快捷键")
{
var value5 = IniHelper.GetValue("快捷键", "翻译文本");
var text9 = "None";
var text10 = "F9";
SetHotkey(text9, text10, value5, 205);
}
HelpWin32.UnregisterHotKey(Handle, 222);
StaticValue.IsCapture = false;
if (IniHelper.GetValue("截图音效", "粘贴板") == "True")
{
PlaySong(IniHelper.GetValue("截图音效", "音效路径"));
}
CommonHelper.ShowHelpMsg("已复制截图");
}
else if (modeFlag == "自动保存" && IniHelper.GetValue("配置", "自动保存") == "True")
{
var filename = IniHelper.GetValue("配置", "截图位置") + "\\" + ReFileName(IniHelper.GetValue("配置", "截图位置"), "图片.Png");
image_screen.Save(filename, ImageFormat.Png);
StaticValue.IsCapture = false;
if (IniHelper.GetValue("截图音效", "自动保存") == "True")
{
PlaySong(IniHelper.GetValue("截图音效", "音效路径"));
}
CommonHelper.ShowHelpMsg("已保存图片");
}
else if (modeFlag == "多区域自动保存" && IniHelper.GetValue("配置", "自动保存") == "True")
{
getSubPics(image_screen, buildRects);
StaticValue.IsCapture = false;
if (IniHelper.GetValue("截图音效", "自动保存") == "True")
{
PlaySong(IniHelper.GetValue("截图音效", "音效路径"));
}
CommonHelper.ShowHelpMsg("已保存图片");
}
else if (modeFlag == "保存")
{
var saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "png图片(*.png)|*.png|jpg图片(*.jpg)|*.jpg|bmp图片(*.bmp)|*.bmp";
saveFileDialog.AddExtension = false;
saveFileDialog.FileName = string.Concat("tianruo_", DateTime.Now.Year.ToString(), "-", DateTime.Now.Month.ToString(), "-", DateTime.Now.Day.ToString(), "-", DateTime.Now.Ticks.ToString());
saveFileDialog.Title = "保存图片";
saveFileDialog.FilterIndex = 1;
saveFileDialog.RestoreDirectory = true;
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
var extension = Path.GetExtension(saveFileDialog.FileName);
if (extension.Equals(".jpg"))
{
image_screen.Save(saveFileDialog.FileName, ImageFormat.Jpeg);
}
if (extension.Equals(".png"))
{
image_screen.Save(saveFileDialog.FileName, ImageFormat.Png);
}
if (extension.Equals(".bmp"))
{
image_screen.Save(saveFileDialog.FileName, ImageFormat.Bmp);
}
}
if (IniHelper.GetValue("快捷键", "翻译文本") != "请按下快捷键")
{
var value6 = IniHelper.GetValue("快捷键", "翻译文本");
var text11 = "None";
var text12 = "F9";
SetHotkey(text11, text12, value6, 205);
}
HelpWin32.UnregisterHotKey(Handle, 222);
StaticValue.IsCapture = false;
}
else if (image_screen != null)
{
if (IniHelper.GetValue("工具栏", "分栏") == "True")
{
minico.Visible = true;
thread = new Thread(ShowLoading);
thread.Start();
ts = new TimeSpan(DateTime.Now.Ticks);
var image = image_screen;
var graphics = Graphics.FromImage(new Bitmap(image.Width, image.Height));
graphics.DrawImage(image, 0, 0, image.Width, image.Height);
graphics.Save();
graphics.Dispose();
((Bitmap)FindBoundingBoxFences((Bitmap)image)).Save("Data\\分栏预览图.jpg");
image.Dispose();
image_screen.Dispose();
}
else
{
minico.Visible = true;
thread = new Thread(ShowLoading);
thread.Start();
ts = new TimeSpan(DateTime.Now.Ticks);
var messageload = new Messageload();
messageload.ShowDialog();
if (messageload.DialogResult == DialogResult.OK)
{
esc_thread = new Thread(Main_OCR_Thread);
esc_thread.Start();
}
}
}
}
break;
}
}
}
catch
{
StaticValue.IsCapture = false;
}
}
public void Main_OCR_Thread()
{
if (ScanQRCode() != "")
{
typeset_txt = ScanQRCode();
RichBoxBody.Text = typeset_txt;
fmloading.FmlClose = "窗体已关闭";
Invoke(new OcrThread(Main_OCR_Thread_last));
return;
}
if (interface_flag == "搜狗")
{
SougouOCR();
fmloading.FmlClose = "窗体已关闭";
Invoke(new OcrThread(Main_OCR_Thread_last));
return;
}
if (interface_flag == "腾讯")
{
OCR_Tencent();
fmloading.FmlClose = "窗体已关闭";
Invoke(new OcrThread(Main_OCR_Thread_last));
return;
}
if (interface_flag == "有道")
{
OCR_youdao();
fmloading.FmlClose = "窗体已关闭";
Invoke(new OcrThread(Main_OCR_Thread_last));
return;
}
if (interface_flag == "公式")
{
OCR_Math();
fmloading.FmlClose = "窗体已关闭";
Invoke(new OcrThread(Main_OCR_Thread_last));
return;
}
if (interface_flag == "百度表格")
{
BdTableOCR();
fmloading.FmlClose = "窗体已关闭";
Invoke(new OcrThread(Main_OCR_Thread_table));
return;
}
if (interface_flag == "阿里表格")
{
OCR_ali_table();
fmloading.FmlClose = "窗体已关闭";
Invoke(new OcrThread(Main_OCR_Thread_table));
return;
}
if (interface_flag == "日语" || interface_flag == "中英" || interface_flag == "韩语")
{
OCR_baidu();
fmloading.FmlClose = "窗体已关闭";
Invoke(new OcrThread(Main_OCR_Thread_last));
}
if (interface_flag == "从左向右" || interface_flag == "从右向左")
{
shupai_Right_txt = "";
var image = image_screen;
var bitmap = new Bitmap(image.Width, image.Height);
var graphics = Graphics.FromImage(bitmap);
graphics.DrawImage(image, 0, 0, image.Width, image.Height);
graphics.Save();
graphics.Dispose();
image_ori = bitmap;
var image2 = new Image<Gray, byte>(bitmap);
var image3 = new Image<Gray, byte>((Bitmap)FindBundingBox(image2.ToBitmap()));
var draw = image3.Convert<Bgr, byte>();
var image4 = image3.Clone();
CvInvoke.Canny(image3, image4, 0.0, 0.0, 5, true);
select_image(image4, draw);
bitmap.Dispose();
image2.Dispose();
image3.Dispose();
}
image_screen.Dispose();
GC.Collect();
}
public void Main_OCR_Thread_last()
{
image_screen.Dispose();
StaticValue.IsCapture = false;
var text = typeset_txt;
text = check_str(text);
split_txt = check_str(split_txt);
if (!punctuation_has_punctuation(text))
{
text = split_txt;
}
if (contain_ch(text.Trim()))
{
text = Del_Space(text);
}
if (text != "")
{
RichBoxBody.Text = text;
}
StaticValue.v_Split = split_txt;
if (bool.Parse(IniHelper.GetValue("工具栏", "拆分")) || set_split)
{
set_split = false;
RichBoxBody.Text = split_txt;
}
if (bool.Parse(IniHelper.GetValue("工具栏", "合并")) || set_merge)
{
set_merge = false;
RichBoxBody.Text = text.Replace("\n", "").Replace("\r", "");
}
var timeSpan = new TimeSpan(DateTime.Now.Ticks);
var timeSpan2 = timeSpan.Subtract(ts).Duration();
var str = string.Concat(new[]
{
timeSpan2.Seconds.ToString(),
".",
Convert.ToInt32(timeSpan2.TotalMilliseconds).ToString(),
"秒"
});
if (RichBoxBody.Text != null)
{
p_note(RichBoxBody.Text);
StaticValue.v_note = pubnote;
if (fmNote.Created)
{
fmNote.TextNote = "";
}
}
if (StaticValue.v_topmost)
{
TopMost = true;
}
else
{
TopMost = false;
}
Text = "耗时:" + str;
minico.Visible = true;
if (interface_flag == "从右向左")
{
RichBoxBody.Text = shupai_Right_txt;
}
if (interface_flag == "从左向右")
{
RichBoxBody.Text = shupai_Left_txt;
}
Clipboard.SetDataObject(RichBoxBody.Text);
if (baidu_flags == "百度")
{
FormBorderStyle = FormBorderStyle.Sizable;
Size = new Size((int)font_base.Width * 23, (int)font_base.Height * 24);
Visible = false;
WindowState = FormWindowState.Minimized;
Show();
Process.Start("https://www.baidu.com/s?wd=" + RichBoxBody.Text);
baidu_flags = "";
if (IniHelper.GetValue("快捷键", "翻译文本") != "请按下快捷键")
{
var value = IniHelper.GetValue("快捷键", "翻译文本");
var text2 = "None";
var text3 = "F9";
SetHotkey(text2, text3, value, 205);
}
HelpWin32.UnregisterHotKey(Handle, 222);
return;
}
if (IniHelper.GetValue("配置", "识别弹窗") == "False")
{
FormBorderStyle = FormBorderStyle.Sizable;
Size = new Size((int)font_base.Width * 23, (int)font_base.Height * 24);
Visible = false;
CommonHelper.ShowHelpMsg(RichBoxBody.Text == "***该区域未发现文本***" ? "无文本" : "已识别");
if (IniHelper.GetValue("快捷键", "翻译文本") != "请按下快捷键")
{
var value2 = IniHelper.GetValue("快捷键", "翻译文本");
var text4 = "None";
var text5 = "F9";
SetHotkey(text4, text5, value2, 205);
}
HelpWin32.UnregisterHotKey(Handle, 222);
return;
}
FormBorderStyle = FormBorderStyle.Sizable;
Visible = true;
Show();
WindowState = FormWindowState.Normal;
Size = new Size(form_width, form_height);
HelpWin32.SetForegroundWindow(Handle);
StaticValue.v_googleTranslate_txt = RichBoxBody.Text;
if (bool.Parse(IniHelper.GetValue("工具栏", "翻译")))
{
try
{
auto_fla = "";
Invoke(new Translate(TransClick));
}
catch
{
//
}
}
if (bool.Parse(IniHelper.GetValue("工具栏", "检查")))
{
try
{
RichBoxBody.Find = "";
}
catch
{
//
}
}
if (IniHelper.GetValue("快捷键", "翻译文本") != "请按下快捷键")
{
var value3 = IniHelper.GetValue("快捷键", "翻译文本");
var text6 = "None";
var text7 = "F9";
SetHotkey(text6, text7, value3, 205);
}
HelpWin32.UnregisterHotKey(Handle, 222);
RichBoxBody.Refresh();
}
private void OCR_baidu_Ch_and_En_Click(object sender, EventArgs e)
{
OCR_foreach("中英");
}
private void OCR_baidu_Jap_Click(object sender, EventArgs e)
{
OCR_foreach("日语");
}
private void OCR_baidu_Kor_Click(object sender, EventArgs e)
{
OCR_foreach("韩语");
}
public string Get_GoogletHtml(string url)
{
var text = "";
var httpWebRequest = WebRequest.Create(url) as HttpWebRequest;
httpWebRequest.Method = "GET";
httpWebRequest.Timeout = 5000;
httpWebRequest.Headers.Add("Accept-Language: zh-CN;q=0.8,en-US;q=0.6,en;q=0.4");
httpWebRequest.Headers.Add("Accept-Encoding: gzip,deflate");
httpWebRequest.Headers.Add("Accept-Charset: utf-8");
httpWebRequest.ContentType = "application/x-www-form-urlencoded; charset=utf-8";
httpWebRequest.Host = "translate.google.cn";
httpWebRequest.Accept = "*/*";
httpWebRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)";
string result;
try
{
using (var httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse())
{
using (var streamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.UTF8))
{
text = streamReader.ReadToEnd();
streamReader.Close();
httpWebResponse.Close();
}
}
result = text;
}
catch
{
result = null;
}
return result;
}
public void OCR_baidu()
{
split_txt = "";
try
{
baidu_vip = CommonHelper.GetHtmlContent("https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=" + StaticValue.BD_API_ID + "&client_secret=" + StaticValue.BD_API_KEY);
if (string.IsNullOrEmpty(baidu_vip))
{
MessageBox.Show("请检查密钥输入是否正确!", "提醒");
}
else
{
var str = "CHN_ENG";
split_txt = "";
var img = image_screen;
var inArray = OcrHelper.ImgToBytes(img);
switch (interface_flag)
{
case "中英":
str = "CHN_ENG";
break;
case "日语":
str = "JAP";
break;
case "韩语":
str = "KOR";
break;
}
var s = "image=" + HttpUtility.UrlEncode(Convert.ToBase64String(inArray)) + "&language_type=" + str;
var url = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token=" +
((JObject) JsonConvert.DeserializeObject(baidu_vip))["access_token"];
var value = CommonHelper.PostStrData(url, s);
var jArray = JArray.Parse(((JObject)JsonConvert.DeserializeObject(value))["words_result"].ToString());
checked_txt(jArray, 1, "words");
}
}
catch
{
if (esc != "退出")
{
RichBoxBody.Text = "***该区域未发现文本或者密钥次数用尽***";
}
else
{
RichBoxBody.Text = "***该区域未发现文本***";
esc = "";
}
}
}
public string check_str(string text)
{
if (contain_ch(text.Trim()))
{
text = CommonHelper.EnPunctuation2Ch(text.Trim());
text = check_ch_en(text.Trim());
}
else
{
text = punctuation_ch_en(text.Trim());
if (contain(text, ".") && (contain(text, ",") || contain(text, "!") || contain(text, "(") || contain(text, ")") || contain(text, "'")))
{
text = punctuation_Del_space(text);
}
}
return text;
}
public static string punctuation_en_ch_x(string text)
{
var array = text.ToCharArray();
for (var i = 0; i < array.Length; i++)
{
var num = ".:;,?![]()".IndexOf(array[i]);
if (num != -1)
{
array[i] = "。:;,?!【】()"[num];
}
}
return new string(array);
}
public string OCR_sougou_SogouPost(string url, CookieContainer cookie, byte[] content)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.Method = "POST";
httpWebRequest.CookieContainer = cookie;
httpWebRequest.Timeout = 10000;
httpWebRequest.Referer = "http://pic.sogou.com/resource/pic/shitu_intro/index.html";
httpWebRequest.ContentType = "multipart/form-data; boundary=----WebKitFormBoundary1ZZDB9E4sro7pf0g";
httpWebRequest.Accept = "*/*";
httpWebRequest.Headers.Add("Origin: http://pic.sogou.com");
httpWebRequest.Headers.Add("Accept-Encoding: gzip,deflate");
httpWebRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)";
httpWebRequest.ServicePoint.Expect100Continue = false;
httpWebRequest.ProtocolVersion = new Version(1, 1);
httpWebRequest.ContentLength = content.Length;
var requestStream = httpWebRequest.GetRequestStream();
requestStream.Write(content, 0, content.Length);
requestStream.Close();
string result;
try
{
var text = "";
using (var httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse())
{
var stream = httpWebResponse.GetResponseStream();
if (httpWebResponse.ContentEncoding.ToLower().Contains("gzip"))
{
stream = new GZipStream(stream, CompressionMode.Decompress);
}
using (var streamReader = new StreamReader(stream, Encoding.UTF8))
{
text = streamReader.ReadToEnd();
streamReader.Close();
httpWebResponse.Close();
}
}
result = text;
}
catch
{
result = null;
}
return result;
}
public string OCR_sougou_SogouGet(string url, CookieContainer cookie, string refer)
{
var text = "";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.Method = "GET";
httpWebRequest.CookieContainer = cookie;
httpWebRequest.Referer = refer;
httpWebRequest.Timeout = 10000;
httpWebRequest.Accept = "application/json";
httpWebRequest.Headers.Add("X-Requested-With: XMLHttpRequest");
httpWebRequest.Headers.Add("Accept-Encoding: gzip,deflate");
httpWebRequest.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
httpWebRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)";
httpWebRequest.ServicePoint.Expect100Continue = false;
httpWebRequest.ProtocolVersion = new Version(1, 1);
string result;
try
{
using (var httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse())
{
var stream = httpWebResponse.GetResponseStream();
if (httpWebResponse.ContentEncoding.ToLower().Contains("gzip"))
{
stream = new GZipStream(stream, CompressionMode.Decompress);
}
using (var streamReader = new StreamReader(stream, Encoding.UTF8))
{
text = streamReader.ReadToEnd();
streamReader.Close();
httpWebResponse.Close();
}
}
result = text;
}
catch
{
result = null;
}
return result;
}
public string OCR_sougou_SogouOCR(Image img)
{
var cookie = new CookieContainer();
var url = "http://pic.sogou.com/pic/upload_pic.jsp";
var str = OCR_sougou_SogouPost(url, cookie, OCR_sougou_Content_Length(img));
var url2 = "http://pic.sogou.com/pic/ocr/ocrOnline.jsp?query=" + str;
var refer = "http://pic.sogou.com/resource/pic/shitu_intro/word_1.html?keyword=" + str;
return OCR_sougou_SogouGet(url2, cookie, refer);
}
public byte[] OCR_sougou_Content_Length(Image img)
{
var bytes = Encoding.UTF8.GetBytes("------WebKitFormBoundary1ZZDB9E4sro7pf0g\r\nContent-Disposition: form-data; name=\"pic_path\"; filename=\"test2018.jpg\"\r\nContent-Type: image/jpeg\r\n\r\n");
var array = OcrHelper.ImgToBytes(img);
var bytes2 = Encoding.UTF8.GetBytes("\r\n------WebKitFormBoundary1ZZDB9E4sro7pf0g--\r\n");
var array2 = new byte[bytes.Length + array.Length + bytes2.Length];
bytes.CopyTo(array2, 0);
array.CopyTo(array2, bytes.Length);
bytes2.CopyTo(array2, bytes.Length + array.Length);
return array2;
}
public void SougouOCR()
{
try
{
split_txt = "";
Image image = ZoomImage((Bitmap)image_screen, 120, 120);
//var value = OcrHelper.SgOcr(image);
var value = OcrHelper.SgBasicOpenOcr(image);
var jArray = JArray.Parse(((JObject)JsonConvert.DeserializeObject(value))["result"].ToString());
if (IniHelper.GetValue("工具栏", "分段") == "True")
{
checked_location_sougou(jArray, 2, "content", "frame");
}
else
{
checked_txt(jArray, 2, "content");
}
image.Dispose();
}
catch
{
if (esc != "退出")
{
RichBoxBody.Text = "***该区域未发现文本***";
}
else
{
RichBoxBody.Text = "***该区域未发现文本***";
esc = "";
}
}
}
public static byte[] MergeByte(byte[] a, byte[] b, byte[] c)
{
var array = new byte[a.Length + b.Length + c.Length];
a.CopyTo(array, 0);
b.CopyTo(array, a.Length);
c.CopyTo(array, a.Length + b.Length);
return array;
}
public static bool contain_punctuation(string str)
{
return Regex.IsMatch(str, "\\p{P}");
}
private void tray_help_Click(object sender, EventArgs e)
{
WindowState = FormWindowState.Minimized;
new FmHelp().Show();
}
public bool Is_punctuation(string text)
{
return ",;:,()、;".IndexOf(text) != -1;
}
public bool has_punctuation(string text)
{
return ",;,;、<>《》()-()".IndexOf(text) != -1;
}
public void checked_txt(JArray jarray, int lastlength, string words)
{
var num = 0;
for (var i = 0; i < jarray.Count; i++)
{
var length = JObject.Parse(jarray[i].ToString())[words].ToString().Length;
if (length > num)
{
num = length;
}
}
var str = "";
var text = "";
for (var j = 0; j < jarray.Count - 1; j++)
{
var jobject = JObject.Parse(jarray[j].ToString());
var array = jobject[words].ToString().ToCharArray();
var jobject2 = JObject.Parse(jarray[j + 1].ToString());
var array2 = jobject2[words].ToString().ToCharArray();
var length2 = jobject[words].ToString().Length;
var length3 = jobject2[words].ToString().Length;
if (Math.Abs(length2 - length3) <= 0)
{
if (split_paragraph(array[array.Length - lastlength].ToString()) && contain_en(array2[0].ToString()))
{
text = text + jobject[words].ToString().Trim() + "\r\n";
}
else if (split_paragraph(array[array.Length - lastlength].ToString()) && IsNum(array2[0].ToString()))
{
text = text + jobject[words].ToString().Trim() + "\r\n";
}
else if (split_paragraph(array[array.Length - lastlength].ToString()) && Is_punctuation(array2[0].ToString()))
{
text = text + jobject[words].ToString().Trim() + "\r\n";
}
else
{
text += jobject[words].ToString().Trim();
}
}
else if (split_paragraph(array[array.Length - lastlength].ToString()) && Math.Abs(length2 - length3) <= 1)
{
if (split_paragraph(array[array.Length - lastlength].ToString()) && contain_en(array2[0].ToString()))
{
text = text + jobject[words].ToString().Trim() + "\r\n";
}
else if (split_paragraph(array[array.Length - lastlength].ToString()) && IsNum(array2[0].ToString()))
{
text = text + jobject[words].ToString().Trim() + "\r\n";
}
else if (split_paragraph(array[array.Length - lastlength].ToString()) && Is_punctuation(array2[0].ToString()))
{
text = text + jobject[words].ToString().Trim() + "\r\n";
}
else
{
text += jobject[words].ToString().Trim();
}
}
else if (contain_ch(array[array.Length - lastlength].ToString()) && length2 <= num / 2)
{
text = text + jobject[words].ToString().Trim() + "\r\n";
}
else if (contain_ch(array[array.Length - lastlength].ToString()) && IsNum(array2[0].ToString()) && length3 - length2 < 4 && array2[1].ToString() == ".")
{
text = text + jobject[words].ToString().Trim() + "\r\n";
}
else if (contain_ch(array[array.Length - lastlength].ToString()) && contain_ch(array2[0].ToString()))
{
text += jobject[words].ToString().Trim();
}
else if (contain_en(array[array.Length - lastlength].ToString()) && contain_en(array2[0].ToString()))
{
text = text + jobject[words].ToString().Trim() + " ";
}
else if (contain_ch(array[array.Length - lastlength].ToString()) && contain_en(array2[0].ToString()))
{
text += jobject[words].ToString().Trim();
}
else if (contain_en(array[array.Length - lastlength].ToString()) && contain_ch(array2[0].ToString()))
{
text += jobject[words].ToString().Trim();
}
else if (contain_ch(array[array.Length - lastlength].ToString()) && Is_punctuation(array2[0].ToString()))
{
text += jobject[words].ToString().Trim();
}
else if (Is_punctuation(array[array.Length - lastlength].ToString()) && contain_ch(array2[0].ToString()))
{
text += jobject[words].ToString().Trim();
}
else if (Is_punctuation(array[array.Length - lastlength].ToString()) && contain_en(array2[0].ToString()))
{
text = text + jobject[words].ToString().Trim() + " ";
}
else if (contain_ch(array[array.Length - lastlength].ToString()) && IsNum(array2[0].ToString()))
{
text += jobject[words].ToString().Trim();
}
else if (IsNum(array[array.Length - lastlength].ToString()) && contain_ch(array2[0].ToString()))
{
text += jobject[words].ToString().Trim();
}
else if (IsNum(array[array.Length - lastlength].ToString()) && IsNum(array2[0].ToString()))
{
text += jobject[words].ToString().Trim();
}
else
{
text = text + jobject[words].ToString().Trim() + "\r\n";
}
if (has_punctuation(jobject[words].ToString()))
{
text += "\r\n";
}
str = str + jobject[words].ToString().Trim() + "\r\n";
}
split_txt = str + JObject.Parse(jarray[jarray.Count - 1].ToString())[words];
typeset_txt = text.Replace("\r\n\r\n", "\r\n") + JObject.Parse(jarray[jarray.Count - 1].ToString())[words];
}
private void OCR_foreach(string name)
{
var filePath = AppDomain.CurrentDomain.BaseDirectory + "Data\\config.ini";
switch (name)
{
case "韩语":
interface_flag = "韩语";
Refresh();
baidu.Text = "百度√";
kor.Text = "韩语√";
break;
case "日语":
interface_flag = "日语";
Refresh();
baidu.Text = "百度√";
jap.Text = "日语√";
break;
case "中英":
interface_flag = "中英";
Refresh();
baidu.Text = "百度√";
ch_en.Text = "中英√";
break;
case "搜狗":
interface_flag = "搜狗";
Refresh();
sougou.Text = "搜狗√";
break;
case "腾讯":
interface_flag = "腾讯";
Refresh();
tencent.Text = "腾讯√";
break;
case "有道":
interface_flag = "有道";
Refresh();
youdao.Text = "有道√";
break;
case "公式":
interface_flag = "公式";
Refresh();
Mathfuntion.Text = "公式√";
break;
case "百度表格":
interface_flag = "百度表格";
Refresh();
ocr_table.Text = "表格√";
baidu_table.Text = "百度√";
break;
case "阿里表格":
interface_flag = "阿里表格";
Refresh();
ocr_table.Text = "表格√";
ali_table.Text = "阿里√";
break;
case "从左向右" when !File.Exists("cvextern.dll"):
MessageBox.Show("请从蓝奏网盘中下载cvextern.dll大小约25m,点击确定自动弹出网页。\r\n将下载后的文件与 天若OCR文字识别.exe 这个文件放在一起。");
Process.Start("https://www.lanzous.com/i1ab3vg");
break;
case "从左向右":
interface_flag = "从左向右";
Refresh();
shupai.Text = "竖排√";
left_right.Text = "从左向右√";
break;
case "从右向左" when !File.Exists("cvextern.dll"):
MessageBox.Show("请从蓝奏网盘中下载cvextern.dll大小约25m,点击确定自动弹出网页。\r\n将下载后的文件与 天若OCR文字识别.exe 这个文件放在一起。");
Process.Start("https://www.lanzous.com/i1ab3vg");
return;
case "从右向左":
interface_flag = "从右向左";
Refresh();
shupai.Text = "竖排√";
righ_left.Text = "从右向左√";
break;
}
HelpWin32.IniFileHelper.SetValue("配置", "接口", interface_flag, filePath);
}
private void OCR_shupai_Click(object sender, EventArgs e)
{
}
private void OCR_write_Click(object sender, EventArgs e)
{
OCR_foreach("手写");
}
private void OCR_lefttoright_Click(object sender, EventArgs e)
{
OCR_foreach("从左向右");
}
private void OCR_righttoleft_Click(object sender, EventArgs e)
{
OCR_foreach("从右向左");
}
public void OCR_baidu_acc()
{
split_txt = "";
var text = "";
try
{
baidu_vip = CommonHelper.GetHtmlContent(string.Format("{0}?{1}", "https://aip.baidubce.com/oauth/2.0/token", "grant_type=client_credentials&client_id=" + StaticValue.BD_API_ID + "&client_secret=" + StaticValue.BD_API_KEY));
if (baidu_vip == "")
{
MessageBox.Show("请检查密钥输入是否正确!", "提醒");
}
else
{
split_txt = "";
var img = image_screen;
var inArray = OcrHelper.ImgToBytes(img);
var s = "image=" + HttpUtility.UrlEncode(Convert.ToBase64String(inArray));
var bytes = Encoding.UTF8.GetBytes(s);
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token=" + ((JObject)JsonConvert.DeserializeObject(baidu_vip))["access_token"]);
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
httpWebRequest.Timeout = 8000;
httpWebRequest.ReadWriteTimeout = 5000;
ServicePointManager.DefaultConnectionLimit = 512;
using (var requestStream = httpWebRequest.GetRequestStream())
{
requestStream.Write(bytes, 0, bytes.Length);
}
var responseStream = ((HttpWebResponse)httpWebRequest.GetResponse()).GetResponseStream();
var value = text = new StreamReader(responseStream, Encoding.GetEncoding("utf-8")).ReadToEnd();
responseStream.Close();
var jarray = JArray.Parse(((JObject)JsonConvert.DeserializeObject(value))["words_result"].ToString());
var text2 = "";
for (var i = 0; i < jarray.Count; i++)
{
var jobject = JObject.Parse(jarray[i].ToString());
text2 += jobject["words"].ToString().Replace("\r", "").Replace("\n", "");
}
shupai_Right_txt = shupai_Right_txt + text2 + "\r\n";
Thread.Sleep(600);
}
}
catch
{
MessageBox.Show(text, "提醒");
StaticValue.IsCapture = false;
esc = "退出";
fmloading.FmlClose = "窗体已关闭";
esc_thread.Abort();
}
}
public void OCR_Tencent_handwriting()
{
try
{
split_txt = "";
var image = image_screen;
if (image.Width > 90 && image.Height < 90)
{
var bitmap = new Bitmap(image.Width, 300);
var graphics = Graphics.FromImage(bitmap);
graphics.DrawImage(image, 5, 0, image.Width, image.Height);
graphics.Save();
graphics.Dispose();
image = new Bitmap(bitmap);
}
else if (image.Width <= 90 && image.Height >= 90)
{
var bitmap2 = new Bitmap(300, image.Height);
var graphics2 = Graphics.FromImage(bitmap2);
graphics2.DrawImage(image, 0, 5, image.Width, image.Height);
graphics2.Save();
graphics2.Dispose();
image = new Bitmap(bitmap2);
}
else if (image.Width < 90 && image.Height < 90)
{
var bitmap3 = new Bitmap(300, 300);
var graphics3 = Graphics.FromImage(bitmap3);
graphics3.DrawImage(image, 5, 5, image.Width, image.Height);
graphics3.Save();
graphics3.Dispose();
image = new Bitmap(bitmap3);
}
else
{
image = image_screen;
}
var url = "https://ai.qq.com/cgi-bin/appdemo_handwritingocr";
var value = OcrHelper.TxComm(image, url);
var jArray = JArray.Parse(((JObject)JsonConvert.DeserializeObject(value))["data"]["item_list"].ToString());
checked_txt(jArray, 1, "itemstring");
}
catch
{
if (esc != "退出")
{
RichBoxBody.Text = "***该区域未发现文本***";
}
else
{
RichBoxBody.Text = "***该区域未发现文本***";
esc = "";
}
}
}
public Image BoundingBox(Image<Gray, byte> src, Image<Bgr, byte> draw)
{
Image result;
using (var vectorOfVectorOfPoint = new VectorOfVectorOfPoint())
{
CvInvoke.FindContours(src, vectorOfVectorOfPoint, null, RetrType.List, ChainApproxMethod.ChainApproxSimple);
Image image = draw.ToBitmap();
var graphics = Graphics.FromImage(image);
var size = vectorOfVectorOfPoint.Size;
for (var i = 0; i < size; i++)
{
using (var vectorOfPoint = vectorOfVectorOfPoint[i])
{
var rectangle = CvInvoke.BoundingRectangle(vectorOfPoint);
var x = rectangle.Location.X;
var y = rectangle.Location.Y;
var width = rectangle.Size.Width;
var height = rectangle.Size.Height;
if (width > 5 || height > 5)
{
graphics.FillRectangle(Brushes.White, x, 0, width, image.Size.Height);
}
}
}
graphics.Dispose();
var bitmap = new Bitmap(image.Width + 2, image.Height + 2);
var graphics2 = Graphics.FromImage(bitmap);
graphics2.DrawImage(image, 1, 1, image.Width, image.Height);
graphics2.Save();
graphics2.Dispose();
result = bitmap;
}
return result;
}
public void select_image(Image<Gray, byte> src, Image<Bgr, byte> draw)
{
try
{
using (var vectorOfVectorOfPoint = new VectorOfVectorOfPoint())
{
CvInvoke.FindContours(src, vectorOfVectorOfPoint, null, RetrType.List, ChainApproxMethod.ChainApproxSimple);
var num = vectorOfVectorOfPoint.Size / 2;
imagelist_lenght = num;
bool_image_count(num);
if (!Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + "Data\\image_temp"))
{
Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + "Data\\image_temp");
}
OCR_baidu_a = "";
OCR_baidu_b = "";
OCR_baidu_c = "";
OCR_baidu_d = "";
OCR_baidu_e = "";
for (var i = 0; i < num; i++)
{
using (var vectorOfPoint = vectorOfVectorOfPoint[i])
{
var rectangle = CvInvoke.BoundingRectangle(vectorOfPoint);
if (rectangle.Size.Width > 1 && rectangle.Size.Height > 1)
{
var x = rectangle.Location.X;
var y = rectangle.Location.Y;
var width = rectangle.Size.Width;
var height = rectangle.Size.Height;
new Point(x, 0);
new Point(x, image_ori.Size.Height);
var srcRect = new Rectangle(x, 0, width, image_ori.Size.Height);
var bitmap = new Bitmap(width + 70, srcRect.Size.Height);
var graphics = Graphics.FromImage(bitmap);
graphics.FillRectangle(Brushes.White, 0, 0, bitmap.Size.Width, bitmap.Size.Height);
graphics.DrawImage(image_ori, 30, 0, srcRect, GraphicsUnit.Pixel);
var bitmap2 = Image.FromHbitmap(bitmap.GetHbitmap());
bitmap2.Save("Data\\image_temp\\" + i + ".jpg", ImageFormat.Jpeg);
bitmap2.Dispose();
bitmap.Dispose();
graphics.Dispose();
}
}
}
var messageload = new Messageload();
messageload.ShowDialog();
if (messageload.DialogResult == DialogResult.OK)
{
var array = new[]
{
new ManualResetEvent(false)
};
ThreadPool.QueueUserWorkItem(DoWork, array[0]);
}
}
}
catch
{
exit_thread();
}
}
public Image FindBundingBox(Bitmap bitmap)
{
var image = new Image<Bgr, byte>(bitmap);
var image2 = new Image<Gray, byte>(image.Width, image.Height);
CvInvoke.CvtColor(image, image2, ColorConversion.Bgra2Gray);
var structuringElement = CvInvoke.GetStructuringElement(ElementShape.Rectangle, new Size(4, 4), new Point(1, 1));
CvInvoke.Erode(image2, image2, structuringElement, new Point(0, 2), 1, BorderType.Reflect101, default(MCvScalar));
CvInvoke.Threshold(image2, image2, 100.0, 255.0, (ThresholdType)9);
var image3 = new Image<Gray, byte>(image2.ToBitmap());
var draw = image3.Convert<Bgr, byte>();
var image4 = image3.Clone();
CvInvoke.Canny(image3, image4, 255.0, 255.0, 5, true);
return BoundingBox(image4, draw);
}
public void Captureimage(int width, Image gImage, string saveFilePath, Rectangle rect)
{
var bitmap = new Bitmap(width + 70, gImage.Size.Height);
var graphics = Graphics.FromImage(bitmap);
graphics.FillRectangle(Brushes.White, 0, 0, bitmap.Size.Width, bitmap.Size.Height);
graphics.DrawImage(gImage, 30, 0, rect, GraphicsUnit.Pixel);
var bitmap2 = Image.FromHbitmap(bitmap.GetHbitmap());
bitmap2.Save(saveFilePath, ImageFormat.Jpeg);
image_screen = bitmap2;
BaiduOcr();
bitmap2.Dispose();
bitmap.Dispose();
graphics.Dispose();
}
public void BaiduOcr()
{
split_txt = "";
try
{
var str = "CHN_ENG";
split_txt = "";
var image = image_screen;
var array = OcrHelper.ImgToBytes(image);
var data = "type=general_location&image=data" + HttpUtility.UrlEncode(":image/jpeg;base64," + Convert.ToBase64String(array)) + "&language_type=" + str;
var value = CommonHelper.PostStrData("http://ai.baidu.com/tech/ocr/general", data);
var jArray = JArray.Parse(((JObject)JsonConvert.DeserializeObject(value))["data"]["words_result"].ToString());
var text = "";
var words = new string[jArray.Count];
for (var i = 0; i < jArray.Count; i++)
{
var jObject = JObject.Parse(jArray[i].ToString());
text += jObject["words"].ToString().Replace("\r", "").Replace("\n", "");
words[jArray.Count - 1 - i] = jObject["words"].ToString().Replace("\r", "").Replace("\n", "");
}
var text2 = "";
foreach (var t in words)
{
text2 += t;
}
shupai_Right_txt = (shupai_Right_txt + text + "\r\n").Replace("\r\n\r\n", "");
shupai_Left_txt = text2.Replace("\r\n\r\n", "");
MessageBox.Show(shupai_Left_txt);
Thread.Sleep(10);
}
catch
{
}
}
public bool split_paragraph(string text)
{
return "。?!?!:".IndexOf(text, StringComparison.Ordinal) != -1;
}
public void baidu_image_a(object objEvent)
{
try
{
for (var i = 0; i < image_num[0]; i++)
{
Stream stream = File.Open("Data\\image_temp\\" + i + ".jpg", FileMode.Open);
OcrBdUseA(Image.FromStream(stream));
stream.Close();
}
((ManualResetEvent)objEvent).Set();
}
catch
{
exit_thread();
}
}
public void baidu_image_b(object objEvent)
{
try
{
for (var i = image_num[0]; i < image_num[1]; i++)
{
Stream stream = File.Open("Data\\image_temp\\" + i + ".jpg", FileMode.Open);
OcrBdUseB(Image.FromStream(stream));
stream.Close();
}
((ManualResetEvent)objEvent).Set();
}
catch
{
exit_thread();
}
}
private void DoWork(object state)
{
var array = new ManualResetEvent[5];
array[0] = new ManualResetEvent(false);
ThreadPool.QueueUserWorkItem(baidu_image_a, array[0]);
array[1] = new ManualResetEvent(false);
ThreadPool.QueueUserWorkItem(baidu_image_b, array[1]);
array[2] = new ManualResetEvent(false);
ThreadPool.QueueUserWorkItem(BdImageC, array[2]);
array[3] = new ManualResetEvent(false);
ThreadPool.QueueUserWorkItem(BdImageD, array[3]);
array[4] = new ManualResetEvent(false);
ThreadPool.QueueUserWorkItem(BdImageE, array[4]);
WaitHandle[] waitHandles = array;
WaitHandle.WaitAll(waitHandles);
shupai_Right_txt = string.Concat(OCR_baidu_a, OCR_baidu_b, OCR_baidu_c, OCR_baidu_d, OCR_baidu_e).Replace("\r\n\r\n", "");
var text = shupai_Right_txt.TrimEnd('\n').TrimEnd('\r').TrimEnd('\n');
if (text.Split(Environment.NewLine.ToCharArray()).Length > 1)
{
var array2 = text.Split(new[]
{
"\r\n"
}, StringSplitOptions.None);
var str = "";
for (var i = 0; i < array2.Length; i++)
{
str = str + array2[array2.Length - i - 1].Replace("\r", "").Replace("\n", "") + "\r\n";
}
shupai_Left_txt = str;
}
fmloading.FmlClose = "窗体已关闭";
Invoke(new OcrThread(Main_OCR_Thread_last));
try
{
DeleteFile("Data\\image_temp");
}
catch
{
exit_thread();
}
image_ori.Dispose();
}
public void OcrBdUseB(Image image)
{
try
{
var str = "CHN_ENG";
var array = OcrHelper.ImgToBytes(image);
var data = "type=general_location&image=data" + HttpUtility.UrlEncode(":image/jpeg;base64," + Convert.ToBase64String(array)) + "&language_type=" + str;
var url = "http://ai.baidu.com/aidemo";
var referer = "http://ai.baidu.com/tech/ocr/general";
var value = CommonHelper.PostStrData(url, data, "", referer);
var jArray = JArray.Parse(((JObject)JsonConvert.DeserializeObject(value))["data"]["words_result"].ToString());
var text = "";
var array2 = new string[jArray.Count];
for (var i = 0; i < jArray.Count; i++)
{
var jObject = JObject.Parse(jArray[i].ToString());
text += jObject["words"].ToString().Replace("\r", "").Replace("\n", "");
array2[jArray.Count - 1 - i] = jObject["words"].ToString().Replace("\r", "").Replace("\n", "");
}
OCR_baidu_b = (OCR_baidu_b + text + "\r\n").Replace("\r\n\r\n", "");
Thread.Sleep(10);
}
catch(Exception)
{
//
}
}
public void OcrBdUseA(Image image)
{
try
{
var str = "CHN_ENG";
var array = OcrHelper.ImgToBytes(image);
var data = "type=general_location&image=data" + HttpUtility.UrlEncode(":image/jpeg;base64," + Convert.ToBase64String(array)) + "&language_type=" + str;
var bytes = Encoding.UTF8.GetBytes(data);
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://ai.baidu.com/tech/ocr/general");
httpWebRequest.CookieContainer = new CookieContainer();
httpWebRequest.GetResponse().Close();
var url = "http://ai.baidu.com/aidemo";
var referer = "http://ai.baidu.com/tech/ocr/general";
var value = CommonHelper.PostStrData(url, data, "", referer);
var jArray = JArray.Parse(((JObject)JsonConvert.DeserializeObject(value))["data"]["words_result"].ToString());
var text = "";
var array2 = new string[jArray.Count];
for (var i = 0; i < jArray.Count; i++)
{
var jObject = JObject.Parse(jArray[i].ToString());
text += jObject["words"].ToString().Replace("\r", "").Replace("\n", "");
array2[jArray.Count - 1 - i] = jObject["words"].ToString().Replace("\r", "").Replace("\n", "");
}
OCR_baidu_a = (OCR_baidu_a + text + "\r\n").Replace("\r\n\r\n", "");
Thread.Sleep(10);
}
catch (Exception)
{
//
}
}
public void DeleteFile(string path)
{
if (File.GetAttributes(path) == FileAttributes.Directory)
{
Directory.Delete(path, true);
return;
}
File.Delete(path);
}
public void OCR_baidu_image(Image image, string strImage)
{
try
{
var str = "CHN_ENG";
var array = OcrHelper.ImgToBytes(image);
var data = "type=general_location&image=data" + HttpUtility.UrlEncode(":image/jpeg;base64," + Convert.ToBase64String(array)) + "&language_type=" + str;
var url = "http://ai.baidu.com/aidemo";
var referer = "http://ai.baidu.com/tech/ocr/general";
var value = CommonHelper.PostStrData(url, data, "", referer);
var jArray = JArray.Parse(((JObject)JsonConvert.DeserializeObject(value))["data"]["words_result"].ToString());
var text = "";
var array2 = new string[jArray.Count];
for (var i = 0; i < jArray.Count; i++)
{
var jObject = JObject.Parse(jArray[i].ToString());
text += jObject["words"].ToString().Replace("\r", "").Replace("\n", "");
array2[jArray.Count - 1 - i] = jObject["words"].ToString().Replace("\r", "").Replace("\n", "");
}
Thread.Sleep(10);
}
catch (Exception)
{
//
}
}
public void OcrBdUseE(Image image)
{
try
{
var str = "CHN_ENG";
var array = OcrHelper.ImgToBytes(image);
var data = "type=general_location&image=data" + HttpUtility.UrlEncode(":image/jpeg;base64," + Convert.ToBase64String(array)) + "&language_type=" + str;
var url = "http://ai.baidu.com/aidemo";
var referer = "http://ai.baidu.com/tech/ocr/general";
var value = CommonHelper.PostStrData(url, data, "", referer);
var jArray = JArray.Parse(((JObject)JsonConvert.DeserializeObject(value))["data"]["words_result"].ToString());
var text = "";
var array2 = new string[jArray.Count];
for (var i = 0; i < jArray.Count; i++)
{
var jObject = JObject.Parse(jArray[i].ToString());
text += jObject["words"].ToString().Replace("\r", "").Replace("\n", "");
array2[jArray.Count - 1 - i] = jObject["words"].ToString().Replace("\r", "").Replace("\n", "");
}
OCR_baidu_e = (OCR_baidu_e + text + "\r\n").Replace("\r\n\r\n", "");
Thread.Sleep(10);
}
catch
{
//
}
}
public void OcrBdUseD(Image image)
{
try
{
var str = "CHN_ENG";
var array = OcrHelper.ImgToBytes(image);
var data = "type=general_location&image=data" + HttpUtility.UrlEncode(":image/jpeg;base64," + Convert.ToBase64String(array)) + "&language_type=" + str;
var url = "http://ai.baidu.com/aidemo";
var referer = "http://ai.baidu.com/tech/ocr/general";
var value = CommonHelper.PostStrData(url, data, "", referer);
var jArray = JArray.Parse(((JObject)JsonConvert.DeserializeObject(value))["data"]["words_result"].ToString());
var text = "";
var array2 = new string[jArray.Count];
for (var i = 0; i < jArray.Count; i++)
{
var jObject = JObject.Parse(jArray[i].ToString());
text += jObject["words"].ToString().Replace("\r", "").Replace("\n", "");
array2[jArray.Count - 1 - i] = jObject["words"].ToString().Replace("\r", "").Replace("\n", "");
}
OCR_baidu_d = (OCR_baidu_d + text + "\r\n").Replace("\r\n\r\n", "");
Thread.Sleep(10);
}
catch
{
//
}
}
public void OcrBdUseC(Image image)
{
try
{
var str = "CHN_ENG";
var array = OcrHelper.ImgToBytes(image);
var data = "type=general_location&image=data" + HttpUtility.UrlEncode(":image/jpeg;base64," + Convert.ToBase64String(array)) + "&language_type=" + str;
var url = "http://ai.baidu.com/aidemo";
var referer = "http://ai.baidu.com/tech/ocr/general";
var value = CommonHelper.PostStrData(url, data, "", referer);
var jArray = JArray.Parse(((JObject)JsonConvert.DeserializeObject(value))["data"]["words_result"].ToString());
var text = "";
var array2 = new string[jArray.Count];
for (var i = 0; i < jArray.Count; i++)
{
var jObject = JObject.Parse(jArray[i].ToString());
text += jObject["words"].ToString().Replace("\r", "").Replace("\n", "");
array2[jArray.Count - 1 - i] = jObject["words"].ToString().Replace("\r", "").Replace("\n", "");
}
OCR_baidu_c = (OCR_baidu_c + text + "\r\n").Replace("\r\n\r\n", "");
Thread.Sleep(10);
}
catch
{
//
}
}
public void BdImageC(object objEvent)
{
try
{
for (var i = image_num[1]; i < image_num[2]; i++)
{
Stream stream = File.Open("Data\\image_temp\\" + i + ".jpg", FileMode.Open);
OcrBdUseC(Image.FromStream(stream));
stream.Close();
}
((ManualResetEvent)objEvent).Set();
}
catch
{
exit_thread();
}
}
public void BdImageD(object objEvent)
{
try
{
for (var i = image_num[2]; i < image_num[3]; i++)
{
Stream stream = File.Open("Data\\image_temp\\" + i + ".jpg", FileMode.Open);
OcrBdUseD(Image.FromStream(stream));
stream.Close();
}
((ManualResetEvent)objEvent).Set();
}
catch
{
exit_thread();
}
}
public void BdImageE(object objEvent)
{
try
{
for (var i = image_num[3]; i < image_num[4]; i++)
{
Stream stream = File.Open("Data\\image_temp\\" + i + ".jpg", FileMode.Open);
OcrBdUseE(Image.FromStream(stream));
stream.Close();
}
((ManualResetEvent)objEvent).Set();
}
catch
{
exit_thread();
}
}
public void bool_image_count(int num)
{
if (num >= 5)
{
image_num = new int[num];
if (num - num / 5 * 5 == 0)
{
image_num[0] = num / 5;
image_num[1] = num / 5 * 2;
image_num[2] = num / 5 * 3;
image_num[3] = num / 5 * 4;
image_num[4] = num;
}
if (num - num / 5 * 5 == 1)
{
image_num[0] = num / 5 + 1;
image_num[1] = num / 5 * 2;
image_num[2] = num / 5 * 3;
image_num[3] = num / 5 * 4;
image_num[4] = num;
}
if (num - num / 5 * 5 == 2)
{
image_num[0] = num / 5 + 1;
image_num[1] = num / 5 * 2 + 1;
image_num[2] = num / 5 * 3;
image_num[3] = num / 5 * 4;
image_num[4] = num;
}
if (num - num / 5 * 5 == 3)
{
image_num[0] = num / 5 + 1;
image_num[1] = num / 5 * 2 + 1;
image_num[2] = num / 5 * 3 + 1;
image_num[3] = num / 5 * 4;
image_num[4] = num;
}
if (num - num / 5 * 5 == 4)
{
image_num[0] = num / 5 + 1;
image_num[1] = num / 5 * 2 + 1;
image_num[2] = num / 5 * 3 + 1;
image_num[3] = num / 5 * 4 + 1;
image_num[4] = num;
}
}
if (num == 4)
{
image_num = new int[5];
image_num[0] = 1;
image_num[1] = 2;
image_num[2] = 3;
image_num[3] = 4;
image_num[4] = 0;
}
if (num == 3)
{
image_num = new int[5];
image_num[0] = 1;
image_num[1] = 2;
image_num[2] = 3;
image_num[3] = 0;
image_num[4] = 0;
}
if (num == 2)
{
image_num = new int[5];
image_num[0] = 1;
image_num[1] = 2;
image_num[2] = 0;
image_num[3] = 0;
image_num[4] = 0;
}
if (num == 1)
{
image_num = new int[5];
image_num[0] = 1;
image_num[1] = 0;
image_num[2] = 0;
image_num[3] = 0;
image_num[4] = 0;
}
if (num == 0)
{
image_num = new int[5];
image_num[0] = 0;
image_num[1] = 0;
image_num[2] = 0;
image_num[3] = 0;
image_num[4] = 0;
}
}
private void exit_thread()
{
try
{
StaticValue.IsCapture = false;
esc = "退出";
fmloading.FmlClose = "窗体已关闭";
esc_thread.Abort();
}
catch
{
//
}
FormBorderStyle = FormBorderStyle.Sizable;
Visible = true;
Show();
WindowState = FormWindowState.Normal;
if (IniHelper.GetValue("快捷键", "翻译文本") != "请按下快捷键")
{
var value = IniHelper.GetValue("快捷键", "翻译文本");
var text = "None";
var text2 = "F9";
SetHotkey(text, text2, value, 205);
}
HelpWin32.UnregisterHotKey(Handle, 222);
}
public void change_pinyin_Click(object sender, EventArgs e)
{
pinyin_flag = true;
TransClick();
}
private Bitmap ZoomImage(Bitmap bitmap1, int destHeight, int destWidth)
{
var num = (double)bitmap1.Width;
var num2 = (double)bitmap1.Height;
if (num < destHeight)
{
while (num < destHeight)
{
num2 *= 1.1;
num *= 1.1;
}
}
if (num2 < destWidth)
{
while (num2 < destWidth)
{
num2 *= 1.1;
num *= 1.1;
}
}
var width = (int)num;
var height = (int)num2;
var bitmap2 = new Bitmap(width, height);
var graphics = Graphics.FromImage(bitmap2);
graphics.DrawImage(bitmap1, 0, 0, width, height);
graphics.Save();
graphics.Dispose();
return new Bitmap(bitmap2);
}
public void 翻译文本()
{
if (IniHelper.GetValue("配置", "快速翻译") == "True")
{
var data = "";
try
{
trans_hotkey = GetTextFromClipboard();
if (IniHelper.GetValue("配置", "翻译接口") == "谷歌")
{
data = Translate_Google(trans_hotkey);
}
if (IniHelper.GetValue("配置", "翻译接口") == "百度")
{
data = TranslateBaidu(trans_hotkey);
}
if (IniHelper.GetValue("配置", "翻译接口") == "腾讯")
{
data = Translate_Tencent(trans_hotkey);
}
Clipboard.SetData(DataFormats.UnicodeText, data);
SendKeys.SendWait("^v");
return;
}
catch
{
Clipboard.SetData(DataFormats.UnicodeText, data);
SendKeys.SendWait("^v");
return;
}
}
SendKeys.SendWait("^c");
SendKeys.Flush();
RichBoxBody.Text = Clipboard.GetText();
TransClick();
FormBorderStyle = FormBorderStyle.Sizable;
Visible = true;
HelpWin32.SetForegroundWindow(StaticValue.mainHandle);
Show();
WindowState = FormWindowState.Normal;
if (IniHelper.GetValue("工具栏", "顶置") == "True")
{
TopMost = true;
return;
}
TopMost = false;
}
public Bitmap GetRect(Image pic, Rectangle rect)
{
var destRect = new Rectangle(0, 0, rect.Width, rect.Height);
var bitmap = new Bitmap(destRect.Width, destRect.Height);
var graphics = Graphics.FromImage(bitmap);
graphics.Clear(Color.FromArgb(0, 0, 0, 0));
graphics.DrawImage(pic, destRect, rect, GraphicsUnit.Pixel);
graphics.Dispose();
return bitmap;
}
private Bitmap[] getSubPics(Image buildPic, Rectangle[] buildRects)
{
var array = new Bitmap[buildRects.Length];
for (var i = 0; i < buildRects.Length; i++)
{
array[i] = GetRect(buildPic, buildRects[i]);
var filename = IniHelper.GetValue("配置", "截图位置") + "\\" + ReFileName(IniHelper.GetValue("配置", "截图位置"), "图片.Png");
array[i].Save(filename, ImageFormat.Png);
}
return array;
}
public bool Exist(bool[][] colors, int x, int y)
{
return x >= 0 && y >= 0 && x < colors.Length && y < colors[0].Length && colors[x][y];
}
public bool R_Exist(bool[][] colors, Rectangle rect)
{
if (rect.Right >= colors[0].Length || rect.Left < 0)
{
return false;
}
for (var i = 0; i < rect.Height; i++)
{
if (Exist(colors, rect.Top + i, rect.Right + 1))
{
return true;
}
}
return false;
}
public bool D_Exist(bool[][] colors, Rectangle rect)
{
if (rect.Bottom >= colors.Length || rect.Top < 0)
{
return false;
}
for (var i = 0; i < rect.Width; i++)
{
if (Exist(colors, rect.Bottom + 1, rect.Left + i))
{
return true;
}
}
return false;
}
public bool L_Exist(bool[][] colors, Rectangle rect)
{
if (rect.Right >= colors[0].Length || rect.Left < 0)
{
return false;
}
for (var i = 0; i < rect.Height; i++)
{
if (Exist(colors, rect.Top + i, rect.Left - 1))
{
return true;
}
}
return false;
}
public bool U_Exist(bool[][] colors, Rectangle rect)
{
if (rect.Bottom >= colors.Length || rect.Top < 0)
{
return false;
}
for (var i = 0; i < rect.Width; i++)
{
if (Exist(colors, rect.Top - 1, rect.Left + i))
{
return true;
}
}
return false;
}
private Bitmap[] getSubPics_ocr(Image buildPic, Rectangle[] buildRects)
{
var text = "";
var array = new Bitmap[buildRects.Length];
var text2 = "";
for (var i = 0; i < buildRects.Length; i++)
{
array[i] = GetRect(buildPic, buildRects[i]);
image_screen = array[i];
var messageload = new Messageload();
messageload.ShowDialog();
if (messageload.DialogResult == DialogResult.OK)
{
if (interface_flag == "搜狗")
{
SougouOCR();
}
if (interface_flag == "腾讯")
{
OCR_Tencent();
}
if (interface_flag == "有道")
{
OCR_youdao();
}
if (interface_flag == "日语" || interface_flag == "中英" || interface_flag == "韩语")
{
OCR_baidu();
}
messageload.Dispose();
}
if (IniHelper.GetValue("工具栏", "分栏") == "True")
{
if (paragraph)
{
text = text + "\r\n" + typeset_txt.Trim();
text2 = text2 + "\r\n" + split_txt.Trim() + "\r\n";
}
else
{
text += typeset_txt.Trim();
text2 = text2 + "\r\n" + split_txt.Trim() + "\r\n";
}
}
else if (paragraph)
{
text = text + "\r\n" + typeset_txt.Trim() + "\r\n";
text2 = text2 + "\r\n" + split_txt.Trim() + "\r\n";
}
else
{
text = text + typeset_txt.Trim() + "\r\n";
text2 = text2 + "\r\n" + split_txt.Trim() + "\r\n";
}
}
typeset_txt = text.Replace("\r\n\r\n", "\r\n");
split_txt = text2.Replace("\r\n\r\n", "\r\n");
fmloading.FmlClose = "窗体已关闭";
Invoke(new OcrThread(Main_OCR_Thread_last));
return array;
}
public Image BoundingBox_fences(Image<Gray, byte> src, Image<Bgr, byte> draw)
{
Image result;
using (var vectorOfVectorOfPoint = new VectorOfVectorOfPoint())
{
CvInvoke.FindContours(src, vectorOfVectorOfPoint, null, RetrType.List, ChainApproxMethod.ChainApproxSimple);
Image image = draw.ToBitmap();
var graphics = Graphics.FromImage(image);
var size = vectorOfVectorOfPoint.Size;
for (var i = 0; i < size; i++)
{
using (var vectorOfPoint = vectorOfVectorOfPoint[i])
{
var rectangle = CvInvoke.BoundingRectangle(vectorOfPoint);
var x = rectangle.Location.X;
var y = rectangle.Location.Y;
var width = rectangle.Size.Width;
var height = rectangle.Size.Height;
graphics.FillRectangle(Brushes.White, x, 0, width, draw.Height);
}
}
graphics.Dispose();
var bitmap = new Bitmap(image.Width + 2, image.Height + 2);
var graphics2 = Graphics.FromImage(bitmap);
graphics2.DrawImage(image, 1, 1, image.Width, image.Height);
graphics2.Save();
graphics2.Dispose();
image.Dispose();
src.Dispose();
result = bitmap;
}
return result;
}
public Image FindBoundingBoxFences(Bitmap bitmap)
{
var image = new Image<Bgr, byte>(bitmap);
var image2 = new Image<Gray, byte>(image.Width, image.Height);
CvInvoke.CvtColor(image, image2, ColorConversion.Bgra2Gray);
var structuringElement = CvInvoke.GetStructuringElement(ElementShape.Rectangle, new Size(6, 20), new Point(1, 1));
CvInvoke.Erode(image2, image2, structuringElement, new Point(0, 2), 1, BorderType.Reflect101, default(MCvScalar));
CvInvoke.Threshold(image2, image2, 100.0, 255.0, (ThresholdType)9);
var image3 = new Image<Gray, byte>(image2.ToBitmap());
var draw = image3.Convert<Bgr, byte>();
var image4 = image3.Clone();
CvInvoke.Canny(image3, image4, 255.0, 255.0, 5, true);
var image5 = BoundingBox_fences(image4, draw);
var image6 = new Image<Gray, byte>((Bitmap)image5);
BoundingBox_fences_Up(image6);
image.Dispose();
image2.Dispose();
image3.Dispose();
image6.Dispose();
return image5;
}
public void BoundingBox_fences_Up(Image<Gray, byte> src)
{
using (var vectorOfVectorOfPoint = new VectorOfVectorOfPoint())
{
CvInvoke.FindContours(src, vectorOfVectorOfPoint, null, RetrType.List, ChainApproxMethod.ChainApproxSimple);
var size = vectorOfVectorOfPoint.Size;
var array = new Rectangle[size];
for (var i = 0; i < size; i++)
{
using (var vectorOfPoint = vectorOfVectorOfPoint[i])
{
array[size - 1 - i] = CvInvoke.BoundingRectangle(vectorOfPoint);
}
}
getSubPics_ocr(image_screen, array);
}
}
public void checked_location_sougou(JArray jarray, int lastlength, string words, string location)
{
paragraph = false;
var num = 20000;
var num2 = 0;
foreach (var t in jarray)
{
var jObject = JObject.Parse(t.ToString());
var num3 = split_char_x(jObject[location][1].ToString()) - split_char_x(jObject[location][0].ToString());
if (num3 > num2)
{
num2 = num3;
}
var num4 = split_char_x(jObject[location][0].ToString());
if (num4 < num)
{
num = num4;
}
}
var jobject2 = JObject.Parse(jarray[0].ToString());
if (Math.Abs(split_char_x(jobject2[location][0].ToString()) - num) > 10)
{
paragraph = true;
}
var text = "";
var text2 = "";
for (var j = 0; j < jarray.Count; j++)
{
var jobject3 = JObject.Parse(jarray[j].ToString());
var array = jobject3[words].ToString().ToCharArray();
var jobject4 = JObject.Parse(jarray[j].ToString());
var flag = Math.Abs(split_char_x(jobject4[location][1].ToString()) - split_char_x(jobject4[location][0].ToString()) - num2) > 20;
var flag2 = Math.Abs(split_char_x(jobject4[location][0].ToString()) - num) > 10;
if (flag && flag2)
{
text = text.Trim() + "\r\n" + jobject4[words].ToString().Trim();
}
else if (IsNum(array[0].ToString()) && !contain_ch(array[1].ToString()) && flag)
{
text = text.Trim() + "\r\n" + jobject4[words].ToString().Trim() + "\r\n";
}
else
{
text += jobject4[words].ToString().Trim();
}
if (contain_en(array[array.Length - lastlength].ToString()))
{
text = text + jobject3[words].ToString().Trim() + " ";
}
text2 = text2 + jobject4[words].ToString().Trim() + "\r\n";
}
split_txt = text2.Replace("\r\n\r\n", "\r\n");
typeset_txt = text;
}
public int split_char_x(string splitChar)
{
return Convert.ToInt32(splitChar.Split(',')[0]);
}
private void tray_double_Click(object sender, EventArgs e)
{
HelpWin32.UnregisterHotKey(Handle, 205);
menu.Hide();
RichBoxBody.Hide = "";
RichBoxBody_T.Hide = "";
MainOCRQuickScreenShots();
}
public int en_count(string text)
{
return Regex.Matches(text, "\\s+").Count + 1;
}
public int ch_count(string str)
{
var num = 0;
var regex = new Regex("^[\\u4E00-\\u9FA5]{0,}$");
for (var i = 0; i < str.Length; i++)
{
if (regex.IsMatch(str[i].ToString()))
{
num++;
}
}
return num;
}
public void Trans_google_Click(object sender, EventArgs e)
{
Trans_foreach("谷歌");
}
public void Trans_baidu_Click(object sender, EventArgs e)
{
Trans_foreach("百度");
}
private void Trans_foreach(string name)
{
if (name == "百度")
{
trans_baidu.Text = "百度√";
trans_google.Text = "谷歌";
trans_tencent.Text = "腾讯";
IniHelper.SetValue("配置", "翻译接口", "百度");
}
if (name == "谷歌")
{
trans_baidu.Text = "百度";
trans_google.Text = "谷歌√";
trans_tencent.Text = "腾讯";
IniHelper.SetValue("配置", "翻译接口", "谷歌");
}
if (name == "腾讯")
{
trans_google.Text = "谷歌";
trans_baidu.Text = "百度";
trans_tencent.Text = "腾讯√";
IniHelper.SetValue("配置", "翻译接口", "腾讯");
}
}
private string TranslateBaidu(string content)
{
var text = "";
try
{
new CookieContainer();
var text2 = "zh";
var text3 = "en";
if (StaticValue.ZH2EN)
{
if (ch_count(content.Trim()) > en_count(content.Trim()) || (en_count(content.Trim()) == 1 && ch_count(content.Trim()) == 1))
{
text2 = "zh";
text3 = "en";
}
else
{
text2 = "en";
text3 = "zh";
}
}
if (StaticValue.ZH2JP)
{
if (contain_jap(replaceStr(Del_ch(content.Trim()))))
{
text2 = "jp";
text3 = "zh";
}
else
{
text2 = "zh";
text3 = "jp";
}
}
if (StaticValue.ZH2KO)
{
if (contain_kor(content.Trim()))
{
text2 = "kor";
text3 = "zh";
}
else
{
text2 = "zh";
text3 = "kor";
}
}
// var html = CommonHelper.PostStrData("https://fanyi.baidu.com/basetrans",
// string.Concat("query=", HttpUtility.UrlEncode(Text.Trim()).Replace("+", "%20"), "&from=", text2,
// "&to=", text3));
var html = TranslateHelper.BdTrans(content.Trim(), text2, text3);
var jArray = JArray.Parse(((JObject)JsonConvert.DeserializeObject(html))["fanyi_list"].ToString());
foreach (var arr in jArray)
{
text = text + arr + "\r\n";
}
}
catch (Exception)
{
text = "[百度接口报错]:\r\n1.接口请求出现问题等待修复。";
}
return text;
}
public void Trans_tencent_Click(object sender, EventArgs e)
{
Trans_foreach("腾讯");
}
public string Content_Length(string text, string from, string to)
{
return string.Concat("&source=", from, "&target=", to, "&sourceText=", HttpUtility.UrlEncode(text)?.Replace("+", "%20"));
}
public string TencentPOST(string url, string content)
{
string result;
try
{
var referer = "https://fanyi.qq.com/";
result = CommonHelper.PostStrData(url, content, "", referer);
}
catch
{
result = "[腾讯接口报错]:\r\n请切换其它接口或再次尝试。";
}
return result;
}
private string Translate_Tencent(string strTrans)
{
var text = "";
try
{
var from = "zh";
var to = "en";
if (StaticValue.ZH2EN)
{
if (ch_count(strTrans.Trim()) > en_count(strTrans.Trim()) || (en_count(text.Trim()) == 1 && ch_count(text.Trim()) == 1))
{
from = "zh";
to = "en";
}
else
{
from = "en";
to = "zh";
}
}
if (StaticValue.ZH2JP)
{
if (contain_jap(replaceStr(Del_ch(strTrans.Trim()))))
{
from = "jp";
to = "zh";
}
else
{
from = "zh";
to = "jp";
}
}
if (StaticValue.ZH2KO)
{
if (contain_kor(strTrans.Trim()))
{
from = "kr";
to = "zh";
}
else
{
from = "zh";
to = "kr";
}
}
var jArray = JArray.Parse(((JObject)JsonConvert.DeserializeObject(TencentPOST("https://fanyi.qq.com/api/translate", Content_Length(strTrans, from, to))))["translate"]["records"].ToString());
foreach (var t in jArray)
{
var jObject = JObject.Parse(t.ToString());
text += jObject["targetText"].ToString();
}
}
catch (Exception)
{
text = "[腾讯接口报错]:\r\n1.接口请求出现问题等待修复。";
}
return text;
}
public void BdTableOCR()
{
typeset_txt = "[消息]:表格已下载!";
split_txt = "";
try
{
baidu_vip = CommonHelper.GetHtmlContent(string.Format("{0}?{1}", "https://aip.baidubce.com/oauth/2.0/token", "grant_type=client_credentials&client_id=" + StaticValue.BD_API_ID + "&client_secret=" + StaticValue.BD_API_KEY));
if (baidu_vip == "")
{
MessageBox.Show("请检查密钥输入是否正确!", "提醒");
}
else
{
split_txt = "";
var image = image_screen;
var array = OcrHelper.ImgToBytes(image);
var s = "image=" + HttpUtility.UrlEncode(Convert.ToBase64String(array));
var bytes = Encoding.UTF8.GetBytes(s);
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://aip.baidubce.com/rest/2.0/solution/v1/form_ocr/request?access_token=" + ((JObject)JsonConvert.DeserializeObject(baidu_vip))["access_token"]);
httpWebRequest.Proxy = null;
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.Timeout = 8000;
httpWebRequest.ReadWriteTimeout = 5000;
using (var requestStream = httpWebRequest.GetRequestStream())
{
requestStream.Write(bytes, 0, bytes.Length);
}
var responseStream = ((HttpWebResponse)httpWebRequest.GetResponse()).GetResponseStream();
var value = new StreamReader(responseStream, Encoding.GetEncoding("utf-8")).ReadToEnd();
responseStream.Close();
var postStr = "request_id=" + JObject.Parse(JArray.Parse(((JObject)JsonConvert.DeserializeObject(value))["result"].ToString())[0].ToString())["request_id"].ToString().Trim() + "&result_type=json";
var text = "";
while (!text.Contains("已完成"))
{
if (text.Contains("image recognize error"))
{
RichBoxBody.Text = "[消息]:未发现表格!";
break;
}
Thread.Sleep(120);
text = CommonHelper.PostStrData("https://aip.baidubce.com/rest/2.0/solution/v1/form_ocr/get_request_result?access_token=" + ((JObject)JsonConvert.DeserializeObject(baidu_vip))["access_token"], postStr);
}
if (!text.Contains("image recognize error"))
{
get_table(text);
}
}
}
catch
{
RichBoxBody.Text = "[消息]:免费百度密钥50次已经耗完!请更换自己的密钥继续使用!";
}
}
public void OCR_table_Click(object sender, EventArgs e)
{
OCR_foreach("表格");
}
private void get_table(string str)
{
var jArray = JArray.Parse(((JObject)JsonConvert.DeserializeObject(((JObject)JsonConvert.DeserializeObject(str))["result"]["result_data"].ToString().Replace("\\", "")))["forms"][0]["body"].ToString());
var array = new int[jArray.Count];
var array2 = new int[jArray.Count];
for (var i = 0; i < jArray.Count; i++)
{
var jObject = JObject.Parse(jArray[i].ToString());
var value = jObject["column"].ToString().Replace("[", "").Replace("]", "").Replace("\r", "").Replace("\n", "").Trim();
var value2 = jObject["row"].ToString().Replace("[", "").Replace("]", "").Replace("\r", "").Replace("\n", "").Trim();
array[i] = Convert.ToInt32(value);
array2[i] = Convert.ToInt32(value2);
}
var array3 = new string[array2.Max() + 1, array.Max() + 1];
for (var j = 0; j < jArray.Count; j++)
{
var jObject = JObject.Parse(jArray[j].ToString());
var value3 = jObject["column"].ToString().Replace("[", "").Replace("]", "").Replace("\r", "").Replace("\n", "").Trim();
var value4 = jObject["row"].ToString().Replace("[", "").Replace("]", "").Replace("\r", "").Replace("\n", "").Trim();
array[j] = Convert.ToInt32(value3);
array2[j] = Convert.ToInt32(value4);
var text = jObject["word"].ToString().Replace("[", "").Replace("]", "").Replace("\r", "").Replace("\n", "").Trim();
array3[Convert.ToInt32(value4), Convert.ToInt32(value3)] = text;
}
var graphics = CreateGraphics();
var array4 = new int[array.Max() + 1];
var num = 0;
var size = new SizeF(10f, 10f);
var num2 = Screen.PrimaryScreen.Bounds.Width / 4;
for (var k = 0; k < array3.GetLength(1); k++)
{
for (var l = 0; l < array3.GetLength(0); l++)
{
size = graphics.MeasureString(array3[l, k], new Font("宋体", 12f));
if (num < (int)size.Width)
{
num = (int)size.Width;
}
if (num > num2)
{
num = num2;
}
}
array4[k] = num;
num = 0;
}
graphics.Dispose();
setClipboard_Table(array3, array4);
}
public void Main_OCR_Thread_table()
{
ailibaba = new AliTable();
var timeSpan = new TimeSpan(DateTime.Now.Ticks);
var timeSpan2 = timeSpan.Subtract(ts).Duration();
var str = string.Concat(new[]
{
timeSpan2.Seconds.ToString(),
".",
Convert.ToInt32(timeSpan2.TotalMilliseconds).ToString(),
"秒"
});
if (StaticValue.v_topmost)
{
TopMost = true;
}
else
{
TopMost = false;
}
Text = "耗时:" + str;
if (interface_flag == "百度表格")
{
var dataObject = new DataObject();
dataObject.SetData(DataFormats.Rtf, RichBoxBody.Rtx1Rtf);
dataObject.SetData(DataFormats.UnicodeText, RichBoxBody.Text);
RichBoxBody.Text = "[消息]:表格已复制到粘贴板!";
Clipboard.SetDataObject(dataObject);
}
image_screen.Dispose();
GC.Collect();
StaticValue.IsCapture = false;
FormBorderStyle = FormBorderStyle.Sizable;
Visible = true;
Show();
WindowState = FormWindowState.Normal;
Size = new Size(form_width, form_height);
HelpWin32.SetForegroundWindow(Handle);
if (interface_flag == "阿里表格")
{
if (split_txt == "弹出cookie")
{
split_txt = "";
ailibaba.TopMost = true;
ailibaba.getcookie = "";
IniHelper.SetValue("特殊", "ali_cookie", ailibaba.getcookie);
ailibaba.ShowDialog();
HelpWin32.SetForegroundWindow(ailibaba.Handle);
return;
}
Clipboard.SetDataObject(typeset_txt);
CopyHtmlToClipBoard(typeset_txt);
}
}
private void setClipboard_Table(string[,] wordo, int[] cc)
{
var str = "{\\rtf1\\ansi\\ansicpg936\\deff0\\deflang1033\\deflangfe2052{\\fonttbl{\\f0\\fnil\\fprq2\\fcharset134";
str += "\\'cb\\'ce\\'cc\\'e5;}{\\f1\\fnil\\fcharset134 \\'cb\\'ce\\'cc\\'e5;}}\\viewkind4\\uc1\\trowd\\trgaph108\\trleft-108";
str += "\\trbrdrt\\brdrs\\brdrw10 \\trbrdrl\\brdrs\\brdrw10 \\trbrdrb\\brdrs\\brdrw10 \\trbrdrb\\brdrs\\brdrw10 ";
var num = 0;
for (var i = 1; i <= cc.Length; i++)
{
num += cc[i - 1] * 17;
str = str + "\\clbrdrt\\brdrw15\\brdrs\\clbrdrl\\brdrw15\\brdrs\\clbrdrb\\brdrw15\\brdrs\\clbrdrr\\brdrw15\\brdrs \\cellx" + num;
}
var text = "";
var str2 = "\\pard\\intbl\\kerning2\\f0";
var str3 = "\\row\\pard\\lang2052\\kerning0\\f1\\fs18\\par}";
for (var j = 0; j < wordo.GetLength(0); j++)
{
for (var k = 0; k < wordo.GetLength(1); k++)
{
if (k == 0)
{
text = text + "\\fs24 " + wordo[j, k];
}
else
{
text = text + "\\cell " + wordo[j, k];
}
}
if (j != wordo.GetLength(0) - 1)
{
text += "\\row\\intbl";
}
}
RichBoxBody.Rtx1Rtf = str + str2 + text + str3;
}
public string Translate_Googlekey(string text)
{
var text2 = "";
try
{
var text3 = "zh-CN";
var text4 = "en";
if (StaticValue.ZH2EN)
{
if (ch_count(typeset_txt.Trim()) > en_count(typeset_txt.Trim()))
{
text3 = "zh-CN";
text4 = "en";
}
else
{
text3 = "en";
text4 = "zh-CN";
}
}
else if (StaticValue.ZH2JP)
{
if (contain_jap(replaceStr(Del_ch(typeset_txt.Trim()))))
{
text3 = "ja";
text4 = "zh-CN";
}
else
{
text3 = "zh-CN";
text4 = "ja";
}
}
else if(StaticValue.ZH2KO)
{
if (contain_kor(typeset_txt.Trim()))
{
text3 = "ko";
text4 = "zh-CN";
}
else
{
text3 = "zh-CN";
text4 = "ko";
}
}
var postData = string.Concat("client=gtx&sl=", text3, "&tl=", text4, "&dt=t&q=", HttpUtility.UrlEncode(text).Replace("+", "%20"));
var jArray = (JArray)JsonConvert.DeserializeObject(CommonHelper.PostStrData("https://translate.google.cn/translate_a/single", postData));
var count = ((JArray)jArray[0]).Count;
for (var i = 0; i < count; i++)
{
text2 += jArray[0][i][0].ToString();
}
}
catch (Exception)
{
text2 = "[谷歌接口报错]:\r\n出现这个提示文字,表示您当前的网络不适合使用谷歌接口。\r\n请放弃使用谷歌接口,腾讯,百度接口都可以正常使用。";
}
return text2;
}
public void OCR_baidutable_Click(object sender, EventArgs e)
{
OCR_foreach("百度表格");
}
public void OCR_ailitable_Click(object sender, EventArgs e)
{
OCR_foreach("阿里表格");
}
private new void Refresh()
{
sougou.Text = "搜狗";
tencent.Text = "腾讯";
baidu.Text = "百度";
youdao.Text = "有道";
shupai.Text = "竖排";
ocr_table.Text = "表格";
ch_en.Text = "中英";
jap.Text = "日语";
kor.Text = "韩语";
left_right.Text = "从左向右";
righ_left.Text = "从右向左";
baidu_table.Text = "百度";
ali_table.Text = "阿里";
Mathfuntion.Text = "公式";
}
public static byte[] ImageToByteArray(Image img)
{
return (byte[])new ImageConverter().ConvertTo(img, typeof(byte[]));
}
public static Stream BytesToStream(byte[] bytes)
{
return new MemoryStream(bytes);
}
public void OCR_ali_table()
{
var text = "";
split_txt = "";
try
{
var value = IniHelper.GetValue("特殊", "ali_cookie");
var stream = BytesToStream(ImageToByteArray(BWPic((Bitmap)image_screen)));
var str = Convert.ToBase64String(new BinaryReader(stream).ReadBytes(Convert.ToInt32(stream.Length)));
stream.Close();
var postStr = "{\n\t\"image\": \"" + str + "\",\n\t\"configure\": \"{\\\"format\\\":\\\"html\\\", \\\"finance\\\":false}\"\n}";
var url = "https://predict-pai.data.aliyun.com/dp_experience_mall/ocr/ocr_table_parse";
text = CommonHelper.PostStrData(url, postStr, value);
typeset_txt = ((JObject)JsonConvert.DeserializeObject(CommonHelper.PostStrData(url, postStr, value)))["tables"].ToString().Replace("table tr td { border: 1px solid blue }", "table tr td {border: 0.5px black solid }").Replace("table { border: 1px solid blue }", "table { border: 0.5px black solid; border-collapse : collapse}\r\n");
RichBoxBody.Text = "[消息]:表格已复制到粘贴板!";
}
catch
{
RichBoxBody.Text = "[消息]:阿里表格识别出错!";
if (text.Contains("NEED_LOGIN"))
{
split_txt = "弹出cookie";
}
}
}
public Bitmap BWPic(Bitmap mybm)
{
var bitmap = new Bitmap(mybm.Width, mybm.Height);
for (var i = 0; i < mybm.Width; i++)
{
for (var j = 0; j < mybm.Height; j++)
{
var pixel = mybm.GetPixel(i, j);
var num = (pixel.R + pixel.G + pixel.B) / 3;
bitmap.SetPixel(i, j, Color.FromArgb(num, num, num));
}
}
return bitmap;
}
public void CopyHtmlToClipBoard(string html)
{
var utf = Encoding.UTF8;
var format = "Version:0.9\r\nStartHTML:{0:000000}\r\nEndHTML:{1:000000}\r\nStartFragment:{2:000000}\r\nEndFragment:{3:000000}\r\n";
var text = "<html>\r\n<head>\r\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=" + utf.WebName + "\">\r\n<title>HTML clipboard</title>\r\n</head>\r\n<body>\r\n<!--StartFragment-->";
var text2 = "<!--EndFragment-->\r\n</body>\r\n</html>\r\n";
var s = string.Format(format, 0, 0, 0, 0);
var byteCount = utf.GetByteCount(s);
var byteCount2 = utf.GetByteCount(text);
var byteCount3 = utf.GetByteCount(html);
var byteCount4 = utf.GetByteCount(text2);
var s2 = string.Format(format, byteCount, byteCount + byteCount2 + byteCount3 + byteCount4, byteCount + byteCount2, byteCount + byteCount2 + byteCount3) + text + html + text2;
var dataObject = new DataObject();
dataObject.SetData(DataFormats.Html, new MemoryStream(utf.GetBytes(s2)));
var data = new HtmlToText().Convert(html);
dataObject.SetData(DataFormats.Text, data);
Clipboard.SetDataObject(dataObject);
}
//
// public static string Encript(string functionName, object[] pams)
// {
// var code = File.ReadAllText("sign.js");
// ScriptControlClass scriptControlClass = new ScriptControlClass();
// ((IScriptControl)scriptControlClass).Language = "javascript";
// ((IScriptControl)scriptControlClass).AddCode(code);
// return ((IScriptControl)scriptControlClass).Run(functionName, ref pams).ToString();
// }
//
// private object ExecuteScript(string sExpression, string sCode)
// {
// ScriptControl scriptControl = new ScriptControlClass();
// scriptControl.UseSafeSubset = true;
// scriptControl.Language = "JScript";
// scriptControl.AddCode(sCode);
// try
// {
// return scriptControl.Eval(sExpression);
// }
// catch (Exception)
// {
// }
// return null;
// }
private void OCR_Mathfuntion_Click(object sender, EventArgs e)
{
OCR_foreach("公式");
}
public void OCR_Math()
{
split_txt = "";
try
{
var img = image_screen;
var inArray = OcrHelper.ImgToBytes(img);
var s = "{\t\"formats\": [\"latex_styled\", \"text\"],\t\"metadata\": {\t\t\"count\": 0,\t\t\"platform\": \"windows 10\",\t\t\"skip_recrop\": true,\t\t\"user_id\": \"\",\t\t\"version\": \"[email protected]\"\t},\t\"ocr\": [\"text\", \"math\"],\t\"src\": \"data:image/jpeg;base64," + Convert.ToBase64String(inArray) + "\"}";
var bytes = Encoding.UTF8.GetBytes(s);
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://api.mathpix.com/v3/latex");
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "application/json";
httpWebRequest.Timeout = 8000;
httpWebRequest.ReadWriteTimeout = 5000;
httpWebRequest.Headers.Add("app_id: mathpix_chrome");
httpWebRequest.Headers.Add("app_key: 85948264c5d443573286752fbe8df361");
using (var requestStream = httpWebRequest.GetRequestStream())
{
requestStream.Write(bytes, 0, bytes.Length);
}
var responseStream = ((HttpWebResponse)httpWebRequest.GetResponse()).GetResponseStream();
var value = new StreamReader(responseStream, Encoding.GetEncoding("utf-8")).ReadToEnd();
responseStream.Close();
var text = "$" + ((JObject)JsonConvert.DeserializeObject(value))["latex_styled"] + "$";
split_txt = text;
typeset_txt = text;
}
catch
{
if (esc != "退出")
{
RichBoxBody.Text = "***该区域未发现文本或者密钥次数用尽***";
}
else
{
RichBoxBody.Text = "***该区域未发现文本***";
esc = "";
}
}
}
public string interface_flag;
public string language;
public string split_txt;
public string note;
public string spacechar;
public string richTextBox1_note;
public string transtalate_fla;
public FmLoading fmloading;
public Thread thread;
public MenuItem Set;
public string googleTranslate_txt;
public int num_ok;
public bool bolActive;
public bool tencent_vip_f;
public string auto_fla;
public string baidu_vip;
public string htmltxt;
public static string TipText;
public bool speaking;
public static bool speak_copy;
public string speak_copyb;
public string speak_stop;
public byte[] ttsData;
public string[] pubnote;
public FmNote fmNote;
public Image image_screen;
public int voice_count;
public int form_width;
public int form_height;
public bool change_QQ_screenshot;
private FmFlags fmflags;
public string trans_hotkey;
public TimeSpan ts;
public Timer esc_timer;
public Thread esc_thread;
public string esc;
private string languagle_flag;
public static string GetTkkJS;
public string typeset_txt;
public string baidu_flags;
public bool 截图排斥;
private Image image_ori;
public string shupai_Right_txt;
private AutoResetEvent are;
public string baiducookies;
public string shupai_Left_txt;
public Image[] image_arr;
public string OCR_baidu_a;
public string OCR_baidu_b;
public List<Image> imgArr;
public List<Image> imagelist;
public int imagelist_lenght;
public string OCR_baidu_d;
public string OCR_baidu_c;
public string OCR_baidu_e;
public int[] image_num;
public string Proxy_flag;
public string Proxy_url;
public string Proxy_port;
public string Proxy_name;
public string Proxy_password;
public bool pinyin_flag;
public bool set_split;
public bool set_merge;
public bool tranclick;
public string myjsTextBox;
private string flags_ocrorder;
public int first_line;
public bool paragraph;
private WebBrowser webBrowser;
public string tencent_cookie;
private AliTable ailibaba;
public delegate void Translate();
public delegate void OcrThread();
public delegate int Dllinput(string command);
public class AutoClosedMsgBox
{
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll")]
private static extern bool EndDialog(IntPtr hDlg, int nResult);
[DllImport("user32.dll")]
private static extern int MessageBoxTimeout(IntPtr hwnd, string txt, string caption, int wtype, int wlange, int dwtimeout);
public static int Show(string text, string caption, int milliseconds, MsgBoxStyle style)
{
return MessageBoxTimeout(IntPtr.Zero, text, caption, (int)style, 0, milliseconds);
}
public static int Show(string text, string caption, int milliseconds, int style)
{
return MessageBoxTimeout(IntPtr.Zero, text, caption, style, 0, milliseconds);
}
private const int WM_CLOSE = 16;
}
public enum MsgBoxStyle
{
OK,
OKCancel,
AbortRetryIgnore,
YesNoCancel,
YesNo,
RetryCancel,
CancelRetryContinue,
RedCritical_OK = 16,
RedCritical_OKCancel,
RedCritical_AbortRetryIgnore,
RedCritical_YesNoCancel,
RedCritical_YesNo,
RedCritical_RetryCancel,
RedCritical_CancelRetryContinue,
BlueQuestion_OK = 32,
BlueQuestion_OKCancel,
BlueQuestion_AbortRetryIgnore,
BlueQuestion_YesNoCancel,
BlueQuestion_YesNo,
BlueQuestion_RetryCancel,
BlueQuestion_CancelRetryContinue,
YellowAlert_OK = 48,
YellowAlert_OKCancel,
YellowAlert_AbortRetryIgnore,
YellowAlert_YesNoCancel,
YellowAlert_YesNo,
YellowAlert_RetryCancel,
YellowAlert_CancelRetryContinue,
BlueInfo_OK = 64,
BlueInfo_OKCancel,
BlueInfo_AbortRetryIgnore,
BlueInfo_YesNoCancel,
BlueInfo_YesNo,
BlueInfo_RetryCancel,
BlueInfo_CancelRetryContinue
}
[Serializable]
public class TransObj
{
public string From
{
get => from;
set => from = value;
}
public string To
{
get => to;
set => to = value;
}
public List<TransResult> Data
{
get => data;
set => data = value;
}
public List<TransResult> data;
public string from;
public string to;
}
[Serializable]
public class TransResult
{
public string Src
{
get => src;
set => src = value;
}
public string Dst
{
get => dst;
set => dst = value;
}
public string dst;
public string src;
}
private class HtmlToText
{
static HtmlToText()
{
Tags.Add("address", "\n");
Tags.Add("blockquote", "\n");
Tags.Add("div", "\n");
Tags.Add("dl", "\n");
Tags.Add("fieldset", "\n");
Tags.Add("form", "\n");
Tags.Add("h1", "\n");
Tags.Add("/h1", "\n");
Tags.Add("h2", "\n");
Tags.Add("/h2", "\n");
Tags.Add("h3", "\n");
Tags.Add("/h3", "\n");
Tags.Add("h4", "\n");
Tags.Add("/h4", "\n");
Tags.Add("h5", "\n");
Tags.Add("/h5", "\n");
Tags.Add("h6", "\n");
Tags.Add("/h6", "\n");
Tags.Add("p", "\n");
Tags.Add("/p", "\n");
Tags.Add("table", "\n");
Tags.Add("/table", "\n");
Tags.Add("ul", "\n");
Tags.Add("/ul", "\n");
Tags.Add("ol", "\n");
Tags.Add("/ol", "\n");
Tags.Add("/li", "\n");
Tags.Add("br", "\n");
Tags.Add("/td", "\t");
Tags.Add("/tr", "\n");
Tags.Add("/pre", "\n");
IgnoreTags = new HashSet<string>();
IgnoreTags.Add("script");
IgnoreTags.Add("noscript");
IgnoreTags.Add("style");
IgnoreTags.Add("object");
}
public string Convert(string html)
{
_text = new TextBuilder();
_html = html;
_pos = 0;
while (!EndOfText)
{
if (Peek() == '<')
{
bool flag;
var text = ParseTag(out flag);
if (text == "body")
{
_text.Clear();
}
else if (text == "/body")
{
_pos = _html.Length;
}
else if (text == "pre")
{
_text.Preformatted = true;
EatWhitespaceToNextLine();
}
else if (text == "/pre")
{
_text.Preformatted = false;
}
string s;
if (Tags.TryGetValue(text, out s))
{
_text.Write(s);
}
if (IgnoreTags.Contains(text))
{
EatInnerContent(text);
}
}
else if (char.IsWhiteSpace(Peek()))
{
_text.Write(_text.Preformatted ? Peek() : ' ');
MoveAhead();
}
else
{
_text.Write(Peek());
MoveAhead();
}
}
return HttpUtility.HtmlDecode(_text.ToString());
}
protected string ParseTag(out bool selfClosing)
{
var result = string.Empty;
selfClosing = false;
if (Peek() == '<')
{
MoveAhead();
EatWhitespace();
var pos = _pos;
if (Peek() == '/')
{
MoveAhead();
}
while (!EndOfText && !char.IsWhiteSpace(Peek()) && Peek() != '/' && Peek() != '>')
{
MoveAhead();
}
result = _html.Substring(pos, _pos - pos).ToLower();
while (!EndOfText && Peek() != '>')
{
if (Peek() == '"' || Peek() == '\'')
{
EatQuotedValue();
}
else
{
if (Peek() == '/')
{
selfClosing = true;
}
MoveAhead();
}
}
MoveAhead();
}
return result;
}
protected void EatInnerContent(string tag)
{
var b = "/" + tag;
while (!EndOfText)
{
if (Peek() == '<')
{
bool flag;
if (ParseTag(out flag) == b)
{
return;
}
if (!flag && !tag.StartsWith("/"))
{
EatInnerContent(tag);
}
}
else
{
MoveAhead();
}
}
}
protected bool EndOfText => _pos >= _html.Length;
protected char Peek()
{
if (_pos >= _html.Length)
{
return '\0';
}
return _html[_pos];
}
protected void MoveAhead()
{
_pos = Math.Min(_pos + 1, _html.Length);
}
private void EatWhitespace()
{
while (char.IsWhiteSpace(Peek()))
{
MoveAhead();
}
}
private void EatWhitespaceToNextLine()
{
while (char.IsWhiteSpace(Peek()))
{
var num = (int)Peek();
MoveAhead();
if (num == 10)
{
break;
}
}
}
private void EatQuotedValue()
{
var c = Peek();
if (c == '"' || c == '\'')
{
MoveAhead();
_pos = _html.IndexOfAny(new[]
{
c,
'\r',
'\n'
}, _pos);
if (_pos < 0)
{
_pos = _html.Length;
return;
}
MoveAhead();
}
}
private static readonly Dictionary<string, string> Tags = new Dictionary<string, string>();
private static readonly HashSet<string> IgnoreTags;
protected TextBuilder _text;
private string _html;
private int _pos;
protected class TextBuilder
{
public TextBuilder()
{
_text = new StringBuilder();
_curLine = new StringBuilder();
_emptyLines = 0;
_preformatted = false;
}
public bool Preformatted
{
get => _preformatted;
set
{
if (value)
{
if (_curLine.Length > 0)
{
FlushCurLine();
}
_emptyLines = 0;
}
_preformatted = value;
}
}
public void Clear()
{
_text.Length = 0;
_curLine.Length = 0;
_emptyLines = 0;
}
public void Write(string s)
{
foreach (var c in s)
{
Write(c);
}
}
public void Write(char c)
{
if (_preformatted)
{
_text.Append(c);
return;
}
if (c != '\r')
{
if (c == '\n')
{
FlushCurLine();
return;
}
if (char.IsWhiteSpace(c))
{
var length = _curLine.Length;
if (length == 0 || !char.IsWhiteSpace(_curLine[length - 1]))
{
_curLine.Append(' ');
}
}
else
{
_curLine.Append(c);
}
}
}
private void FlushCurLine()
{
var text = _curLine.ToString().Trim();
if (text.Replace("\u00a0", string.Empty).Length == 0)
{
_emptyLines++;
if (_emptyLines < 2 && _text.Length > 0)
{
_text.AppendLine(text);
}
}
else
{
_emptyLines = 0;
_text.AppendLine(text);
}
_curLine.Length = 0;
}
public override string ToString()
{
if (_curLine.Length > 0)
{
FlushCurLine();
}
return _text.ToString();
}
private readonly StringBuilder _text;
private readonly StringBuilder _curLine;
private int _emptyLines;
private bool _preformatted;
}
}
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/amtech/tianruoocr.git
[email protected]:amtech/tianruoocr.git
amtech
tianruoocr
tianruoocr
master

搜索帮助