2010-06-23 91 views
3

我不得不在flash中加載一個大的XML,我試圖發送它壓縮。爲此,我嘗試zlib壓縮字符串並將其發送給base64編碼。在Flash中,我將字符串轉換爲一個字節數組並使用其uncompress()方法。到目前爲止,我嘗試:如何在.net c#中壓縮字符串並在flash as3中解壓縮?

ZLIB.NET

byte[] bytData = System.Text.Encoding.UTF8.GetBytes(str); 
MemoryStream ms = new MemoryStream(); 
Stream s = new zlib.ZOutputStream(ms, 3); 
s.Write(bytData, 0, bytData.Length); 
s.Close(); 
byte[] compressedData = (byte[])ms.ToArray(); 
return System.Convert.ToBase64String(compressedData); 

Ionic.Zlib(DotNetZip)

return System.Convert.ToBase64String(Ionic.Zlib.GZipStream.CompressBuffer(System.Text.Encoding.UTF8.GetBytes(str))); 

ICSharpCode.SharpZipLib(我不知道如何設置壓縮爲zlib)

byte[] a = Encoding.Default.GetBytes(str); 
MemoryStream memStreamIn = new MemoryStream(a); 
MemoryStream outputMemStream = new MemoryStream(); 
ZipOutputStream zipStream = new ZipOutputStream(outputMemStream); 
zipStream.SetLevel(3); //0-9, 9 being the highest level of compression 
ZipEntry newEntry = new ZipEntry("zipEntryName"); 
newEntry.DateTime = DateTime.Now; 
zipStream.PutNextEntry(newEntry); 
StreamUtils.Copy(memStreamIn, zipStream, new byte[4096]); 
zipStream.CloseEntry(); 
zipStream.IsStreamOwner = false; // False stops the Close also Closing the underlying stream. 
zipStream.Close(); // Must finish the ZipOutputStream before using outputMemStream. 
byte[] byteArrayOut = outputMemStream.ToArray(); 
return System.Convert.ToBase64String(byteArrayOut); 

所有產生不同的結果,但閃光燈引發錯誤#2058:解壓縮數據時出錯。

var decode:ByteArray = Base64.decodeToByteArray(str); 
decode.uncompress(); 
return decode.toString(); 

的Base64類從這裏http://code.google.com/p/as3crypto/source/browse/trunk/as3crypto/src/com/hurlant/util/Base64.as?r=3

所以,我怎麼能壓縮在.NET中的字符串,並將其在閃存解壓?

回答

2

我得到了它與ZLIB.NET工作。我只需將編碼設置爲ASCII Encoding.ASCII.GetBytes(str);

+0

就性能而言,它將6.5 MB xml轉換爲43 KB的字符串。我沒有時間測試閃存解碼速度,但在我舊的Core 2 Duo 2 GHz上看起來非常快。 – bfi 2010-06-23 16:07:22

+0

+1我一直在尋找適用於壓縮的代碼,並且您的評論以及您的原始評論是第一個實際工作的代碼。謝謝你,謝謝你,謝謝你。 – 2013-04-03 12:17:27

0

Flash不支持插件版本中的zip壓縮。它只做gzip。只有在爲AIR編譯時,您纔可以選擇使用zip。所以,如果你的目標是你需要在C#側一個gzip編碼器的瀏覽器(我認爲這是GZipStream)

http://www.adobe.com/livedocs/flash/9.0/ActionScriptLangRefV3/flash/utils/ByteArray.html#uncompress%28%29

+0

是的,從文檔:「Flash Player僅支持默認算法zlib」。這就是爲什麼我嘗試在.net中使用zlib。或者我在這裏錯過了什麼? – bfi 2010-06-23 15:28:05

+0

P.S.我已經嘗試了GZipStream(來自我的文章的第二個例子),來自DotNetZip庫。我和System.IO.Compression做的一樣,只是更好。 – bfi 2010-06-23 15:39:35

+0

哦,我看到了 - 我不知何故只是看了你的第三個例子,而忽略了第二個例子。 – Quasimondo 2010-06-23 15:52:01