zlibfromC++toC#(字节转流和流转字节)我的任务是使用zlib来解压缩一个数据包(收到),然后使用算法从数据中生成图片好消息是我有C++代码,但任务是在C#C++中完成的//读取数据包的第一个值收到的DWORD图像[200*64]={0};//用于算法(宽度总是=200和高度总是==64)intimgIndex=0;//用于算法unsignedcharrawbytes_[131072]={0};//阅读下面的unsignedchar*rawbytes=rawbytes_;//解压缩的目标参数(ptr)compressed=r.Read();//压缩后的字节长度(图片)uncompressed=r.Read();//解压后应有的长度width=r.Read();//图片的宽度height=r.Read();//图片的高度LPBYTEptr=r.GetCurrentStream();//字节数(必须解压的文件)outLen=uncompressed;//将len复制到另一个变量中//解压缩if(uncompress((Bytef*)rawbytes,&outLen,ptr,compressed)!=Z_OK){printf("Couldnotuncompresstheimagecode.n");Disconnect();return;}//Algoritmtomakethepicture//遍历数据for(intc=0;c<(int)height;++c){for(intr=0;r<(int)width;++r){imgIndex=(height-1-c)*width+r;image[imgIndex]=0xFF000000;if(-((1<>3)]))image[imgIndex]=0xFFFFFFFF;}}我试图用zlib.NET做这个,但所有表现都有解压的代码(C#)privatevoiddecompressFile(stringinFile,stringoutFile){System.IO.FileStreamoutFileStream=newSystem.IO.FileStream(outFile,System.IO.FileMode.Create);zlib.ZOutputStreamoutZStream=newzlib.ZOutputStream(outFileStream);System.IO.FileStreaminFileStream=newSystem.IO.FileStream(inFile,System.IO.FileMode.Open);try{CopyStream(inFileStream,outZStream);}最后{outZStream.Close();outFileStream.Close();inFileStream.Close();}}publicstaticvoidCopyStream(System.IO.Streaminput,System.IO.Stream输出){byte[]buffer=newbyte[2000];intlen;while((len=input.Read(buffer,0,2000))>0){output.Write(缓冲区,0,len);}output.Flush();我的问题:我不想在解压后保存文件,因为我必须使用Howdoesthealgorithmshownconvertthebyte[]arraytoastreamsimilartothestreamintheC#zlibcodetodecompressthedataandthen将流转换回字节数组?另外,如何更改zlib.NET代码以不保存文件?只需使用MemoryStreams而不是FileStreams://假设inputData是一个byte[]MemoryStreaminput=newMemoryStream(inputData);内存流输出=新的内存流();然后你可以使用output.ToArray()来获取字节数组。请注意,通常最好使用using语句而不是单个try/finally块-否则如果第一次调用Close失败,则其余部分将不会继续。你可以像这样嵌套它们:using(MemoryStreamoutput=newMemoryStream())返回输出.ToArray();我只是有同样的问题。为了完整性......(因为这让我困了几个小时)在ZLib.Net的情况下,你还必须调用finish(),这通常发生在Close()期间,在调用returnoutput.ToArray()else之前,你'你会从内存流中得到一个空的/不完整的字节数组,因为ZStream实际上还没有写入所有的数据:))使用(ZOutputStreamoutZStream=newZOutputStream(outMemoryStream,zlibConst.Z_DEFAULT_COMPRESSION))使用(StreaminMemoryStream=newMemoryStream(inData)){CopyStream(inMemoryStream,outZStream);出ZStream。);}}publicstaticvoidDecompressData(byte[]inData,outbyte[]outData){使用(MemoryStreamoutMemoryStream=newMemoryStream())){CopyStream(inMemoryStream,outZStream);outZStream.finish();outData=outMemoryStream.ToArray();在这个例子中我也使用了zlib命名空间:usingzlib;最初在这篇文章中找到:ZLib解压我还没有足够的点赞,所以...感谢TimGreaves在ToArray之前提供的完成提示和JonSkeet提供的关于对嵌套流使用语句的提示(我比try/finally更好)以上就是C#学习教程:从C++到C#的zlib(如何将byte转stream和stream转byte)全部分享的内容,如果对你有用又需要了解更多C#学习教程,希望你以后会多加关注—本文为网络搜集,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如有转载请注明出处:
