public Write ( byte buffer, int offset, int count ) : void | ||
buffer | byte | The buffer containing data to write. |
offset | int | The offset of the first byte to write. |
count | int | The number of bytes to write. |
return | void |
public void BasicRoundTrip() { MemoryStream ms = new MemoryStream(); BZip2OutputStream outStream = new BZip2OutputStream(ms); byte[] buf = new byte[10000]; System.Random rnd = new Random(); rnd.NextBytes(buf); outStream.Write(buf, 0, buf.Length); outStream.Close(); ms = new MemoryStream(ms.GetBuffer()); ms.Seek(0, SeekOrigin.Begin); using (BZip2InputStream inStream = new BZip2InputStream(ms)) { byte[] buf2 = new byte[buf.Length]; int pos = 0; while (true) { int numRead = inStream.Read(buf2, pos, 4096); if (numRead <= 0) { break; } pos += numRead; } for (int i = 0; i < buf.Length; ++i) { Assert.AreEqual(buf2[i], buf[i]); } } }
public void BasicRoundTrip() { MemoryStream ms = new MemoryStream(); BZip2OutputStream outStream = new BZip2OutputStream(ms); byte[] buf = new byte[10000]; System.Random rnd = new Random(); rnd.NextBytes(buf); outStream.Write(buf, 0, buf.Length); outStream.Close(); ms = new MemoryStream(ms.GetBuffer()); ms.Seek(0, SeekOrigin.Begin); BZip2InputStream inStream = new BZip2InputStream(ms); byte[] buf2 = new byte[buf.Length]; int pos = 0; while (true) { int numRead = inStream.Read(buf2, pos, 4096); if (numRead <= 0) { break; } pos += numRead; } for (int i = 0; i < buf.Length; ++i) { Assertion.AssertEquals(buf2[i], buf[i]); } }
/// <summary> /// 压缩字符串 /// </summary> /// <param name="str">需要压缩的字符串</param> /// <returns>base64位字符串</returns> public string CompressStr(string str) { //判断字符串是否为空,为空则返回结果为空 if (str == null) { return(""); } //字符串不为空则执行一下语句 try { //定义数组存放压缩字符串字节序列 byte[] bytData = System.Text.Encoding.Unicode.GetBytes(str); //创建存储内存流 MemoryStream ms = new MemoryStream(); //实例化BZip2OutputStream类 Stream s = new ICSharpCode.SharpZipLib.BZip2.BZip2OutputStream(ms); //字节压缩 s.Write(bytData, 0, bytData.Length); //关闭内存流,释放字节序列 s.Close(); //获取返回的字节序列数组 byte[] compressedData = (byte[])ms.ToArray(); //获取数组转化为base64位字符串 string result = System.Convert.ToBase64String(compressedData, 0, compressedData.Length) + " " + bytData.Length; //返回base64位字符串 return(result); } catch (Exception ex) { //报错信息 throw ex; } }
/// <summary> /// 지정된 데이타를 압축한다. /// </summary> /// <param name="input">압축할 Data</param> /// <returns>압축된 Data</returns> public override byte[] Compress(byte[] input) { if(IsDebugEnabled) log.Debug(CompressorTool.SR.CompressStartMsg); // check input data if(input.IsZeroLength()) { if(IsDebugEnabled) log.Debug(CompressorTool.SR.InvalidInputDataMsg); return CompressorTool.EmptyBytes; } byte[] output; // Compress using(var outStream = new MemoryStream(input.Length)) using(var bz2 = new BZip2OutputStream(outStream, CompressorTool.BUFFER_SIZE)) { bz2.Write(input, 0, input.Length); bz2.Close(); output = outStream.ToArray(); } if(IsDebugEnabled) log.Debug(CompressorTool.SR.CompressResultMsg, input.Length, output.Length, output.Length / (double)input.Length); return output; }
public void BZip2_Compress_Extract_Test() { var plainStream = PlainText.ToStream(); plainStream.Seek(0, SeekOrigin.Begin); var plainData = Encoding.UTF8.GetBytes(PlainText); byte[] compressedData; byte[] extractedData; // Compress using(var compressedStream = new MemoryStream()) using(var bz2 = new BZip2OutputStream(compressedStream)) { bz2.Write(plainData, 0, plainData.Length); bz2.Close(); compressedData = compressedStream.ToArray(); } Assert.IsNotNull(compressedData); // Array.Resize(ref compressedData, compressedData.Length+1); // compressedData[compressedData.Length - 1] = (byte)0; // Extract using(var compressedStream = new MemoryStream(compressedData)) using(var bz2 = new BZip2InputStream(compressedStream)) using(var extractedStream = new MemoryStream()) { StreamTool.CopyStreamToStream(bz2, extractedStream); extractedData = extractedStream.ToArray(); } Assert.IsNotNull(extractedData); string extractedText = Encoding.UTF8.GetString(extractedData).TrimEnd('\0'); Assert.AreEqual(PlainText, extractedText); }
/// <summary> /// Compresses a byte array /// </summary> /// <param name="data"></param> /// <returns></returns> public static byte[] CompressBytes(this byte[] data) { // empty if null if (data.IsNullOrEmpty()) return null; using (MemoryStream msBZip2 = new MemoryStream()) { int size = data.Length; // Prepend the compressed data with the length of the uncompressed data (firs 4 bytes) using (BinaryWriter writer = new BinaryWriter(msBZip2)) { writer.Write(size); using (BZip2OutputStream BZip2OutStream = new BZip2OutputStream(msBZip2)) { BZip2OutStream.Write(data, 0, size); } } // return the compressed data return msBZip2.ToArray(); } }
/// <summary> /// /// </summary> /// <param name="bytesToCompress"></param> /// <returns></returns> public byte[] Compress(byte[] bytesToCompress) { MemoryStream ms = new MemoryStream(); Stream s = new BZip2OutputStream(ms); //fire the contents of the byte-array into the OutputStream to perform the compression s.Write(bytesToCompress,0, bytesToCompress.Length); s.Close(); //Convert the memoryStream back into a byte Array byte[] compressedData = (byte[]) ms.ToArray(); ms.Close(); return compressedData; }
public static byte[] Compress(byte[] input) { Contract.Requires(input != null); Contract.Ensures(Contract.Result<byte[]>() != null); var length = input.Length; var ms = new MemoryStream(length); using (var stream = new BZip2OutputStream(ms)) stream.Write(input, 0, length); return ms.ToArray(); }
/// <summary> /// 压缩 /// </summary> /// <param name="input"></param> /// <returns></returns> public static string Compress(string input) { string result = string.Empty; byte[] buffer = Encoding.UTF8.GetBytes(input); using (MemoryStream outputStream = new MemoryStream()) { using (BZip2OutputStream zipStream = new BZip2OutputStream(outputStream)) { zipStream.Write(buffer, 0, buffer.Length); zipStream.Close(); } return Convert.ToBase64String(outputStream.ToArray()); } }
public static byte[] BZip2CompressArray(byte[] data) { MemoryStream ms = new MemoryStream(); using (BZip2OutputStream bz = new BZip2OutputStream(ms, 9)) { bz.IsStreamOwner = false; bz.Write(data, 0, data.Length); } ms.Position = 0; byte[] compressed = new byte[ms.Length]; ms.Read(compressed, 0, compressed.Length); byte[] gzBuffer = new byte[compressed.Length + 4]; System.Buffer.BlockCopy(compressed, 0, gzBuffer, 4, compressed.Length); System.Buffer.BlockCopy(BitConverter.GetBytes(data.Length), 0, gzBuffer, 0, 4); return gzBuffer; }
/// <summary> /// 压缩 /// </summary> /// <param name="param"></param> /// <returns></returns> public static string Compress(string param) { byte[] data = System.Text.Encoding.UTF8.GetBytes(param); //byte[] data = Convert.FromBase64String(param); MemoryStream ms = new MemoryStream(); Stream stream = new ICSharpCode.SharpZipLib.BZip2.BZip2OutputStream(ms); try { stream.Write(data, 0, data.Length); } finally { stream.Close(); ms.Close(); } return(Convert.ToBase64String(ms.ToArray())); }
private void AddFile(string path) { string fileNameInDestination = this.GetFileNameInDestination(path); if (!Directory.Exists(Path.GetDirectoryName(fileNameInDestination))) { Directory.CreateDirectory(Path.GetDirectoryName(fileNameInDestination)); } string contents = this.GetMd5Sum(File.ReadAllBytes(path)); using (BZip2OutputStream stream = new BZip2OutputStream(new FileStream(fileNameInDestination + ".bz2", FileMode.Create, FileAccess.Write))) { byte[] buffer = File.ReadAllBytes(path); stream.Write(buffer, 0, buffer.Length); } File.WriteAllText(this.GetDestinationHashLocation(fileNameInDestination), contents); }
public static string ZipString(string sBuffer) { MemoryStream m_msBZip2 = null; BZip2OutputStream m_osBZip2 = null; string result; try { m_msBZip2 = new MemoryStream(); Int32 size = sBuffer.Length; // Prepend the compressed data with the length of the uncompressed data (firs 4 bytes) // using (BinaryWriter writer = new BinaryWriter(m_msBZip2, System.Text.Encoding.ASCII)) { writer.Write(size); m_osBZip2 = new BZip2OutputStream(m_msBZip2); m_osBZip2.Write(Encoding.ASCII.GetBytes(sBuffer), 0, sBuffer.Length); m_osBZip2.Close(); result = Convert.ToBase64String(m_msBZip2.ToArray()); m_msBZip2.Close(); writer.Close(); } } finally { if (m_osBZip2 != null) { m_osBZip2.Dispose(); } if (m_msBZip2 != null) { m_msBZip2.Dispose(); } } return result; }
override public void AddToStream (Stream stream, EventTracker tracker) { if (ChildCount > 1) throw new Exception ("Bzip2 file " + Uri + " has " + ChildCount + " children"); if (tracker != null) tracker.ExpectingAdded (UriFu.UriToEscapedString (this.Uri)); UnclosableStream unclosable; unclosable = new UnclosableStream (stream); BZip2OutputStream bz2_out; bz2_out = new BZip2OutputStream (unclosable); MemoryStream memory; memory = new MemoryStream (); // There should just be one child foreach (FileObject file in Children) file.AddToStream (memory, tracker); bz2_out.Write (memory.ToArray (), 0, (int) memory.Length); memory.Close (); bz2_out.Close (); }
/// <summary> /// 压缩字符串(ICSharpCode.SharpZipLib版) /// </summary> /// <param name="buffer"></param> /// <returns></returns> public static string CompressByteToStr(byte[] buffer) { using (MemoryStream outputStream = new MemoryStream()) { using (BZip2OutputStream zipStream = new BZip2OutputStream(outputStream)) { zipStream.Write(buffer, 0, buffer.Length); zipStream.Close(); } return Convert.ToBase64String(outputStream.ToArray()); } }
public void Compress(ProgressChangedEventHandler progressChanged) { using (FileStream archiveStream = new FileStream(ReportBaseName + ".tar", FileMode.Create, FileAccess.Write)) { TarArchive archive = TarArchive.CreateOutputTarArchive(archiveStream); foreach (FileInfo file in Report.Files) { TarEntry entry = TarEntry.CreateEntryFromFile(file.FullName); entry.Name = Path.GetFileName(entry.Name); archive.WriteEntry(entry, false); } archive.Close(); } using (FileStream bzipFile = new FileStream(ReportBaseName + ".tbz", FileMode.Create)) using (FileStream tarStream = new FileStream(ReportBaseName + ".tar", FileMode.Open, FileAccess.Read, FileShare.Read, 262144, FileOptions.DeleteOnClose)) using (BZip2OutputStream bzipStream = new BZip2OutputStream(bzipFile, 262144)) { int lastRead = 0; byte[] buffer = new byte[524288]; while ((lastRead = tarStream.Read(buffer, 0, buffer.Length)) != 0) { bzipStream.Write(buffer, 0, lastRead); progressChanged(this, new ProgressChangedEventArgs( (int)(tarStream.Position * 100 / tarStream.Length), null)); } } }
public void CompressAndSendBuffer(ref byte []buffer,DataType bDataType,ref int nX ,ref int nY) { if(buffer != null) { try { MemoryStream msCompressed = new MemoryStream(); BZip2OutputStream zosCompressed = new BZip2OutputStream(msCompressed); zosCompressed.Write(buffer, 0, buffer.Length); zosCompressed.Close(); buffer =msCompressed.ToArray(); } catch(Exception ex) { WebMeeting.Client.ClientUI.getInstance().ShowExceptionMessage("Module ::: AppShare public void CompressAndSendBuffer(ref byte []buffer,DataType bDataType,ref int nX ,ref int nY)",ex,"",false); } } try { OnDataAvailable(ref buffer,bDataType,ref nX,ref nY); } catch(Exception ex) { WebMeeting.Client.ClientUI.getInstance().ShowExceptionMessage("Module ::: AppShare public void CompressAndSendBuffer(ref byte []buffer,DataType bDataType,ref int nX ,ref int nY)",ex,"",false); } }
private void Compress(SteppedProgressManager progress, ProgressChangedEventHandler progressChanged) { using (FileStream archiveStream = new FileStream(ReportBaseName + ".tar", FileMode.Create, FileAccess.Write)) { TarArchive archive = TarArchive.CreateOutputTarArchive(archiveStream); foreach (FileInfo file in Report.Files) { TarEntry entry = TarEntry.CreateEntryFromFile(file.FullName); entry.Name = Path.GetFileName(entry.Name); archive.WriteEntry(entry, false); } archive.Close(); } ProgressManager step = new ProgressManager(); progress.Steps.Add(new SteppedProgressManagerStep(step, 0.5f, "Compressing")); using (FileStream bzipFile = new FileStream(ReportBaseName + ".tbz", FileMode.Create)) using (FileStream tarStream = new FileStream(ReportBaseName + ".tar", FileMode.Open, FileAccess.Read, FileShare.Read, 262144, FileOptions.DeleteOnClose)) using (BZip2OutputStream bzipStream = new BZip2OutputStream(bzipFile, 262144)) { int lastRead = 0; byte[] buffer = new byte[524288]; while ((lastRead = tarStream.Read(buffer, 0, buffer.Length)) != 0) { bzipStream.Write(buffer, 0, lastRead); step.Completed = tarStream.Position; step.Total = tarStream.Length; if (progressChanged != null) progressChanged(this, new ProgressChangedEventArgs(progress, null)); } } }
static void CreateInternal(byte[] oldData, byte[] newData, Stream output) { // check arguments if (oldData == null) throw new ArgumentNullException("oldData"); if (newData == null) throw new ArgumentNullException("newData"); if (output == null) throw new ArgumentNullException("output"); if (!output.CanSeek) throw new ArgumentException("Output stream must be seekable.", "output"); if (!output.CanWrite) throw new ArgumentException("Output stream must be writable.", "output"); /* Header is 0 8 "BSDIFF40" 8 8 length of bzip2ed ctrl block 16 8 length of bzip2ed diff block 24 8 length of new file */ /* File is 0 32 Header 32 ?? Bzip2ed ctrl block ?? ?? Bzip2ed diff block ?? ?? Bzip2ed extra block */ byte[] header = new byte[c_headerSize]; WriteInt64(c_fileSignature, header, 0); // "BSDIFF40" WriteInt64(0, header, 8); WriteInt64(0, header, 16); WriteInt64(newData.Length, header, 24); long startPosition = output.Position; output.Write(header, 0, header.Length); int[] I = SuffixSort(oldData); byte[] db = new byte[newData.Length]; byte[] eb = new byte[newData.Length]; int dblen = 0; int eblen = 0; using (WrappingStream wrappingStream = new WrappingStream(output, Ownership.None)) using (BZip2OutputStream bz2Stream = new BZip2OutputStream(wrappingStream)) { // compute the differences, writing ctrl as we go int scan = 0; int pos = 0; int len = 0; int lastscan = 0; int lastpos = 0; int lastoffset = 0; while (scan < newData.Length) { int oldscore = 0; for (int scsc = scan += len; scan < newData.Length; scan++) { len = Search(I, oldData, newData, scan, 0, oldData.Length, out pos); for (; scsc < scan + len; scsc++) { if ((scsc + lastoffset < oldData.Length) && (oldData[scsc + lastoffset] == newData[scsc])) oldscore++; } if ((len == oldscore && len != 0) || (len > oldscore + 8)) break; if ((scan + lastoffset < oldData.Length) && (oldData[scan + lastoffset] == newData[scan])) oldscore--; } if (len != oldscore || scan == newData.Length) { int s = 0; int sf = 0; int lenf = 0; for (int i = 0; (lastscan + i < scan) && (lastpos + i < oldData.Length); ) { if (oldData[lastpos + i] == newData[lastscan + i]) s++; i++; if (s * 2 - i > sf * 2 - lenf) { sf = s; lenf = i; } } int lenb = 0; if (scan < newData.Length) { s = 0; int sb = 0; for (int i = 1; (scan >= lastscan + i) && (pos >= i); i++) { if (oldData[pos - i] == newData[scan - i]) s++; if (s * 2 - i > sb * 2 - lenb) { sb = s; lenb = i; } } } if (lastscan + lenf > scan - lenb) { int overlap = (lastscan + lenf) - (scan - lenb); s = 0; int ss = 0; int lens = 0; for (int i = 0; i < overlap; i++) { if (newData[lastscan + lenf - overlap + i] == oldData[lastpos + lenf - overlap + i]) s++; if (newData[scan - lenb + i] == oldData[pos - lenb + i]) s--; if (s > ss) { ss = s; lens = i + 1; } } lenf += lens - overlap; lenb -= lens; } for (int i = 0; i < lenf; i++) db[dblen + i] = (byte) (newData[lastscan + i] - oldData[lastpos + i]); for (int i = 0; i < (scan - lenb) - (lastscan + lenf); i++) eb[eblen + i] = newData[lastscan + lenf + i]; dblen += lenf; eblen += (scan - lenb) - (lastscan + lenf); byte[] buf = new byte[8]; WriteInt64(lenf, buf, 0); bz2Stream.Write(buf, 0, 8); WriteInt64((scan - lenb) - (lastscan + lenf), buf, 0); bz2Stream.Write(buf, 0, 8); WriteInt64((pos - lenb) - (lastpos + lenf), buf, 0); bz2Stream.Write(buf, 0, 8); lastscan = scan - lenb; lastpos = pos - lenb; lastoffset = pos - scan; } } } // compute size of compressed ctrl data long controlEndPosition = output.Position; WriteInt64(controlEndPosition - startPosition - c_headerSize, header, 8); // write compressed diff data using (WrappingStream wrappingStream = new WrappingStream(output, Ownership.None)) using (BZip2OutputStream bz2Stream = new BZip2OutputStream(wrappingStream)) { bz2Stream.Write(db, 0, dblen); } // compute size of compressed diff data long diffEndPosition = output.Position; WriteInt64(diffEndPosition - controlEndPosition, header, 16); // write compressed extra data using (WrappingStream wrappingStream = new WrappingStream(output, Ownership.None)) using (BZip2OutputStream bz2Stream = new BZip2OutputStream(wrappingStream)) { bz2Stream.Write(eb, 0, eblen); } // seek to the beginning, write the header, then seek back to end long endPosition = output.Position; output.Position = startPosition; output.Write(header, 0, header.Length); output.Position = endPosition; }