我需要将压缩文本写入QR码,然后对其进行扫描和解压缩。
源文本是缩小的JSON字符串:
{"ref":"WR0001","customsType":"GIFT","insuredValue":20000,"weight":500,"shippingMethod":"EMS","sender":{"notificationEmail":"asd@asd.com","phoneNumber":"+818023459877","address":{"name":"TestName","companyName":"TestCompanyName","address1":"Testaddress1","address2":"Testaddress2","city":"Testcity","postalCode":"111222","region":"Tokyo","countryIso2":"ES"}},"recipient":{"phoneNumber":"+81231231","address":{"name":"John","companyName":"Salchichon","address1":"myhome","address2":"somewhere","city":"somecity","region":"someregion","postalCode":"111","codiceFiscale":"232323","countryIso2":"IT"}},"items":[{"quantity":1,"price":1000,"customs":"Somecustoms1"},{"quantity":2,"price":1500,"customs":"Somecustoms2"}]}
Deflate似乎会生成这样的二进制文本
óMMÉ,I,ÉÌÏSÈÈ/QHÎÈLÎNÍS(K,È/ * O,JŠ%gèf§Vò[...截短]
有没有一种压缩算法可以渲染base64文本?我需要一些可以存储在QR码中的东西。
如果仅将base64编码应用于压缩字节,则会得到一个比源文本大的字符串!
public partial class Main : Form
{
public Main()
{
InitializeComponent();
this.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.Main_KeyPress);
}
List<char> _barcode = new List<char>(1000);
private void Main_KeyPress(object sender, KeyPressEventArgs e)
{
_barcode.Add(e.KeyChar);
// process barcode
if (e.KeyChar == 13 && _barcode.Count > 0)
{
string msg = new String(_barcode.ToArray());
MessageBox.Show(msg );
Console.WriteLine(msg);
//serializer
MemoryStream stream = new MemoryStream(Encoding.Default.GetBytes(msg));
byte[] compressedBytes;
compressedBytes = Compress(stream);
Console.WriteLine("compressed:" + Encoding.Default.GetString(compressedBytes));
Decompress(compressedBytes);
_barcode.Clear();
}
}
private static Stream Decompress(byte[] input)
{
var output = new MemoryStream();
using (var compressStream = new MemoryStream(input))
using (var decompressor = new DeflateStream(compressStream, CompressionMode.Decompress))
decompressor.CopyTo(output);
output.Position = 0;
Console.WriteLine("decompressed:" + Encoding.Default.GetString(output.ToArray()));
output.Position = 0;
return output;
}
private static byte[] Compress(Stream input)
{
using (var compressStream = new MemoryStream())
using (var compressor = new DeflateStream(compressStream, CompressionMode.Compress))
{
input.CopyTo(compressor);
compressor.Close();
return compressStream.ToArray();
}
}
}
}
答案 0 :(得分:1)
如果您的数据按注释中所述4:1压缩,那么使用Base64进行编码只会将其扩展33%,剩下3:1压缩。
您可以改用Base85编码,选择85个可打印字符。这样会将四个字节转换为五个字符,而不是像Base64那样将三个字节转换为四个字符。