最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Is it possible to further compress a Base64 PNG String? - Stack Overflow

programmeradmin1浏览0评论

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?

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.

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?

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.

Share Improve this question asked Mar 19, 2012 at 12:18 AlpAlp 29.7k29 gold badges122 silver badges202 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 11

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.

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.

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.

Using Express.js the limit of the bodyParser is defaulted to 1056k so you can fix the problem by changing the limit as below.

app.use(bodyParser.urlencoded({ limit: '50mb', 
  extended: true
}));
app.use(bodyParser.json({ limit: '50mb' }));

You might save a few hundred bytes using a Run Length Encoding algorithm.

For example,

const encode = (plainText) => {
  const consecutiveChars = /([\w\s])\1*/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)

test: expect(encode('AABBBCCCC')).toEqual('2A3B4C')

发布评论

评论列表(0)

  1. 暂无评论