javascript 是否可以进一步压缩 Base64 PNG 字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9770051/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it possible to further compress a Base64 PNG String?
提问by Alp
I have a PNG image and got its Base64 PNG string representation. It's still quite large and i'd like to know if it can be significantly further compressed. Is that even possible?
我有一个 PNG 图像并得到了它的 Base64 PNG 字符串表示。它仍然很大,我想知道它是否可以进一步压缩。这甚至可能吗?
Background
背景
I am using Selenium 2 (Java) to create a screenshot of the current web page, convert it as base64 string and send that string to the JavaScript executor to recreate that image and do some image processing. But if that string size is too large, the server returns an Exception.
我正在使用 Selenium 2 (Java) 创建当前网页的屏幕截图,将其转换为 base64 字符串并将该字符串发送到 JavaScript 执行程序以重新创建该图像并进行一些图像处理。但是如果该字符串过大,服务器将返回一个异常。
回答by Robert
The simple answer: No - not without loosing the "printable string" nature
简单的答案:不-并非没有失去“可打印字符串”的性质
Usually PNG already uses sophisticated compression like it is used in ZIP files. Therefore compressing it before applying the base64 encoding will give you only very limited size reduction.
通常 PNG 已经使用了复杂的压缩方式,就像在 ZIP 文件中使用的一样。因此在应用 base64 编码之前压缩它只会给你非常有限的尺寸减少。
Applying the compression after the base64 encoding will make it to binary data again - in this case you could just skip the base64 encoding step.
在 base64 编码后应用压缩将使其再次变为二进制数据 - 在这种情况下,您可以跳过 base64 编码步骤。
回答by Peter Evans
If it is a problem with the network and not really the size of your string, this worked for me when I sent my images to a mongo database.
如果是网络问题而不是字符串的大小,当我将图像发送到 mongo 数据库时,这对我有用。
Using Express.js
the limit of the bodyParser is defaulted to 1056k
so you can fix the problem by changing the limit as below.
使用Express.js
bodyParser 的限制默认为 1056k,因此您可以通过如下更改限制来解决问题。
app.use(bodyParser.urlencoded({ limit: '50mb',
extended: true
}));
app.use(bodyParser.json({ limit: '50mb' }));
回答by Ed Williams
You might save a few hundred bytes using a Run Length Encodingalgorithm.
使用运行长度编码算法可以节省几百个字节。
For example,
例如,
const encode = (plainText) => {
const consecutiveChars = /([\w\s])*/g;
return plainText.replace(consecutiveChars,
match => (match.length > 1 ? match.length + match[0] : match[0]));
};
(credit: https://github.com/exercism/javascript/blob/master/exercises/run-length-encoding/example.js)
(信用:https: //github.com/exercism/javascript/blob/master/exercises/run-length-encoding/example.js)
test:expect(encode('AABBBCCCC')).toEqual('2A3B4C')
测试:expect(encode('AABBBCCCC')).toEqual('2A3B4C')