How to get valid base64 string for an image

橙三吉。 提交于 2020-01-02 23:02:13

问题


I use the following code to get a base64 encoded string of my image:

UIImage *image = [photoView image];
NSString *encoded = [UIImagePNGRepresentation(image) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];

The image is 800*800 pixels, but the generated string is so big that it crashes my browser when I paste it in a textbox. I pasted it in dreamweaver to count the lines and it is over 300.000 lines. This can't be right. If I upload the same picture to this site it generates a base64 string of about 200 lines.

How do I generate a 'normal' base64 string in objective c? One that I can actually use...

As Martin R suggested I checked the data length of what UIImagePNGRepresentation(image) returns and it is 4502370 bytes. This is probably a part of the problem. Could it be that drawing an image in a UIImageView and retrieving it later like I'm doing gives back an image at the screen size?


回答1:


By using NSDataBase64Encoding64CharacterLineLength you limit each line to 64 characters (as is written in the documentation). Try:

NSString *encoded = [UIImagePNGRepresentation(image) base64EncodedStringWithOptions:0];



回答2:


A base-64 encoded string is 1.37 times the size of the binary data. Therefore:

800x800x4 (32-bit RGBA) = 2,560,000 bytes

x 1.37 = 3,507,200 bytes

I don't understand why you are pasting the base-64 encoded string into a browser though?



来源:https://stackoverflow.com/questions/20971719/how-to-get-valid-base64-string-for-an-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!