Calculate the size of a base64 image in Kb, Mb - javascript

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.

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

Related

how can i convert kilobyte to GB

I have
size: 0.20800000000000002``` in KB
I need to convert the readable format of the GB
{size / 1000000} is used this
output: 2.08e7
but it is not correct in a readable format I need to set it to a proper readable format of GB
let size_gb = (size / 1000000).toFixed(2);
The toFixed(2) method formats the number to have two decimal
Usually, 0.20800000000000002 Kb would be 0 Gb in a readable format. because the result will be 0.0000002000008. however, if you want to show it in a decimal number you can use the .toFixed() function.
let size: 0.20800000000000002
let sizeGb = (size/1000000).toFixed(7) // for this scenario
// the output will be 0.0000002
or
let size: 0.20800000000000002
let sizeGb = (size/1000000).toFixed(2) // the output will be 0.00
What do you define as a "readable" format? The hundreths place (if necessary?)
This will convert your number UP to the hundreths place IF necessary:
let kb = 0.20800000000000002;
let gb = kb / 1000000;
let gbFormat = Math.round(((kb / 1000000) + Number.EPSILON) * 100) / 100;
console.log(gbFormat);

Convert exponential notation of number (e+) to 10^ in JavaScript

I have a script, where I can convert gigs to megs to kilobytes to bytes to bits.
After that it uses the .toExponential function to turn it into scientific notation.
But I want it to change into an exponent, instead of it being +e# I want it to be ^#, any way I can change it to print that way instead, if not, anyway I can alter the string to change +e to ^?
Code:
console.log('calculator');
const gigabytes = 192;
console.log(`gigabytes equals ${gigabytes}`);
var megabytes = gigabytes * 1000;
console.log(`megabytes = ${megabytes}`);
var kilabytes = megabytes * 1000;
console.log (`kilabytes = ${kilabytes}`);
bytes = kilabytes * 1000;
console.log(`bytes = ${bytes}`);
bites = bytes * 8;
console.log(`bites are equal to ${bites}`);
console.log (bites.toExponential());
You can use .replace:
const bytes = '1.536e+12'
console.log(convert(bytes))
const inputs = [
'1.536e+12',
'1.536e-12',
'123',
'-123',
'123.456',
'-123.456',
'1e+1',
'1e-1',
'0e+0',
'1e+0',
'-1e+0'
]
function convert(value) {
return value.replace(/e\+?/, ' x 10^')
}
inputs.forEach(i => console.log(convert(i)))
You can just replace e+ with ^ using replace
console.log('calculator');
const gigabytes = 192;
console.log(`gigabytes equals ${gigabytes}`);
var megabytes = gigabytes * 1000;
console.log(`megabytes = ${megabytes}`);
var kilabytes = megabytes * 1000;
console.log (`kilabytes = ${kilabytes}`);
bytes = kilabytes * 1000;
console.log(`bytes = ${bytes}`);
bites = bytes * 8;
console.log(`bites are equal to ${bites}`);
console.log (bites.toExponential().replace(/e\+/g, '^'));
Instead of using
console.log(bites.toExponential);
You may need to use
bites = bites.toExponential;
console.log(bites.replace(“e+”, “*10^”);
Hope this helped!

Best way to download depth data in javascript?

I am making a Three.js application that needs to download some depth data. The data consist of 512x256 depth entries, stored in a compressed binary format with the precision of two bytes each. The data must be readable from the CPU, so I cannot store the data in a texture. Floating point textures is not supported on many browsers anyway, such as Safari on iOS.
I have this working in Unity, but I am not sure how to go about downloading compressed depth like this using javascript / three.js. I am new to javascript, but seems it has limited support for binary data handling and compression.
I was thinking of switching to a textformat, but then memory footprint and download size is a concern. The user could potentially have to load hundreds of these depth buffers.
Is there a better way to download a readable depth buffer?
You can download a file as binary data with fetch and async/await
async function doIt() {
const response = await fetch('https://webglfundamentals.org/webgl/resources/eye-icon.png');
const arrayBuffer = await response.arrayBuffer();
// the data is now in arrayBuffer
}
doIt();
After that you can make TypedArray views to view the data.
async function doIt() {
const response = await fetch('https://webglfundamentals.org/webgl/resources/eye-icon.png');
const arrayBuffer = await response.arrayBuffer();
console.log('num bytes:', arrayBuffer.byteLength);
// arrayBuffer is now the binary data. To access it make one or more views
const bytes = new Uint8Array(arrayBuffer);
console.log('first 4 bytes:', bytes[0], bytes[1], bytes[2], bytes[3]);
const decoder = new TextDecoder();
console.log('bytes 1-3 as unicode:', decoder.decode(bytes.slice(1, 4)));
}
doIt();
As for a format for depth data that's really up to you. Assuming your format was just 16bit values representing ranges of depths from min to max
uint32 width
uint32 height
float min
float max
uint16 data[width * height]
Then after you've loaded the data you can use either muliplte array views.
const uint32s = new Uint32Array(arrayBuffer);
const floats = new Float32Array(arrayBuffer, 8); // skip first 8 bytes
const uint16s = new Uint16Array(arrayBuffer, 16); // skip first 16 bytes
const width = uint32s[0];
const height = uint32s[1];
const min = floats[0];
const max = floats[1];
const range = max - min;
const depthData = new Float32Array(width * height);
for (let i = 0; i < uint16s.length; ++i) {
depthData[i] = uint16s[i] / 0xFFFF * range + min;
}
If you care about endianness for some future world where there are any browsers running on big endian hardware, then you either write your own functions to read bytes and generate those values or you can use a DataView.
Assuming you know the data is in little endian format
const data = new DataView(arrayBuffer);
const width = data.getUint32(0, true);
const height = data.getUint32(4, true);
const min = data.getFloat32(8, true);
const max = data.getFloat32(12, true);
const range = max - min;
const depthData = new Float32Array(width * height);
for (let i = 0; i < uint16s.length; ++i) {
depthData[i] = data.getUint16(i * 2 + 16, true) / 0xFFFF * range + min;
}
Of you want more complex compression like a inflate/deflate file you'll need a library or to write your own.

How to handle the endianness with UInt8 in a DataView?

It seems like there is nothing to handle endianness when working with UInt8. For example, when dealing with UInt16, you can set if you want little or big endian:
dataview.setUint16(byteOffset, value [, littleEndian])
vs
dataview.setUint8(byteOffset, value)
I guess this is because endianness is dealing with the order of the bytes and if I'm inserting one byte at a time, then I need to order them myself.
So how do I go about handling endianness myself? I'm creating a WAVE file header using this spec: http://soundfile.sapp.org/doc/WaveFormat/
The first part of the header is "ChunkID" in big endian and this is how I do it:
dataView.setUint8(0, 'R'.charCodeAt());
dataView.setUint8(1, 'I'.charCodeAt());
dataView.setUint8(2, 'F'.charCodeAt());
dataView.setUint8(3, 'F'.charCodeAt());
The second part of the header is "ChunkSize" in small endian and this is how I do it:
dataView.setUint8(4, 172);
Now I suppose that since the endianness of those chunks is different then I should be doing something different in each chunk. What should I be doing different in those two instances?
Cheers!
EDIT
I'm asking this question, because the wav file I'm creating is invalid (according to https://indiehd.com/auxiliary/flac-validator/). I suspect this is because I'm not handling the endianness correctly. This is the full wave file:
const fs = require('fs');
const BITS_PER_BYTE = 8;
const BITS_PER_SAMPLE = 8;
const SAMPLE_RATE = 44100;
const NB_CHANNELS = 2;
const SUB_CHUNK_2_SIZE = 128;
const chunkSize = 36 + SUB_CHUNK_2_SIZE;
const blockAlign = NB_CHANNELS * (BITS_PER_SAMPLE / BITS_PER_BYTE);
const byteRate = SAMPLE_RATE * blockAlign;
const arrayBuffer = new ArrayBuffer(chunkSize + 8)
const dataView = new DataView(arrayBuffer);
// The RIFF chunk descriptor
// ChunkID
dataView.setUint8(0, 'R'.charCodeAt());
dataView.setUint8(1, 'I'.charCodeAt());
dataView.setUint8(2, 'F'.charCodeAt());
dataView.setUint8(3, 'F'.charCodeAt());
// ChunkSize
dataView.setUint8(4, chunkSize);
// Format
dataView.setUint8(8, 'W'.charCodeAt());
dataView.setUint8(9, 'A'.charCodeAt());
dataView.setUint8(10, 'V'.charCodeAt());
dataView.setUint8(11, 'E'.charCodeAt());
// The fmt sub-chunk
// Subchunk1ID
dataView.setUint8(12, 'f'.charCodeAt());
dataView.setUint8(13, 'm'.charCodeAt());
dataView.setUint8(14, 't'.charCodeAt());
// Subchunk1Size
dataView.setUint8(16, 16);
// AudioFormat
dataView.setUint8(20, 1);
// NumChannels
dataView.setUint8(22, NB_CHANNELS);
// SampleRate
dataView.setUint8(24, ((SAMPLE_RATE >> 8) & 255));
dataView.setUint8(25, SAMPLE_RATE & 255);
// ByteRate
dataView.setUint8(28, ((byteRate >> 8) & 255));
dataView.setUint8(29, byteRate & 255);
// BlockAlign
dataView.setUint8(32, blockAlign);
// BitsPerSample
dataView.setUint8(34, BITS_PER_SAMPLE);
// The data sub-chunk
// Subchunk2ID
dataView.setUint8(36, 'd'.charCodeAt());
dataView.setUint8(37, 'a'.charCodeAt());
dataView.setUint8(38, 't'.charCodeAt());
dataView.setUint8(39, 'a'.charCodeAt());
// Subchunk2Size
dataView.setUint8(40, SUB_CHUNK_2_SIZE);
// Data
for (let i = 0; i < SUB_CHUNK_2_SIZE; i++) {
dataView.setUint8(i + 44, i);
}
A single byte (uint8) doesn't have any endianness, endianness is a property of a sequence of bytes.
According to the spec you linked, the ChunkSize takes space for 4 bytes - with the least significant byte first (little endian). If your value is only one byte (not larger than 255), you would just write the byte at offset 4 as you did. If the 4 bytes were in big endian order, you'd have to write your byte at offset 7.
I would however recommend to simply use setUint32:
dataView.setUint32(0, 0x52494646, false); // RIFF
dataView.setUint32(4, 172 , true);
dataView.setUint32(8, 0x57415645, false) // WAVE

How to read an ArrayBuffer with binary data in "4 byte single"/floating point/IEEE 754 encoded data?

I need to loop over a binary file via an arrayBufferand retrieve sets of 1024 floating points. I'm doing this:
// chunk_size = 1024
// chunk_len = 48
// response_buffer = ArrayBuffer
// response_buffer.byteLength = 49152
for (i = chunk_len; i > 0; i -= 1) {
switch (i) {
case (chunk_len):
// create view from last chunk of 1024 out of 49152 total
float_buffer = new Float32Array(response_buffer, ((i - 1) * chunk_size));
// add_data(net_len, float_buffer);
break;
case 0:
break;
default:
float_buffer = new Float32Array(response_buffer, ((i - 1) * chunk_size)), chunk_size);
//add_data(net_len, float_buffer);
break;
}
}
My problem is if I call this on the first run for the end of my buffer:
// i - 1 = 47 * chunk_size
new Float32Array(response_buffer, ((i - 1) * chunk_size));
the same statement fails on the next run where I call:
new Float32Array(response_buffer, ((i - 1) * chunk_size), 1024);
Although I can read here, that
I can do this:
Float32Array Float32Array(
ArrayBuffer buffer,
optional unsigned long byteOffset,
optional unsigned long length
);
Question:
Why is my loop failing after declaring the first Float32Array view on my response_offer ArrayBuffer?
I think you have an extra ")" in the first line of your "default" case.
float_buffer = new Float32Array(response_buffer, ((i - 1) * chunk_size)), chunk_size);
Should be:
float_buffer = new Float32Array(response_buffer, ((i - 1) * chunk_size), chunk_size);
So. Finally understand... maybe this helps the next person wondering:
First off - I was all wrong in trying to read my data, which is 4 byte single format.
If I have an arrayBuffer with byteLength = 49182 this means there are that many entries in my array.
Since my array is 4 byte single format, I found out with some SO-help and searching that this is readable with getFloat32 AND that 4 entries comprise one "real" value
My data contains 3 measurements a 4000 data points stored in units of 1024 column by column.
So if I have 12000 data-points and 49182/4 = 12288 datapoints, I will have 288 empty data points at the end of my data structure.
So my binary data should be stored like this:
0 - 1024 a
1025 - 2048 a
2049 - 3072 a
3072 - 4000 [a
4001 - 4096 b]
4097 - 5120 b
5121 - 6144 b
6145 - 7168 b
7169 - 8000 [b
8001 - 8192 c]
8193 - 9216 c
9217 - 10240 c
10240 - 11264 c
11264 - 12000 [c
12000 - 12288 0]
My final snippet will contain 288 empty results, because 3x4000 datapoints in 1024 chunks will return some empty results
To read, I found a nice snippet here (dynamic high range rendering), which helped me to this:
// ...
raw_data = ...
data = new DataView(raw_data);
...
tmp_data = new Float32Array(byte_len / Float32Array.BYTES_PER_ELEMENT);
len = tmp_data.length;
// Incoming data is raw floating point values with little-endian byte ordering.
for (i = 0; i < len; i += 1) {
tmp_data[i] = data.getFloat32(i * Float32Array.BYTES_PER_ELEMENT, true);
}
Now I have a single array with which I can work and build my processing structure.

Categories

Resources