In build a small Javascript application. With this app you can take photos via the cam. The App temporarily stores images in the Browser localStorage as base64. Now I want the app to be told the amount of storage used. So how big the image is in KB.
Asked
Active
Viewed 906 times
2
-
Does this answer your question? [How to get file size of newly created Image() if src is base64 string?](https://stackoverflow.com/questions/29939635/how-to-get-file-size-of-newly-created-image-if-src-is-base64-string) – GrafiCode Aug 25 '22 at 10:06
-
2"temporarily stores images in the Browser localStorage as base64." gentle unrelated note: you may prefer to avoid that. The LocalStorage is a very slow API and is not meant to store big amount of data like an image. At each page load the browser has to load all its content synchronously in memory. Instead prefer IndexedDB where you can store the image as binary directly (as Blob), and where the browser will keep it on the user's disk until you explicitly ask for it. Using a lib like [localForage](https://github.com/localForage/localForage), it's almost as easy to use as the LocalStorage API. – Kaiido Aug 25 '22 at 10:13
-
1And it's unclear if you want to know the size (in KB) of the string, or the size of the binary data it represents. – Kaiido Aug 25 '22 at 10:16
-
@Kaiido That is a really important hint! I already had a strange feeling about saving pictures in the localStorage, because pictures (depending on the camera, etc.) can become very large. I didn't know IndexDB but I'll have a look at it right away. If I could I would give you a +1 for this important tip!!! Thank you very much! – Max Pattern Aug 25 '22 at 10:19
-
@Kaiido Size of the image. – Max Pattern Aug 25 '22 at 10:19
1 Answers
1
Each character has 8 bits. And 8 bits are 1 byte. So you have the formula:
small Example
const base64Image = 'data;image/png;base64, ... ';
const yourBase64String =
base64Image.substring(base64Image.indexOf(',') + 1);
const bits = yourBase64String.length * 6; // 567146
const bytes = bits / 8;
const kb = ceil(bytes / 1000);
// in one Line
const kb = ceil( ( (yourBase64String.length * 6) / 8) / 1000 ); // 426 kb

Maik Lowrey
- 15,957
- 6
- 40
- 79
-
2The size of the string will depend on the encoding used by the browser to store the data. – Kaiido Aug 25 '22 at 10:16
-
Thank you @Kaiido for pointing this out. You mean the first characters of a Bas64 string, right? You could delete this with `str.substring(str.indexOf(',') + 1`. I will update it. – Maik Lowrey Aug 25 '22 at 10:23
-
@Kaiido updated. I thought that base64 encodes everything into a base64 by itself. And the base64 length is the decisive factor, or am I seeing it wrong? – Maik Lowrey Aug 25 '22 at 10:36
-
1This seems to me to be a quite stable and simple solution. Thank you – Max Pattern Aug 25 '22 at 10:38