You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
`ArrayBuffer`and views are a part of ECMA standard, a part of JavaScript.
3
+
Gli `ArrayBuffer`e i visualizzatori fanno parte dello standard ECMA; sono quindi parte di JavaScript.
4
4
5
-
In the browser, there are additional higher-level objects, described in [File API](https://www.w3.org/TR/FileAPI/), in particular`Blob`.
5
+
Nei browser, abbiamo a disposizione degli oggetti più ad alto livello, descritti in [File API](https://www.w3.org/TR/FileAPI/), in particolare l'oggetto`Blob`.
6
6
7
-
`Blob`consists of an optional string`type` (a MIME-type usually), plus `blobParts` -- a sequence of other `Blob` objects, strings and`BufferSource`.
7
+
L'oggetto `Blob`consiste di una stringa opzionale`type` (solitamente di tipo MIME), e di `blobParts`, una sequenza di oggetti `Blob`, stringhe e`BufferSource`.
8
8
9
9

10
10
11
-
The constructor syntax is:
11
+
La sintassi da utilizzare per costruire l'oggetto:
12
12
13
13
```js
14
14
newBlob(blobParts, options);
15
15
```
16
16
17
-
-**`blobParts`**is an array of `Blob`/`BufferSource`/`String` values.
18
-
-**`options`**optional object:
19
-
-**`type`** -- `Blob` type, usually MIME-type, e.g. `image/png`,
20
-
-**`endings`** -- whether to transform end-of-line to make the `Blob`correspond to current OS newlines (`\r\n`or`\n`). By default `"transparent"` (do nothing), but also can be `"native"` (transform).
17
+
-**`blobParts`**è un array di valori di tipo `Blob`/`BufferSource`/`String`.
18
+
-**`options`**oggetto opzionale:
19
+
-**`type`**, di tipo `Blob`, solitamente di tipo MIME, e.g. `image/png`,
20
+
-**`endings`**, se trasformare il carattere di fine riga per far sì che il `Blob`contenga il carattere nuova riga del Sistema Operativo corrente (`\r\n`o`\n`). Di default è `"transparent"` (non fa nulla), ma può assumere il valore `"native"` (effettua la trasformazione).
21
21
22
-
For example:
22
+
Ad esempio:
23
23
24
24
```js
25
-
//create Blob from a string
25
+
//creiamo un Blob partendo da una stringa
26
26
let blob =newBlob(["<html>…</html>"], {type:'text/html'});
27
-
//please note: the first argument must be an array [...]
27
+
//da notare: il primo argomento deve essere un array [...]
28
28
```
29
29
30
30
```js
31
-
//create Blob from a typed array and strings
32
-
let hello =newUint8Array([72, 101, 108, 108, 111]); // "Hello" in binary form
31
+
//creiamo un Blob partendo da un TypedArray e da due stringhe
32
+
let hello =newUint8Array([72, 101, 108, 108, 111]); // "Hello" nella forma binaria
33
33
34
34
let blob =newBlob([hello, '', 'world'], {type:'text/plain'});
-**`byteStart`** -- the starting byte, by default 0.
45
-
-**`byteEnd`** -- the last byte (exclusive, by default till the end).
46
-
-**`contentType`** -- the`type`of the new blob, by default the same as the source.
44
+
-**`byteStart`** - il byte di partenza, di default 0.
45
+
-**`byteEnd`** - l'ultimo byte (escluso, fino alla fine di default).
46
+
-**`contentType`** - il`type`del nuovo blob, di default lo stesso di quello di origine.
47
47
48
-
The arguments are similar to `array.slice`, negative numbers are allowed too.
48
+
Gli argomenti sono simili al metodo `array.slice`; sono ammessi anche i valori negativi.
49
49
50
-
```smart header="`Blob`objects are immutable"
51
-
We can't change data directly in a `Blob`, but we can slice parts of a `Blob`, create new `Blob` objects from them, mix them into a new`Blob` and so on.
Non possiamo modificare direttamente i dati di un `Blob`, ma possiamo estrarne delle parti, utilizzarle per creare nuovi `Blob`, fonderle insieme in un unico`Blob`, e molto altro.
52
52
53
-
This behavior is similar to JavaScript strings: we can't change a character in a string, but we can make a new corrected string.
53
+
Questo comportamento è simile alle stringhe JavaScript: non possiamo modificare direttamente un carattere in una stringa, ma possiamo creare una nuova stringa modificata.
54
54
```
55
55
56
-
## Blob as URL
56
+
## Blob come URL
57
57
58
-
A Blob can be easily used as a URL for `<a>`, `<img>` or other tags, to show its contents.
58
+
Un `Blob` può essere utilizzato facilmente come URL per `<a>`, `<img>` o altri tag, per mostrarne i contenuti.
59
59
60
-
Thanks to `type`, we can also download/upload `Blob` objects, and the `type` naturally becomes `Content-Type` in network requests.
60
+
Grazie alla proprietà `type`, possiamo anche effettuare download/upload di `Blob`, ed il `type`, naturalmente, diventerà il `Content-Type` nelle richieste network.
61
61
62
-
Let's start with a simple example. By clicking on a link you download a dynamically-generated `Blob` with `hello world` contents as a file:
62
+
Iniziamo con un semplice esempio. Cliccando sul link verrà scaricato come file un `Blob` generato dinamicamente, contenente `hello world`:
63
63
64
64
```html run
65
-
<!-- download attribute forces the browser to download instead of navigating -->
65
+
<!-- l'attributo download forza il browser ad effettuare il download anziché navigare -->
For each URL generated by`URL.createObjectURL`the browser stores a URL -> `Blob` mapping internally. So such URLs are short, but allow to access the`Blob`.
100
+
Per ogni URL generato da`URL.createObjectURL`il browser memorizza in una mappa interna la coppia URL -> `Blob`. Così da rendere questi URL più corti, ma in grado di fornire comunque l'accesso al`Blob`.
101
101
102
-
A generated URL (and hence the link with it) is only valid within the current document, while it's open. And it allows to reference the `Blob`in `<img>`, `<a>`, basically any other object that expects a URL.
102
+
Un URL generato (e quindi anche il suo link) è valido solamente all'interno del `document` corrente, finché questo rimane aperto. E può essere utilizzato per fare riferimento al `Blob`nei tag `<img>`, `<a>`, e qualsiasi altro oggetto che accetta un URL.
103
103
104
-
There's a side-effect though. While there's a mapping for a `Blob`, the `Blob`itself resides in the memory. The browser can't free it.
104
+
Abbiamo però un effetto collaterale. Poiché i `Blob` sono mappati, ogni oggetto `Blob`risiede in memoria. Quindi il browser non potrà liberarla.
105
105
106
-
The mapping is automatically cleared on document unload, so `Blob`objects are freed then. But if an app is long-living, then that doesn't happen soon.
106
+
La mappa verrà automaticamente ripulita al momento dell'`unload` del `document`, quindi gli oggetti di `Blob`verranno eliminati in quel momento. Ma nel caso di applicazioni che "vivono a lungo", questa pulizia non avverrà presto.
107
107
108
-
**So if we create a URL, that `Blob`will hang in memory, even if not needed any more.**
108
+
**Quindi se creiamo un URL, il relativo `Blob`rimarrà in memoria, anche se non è più necessario.**
109
109
110
-
`URL.revokeObjectURL(url)`removes the reference from the internal mapping, thus allowing the `Blob` to be deleted (if there are no other references), and the memory to be freed.
110
+
`URL.revokeObjectURL(url)`rimuove il riferimento dalla mappa interna, in questo modo sarà possibile eliminare i `Blob` (se questi non possiedono più alcun riferimento), e liberare la memoria.
111
111
112
-
In the last example, we intend the `Blob`to be used only once, for instant downloading, so we call`URL.revokeObjectURL(link.href)`immediately.
112
+
Nell'ultimo esempio, il nostro intento era di utilizzare il `Blob`solamente una volta, per il download istantaneo, quindi possiamo invocare`URL.revokeObjectURL(link.href)`immediatamente.
113
113
114
-
In the previous example with the clickable HTML-link, we don't call `URL.revokeObjectURL(link.href)`, because that would make the`Blob`url invalid. After the revocation, as the mapping is removed, the URL doesn't work any more.
114
+
Nell'esempio precedente, con il link HTML cliccabile, non invochiamo `URL.revokeObjectURL(link.href)`, poiché questo renderebbe l'URL del`Blob`invalido. Dopo averlo revocato, la coppia URL-`Blob` verrà rimossa dalla mappa, e l'URL non funzionerà più.
115
115
116
-
## Blob to base64
116
+
## Da Blob a base64
117
117
118
-
An alternative to`URL.createObjectURL`is to convert a `Blob`into a base64-encoded string.
118
+
Un alternativa a`URL.createObjectURL`è quella di convertire un `Blob`in una stringa codificata in base 64.
119
119
120
-
That encoding represents binary data as a string of ultra-safe "readable" characters with ASCII-codes from 0 to 64. And what's more important -- we can use this encoding in "data-urls".
120
+
Questo tipo di encoding rappresenta i dati binari come una stringa leggibile di caratteri ultra-safe, con caratteri ASCII-code da 0 a 64. E, molto più importante, possiamo utilizzare questo encoding nei "data-urls".
121
121
122
-
A[data url](mdn:/http/Data_URIs)has the form `data:[<mediatype>][;base64],<data>`. We can use such urls everywhere, on par with "regular" urls.
122
+
Un[data url](mdn:/http/Data_URIs)è rappresentato nella forma `data:[<mediatype>][;base64],<data>`. Possiamo utilizzare questi URL ovunque, in alternativa agli URL "regolari".
The browser will decode the string and show the image: <imgsrc="data:image/png;base64,R0lGODlhDAAMAKIFAF5LAP/zxAAAANyuAP/gaP///wAAAAAAACH5BAEAAAUALAAAAAAMAAwAAAMlWLPcGjDKFYi9lxKBOaGcF35DhWHamZUW0K4mAbiwWtuf0uxFAgA7">
130
+
Il browser decodificherà la stringa e mostrerà l'immagine: <imgsrc="data:image/png;base64,R0lGODlhDAAMAKIFAF5LAP/zxAAAANyuAP/gaP///wAAAAAAACH5BAEAAAUALAAAAAAMAAwAAAMlWLPcGjDKFYi9lxKBOaGcF35DhWHamZUW0K4mAbiwWtuf0uxFAgA7">
131
131
132
132
133
-
To transform a`Blob`into base64, we'll use the built-in `FileReader` object. It can read data from Blobs in multiple formats. In the [next chapter](info:file)we'll cover it more in-depth.
133
+
Per trasformare un`Blob`in base64, utilizzeremo l'oggetto integrato `FileReader`. Può leggere dati da un Blob in diversi formati. Nel [prossimo capitolo](info:file)lo vedremo più in dettaglio.
134
134
135
-
Here's the demo of downloading a blob, now via base-64:
135
+
Qui vediamo un esempio di download di un Blob, utilizzando la base-64:
136
136
137
137
```js run
138
138
let link =document.createElement('a');
@@ -142,7 +142,7 @@ let blob = new Blob(['Hello, world!'], {type: 'text/plain'});
142
142
143
143
*!*
144
144
let reader =newFileReader();
145
-
reader.readAsDataURL(blob); //converts the blob to base64 and calls onload
145
+
reader.readAsDataURL(blob); //convertiamo il Blob in base64 e invochiamo onload
Both ways of making a URL of a `Blob`are usable. But usually `URL.createObjectURL(blob)`is simpler and faster.
154
+
Entrambi i modi per costruire un URL corrispondente ad un `Blob`sono utilizzabili. Solitamente `URL.createObjectURL(blob)`è più semplice e veloce.
155
155
156
-
```compare title-plus="URL.createObjectURL(blob)" title-minus="Blob to data url"
157
-
+ We need to revoke them if care about memory.
158
-
+ Direct access to blob, no "encoding/decoding"
159
-
- No need to revoke anything.
160
-
- Performance and memory losses on big `Blob` objects for encoding.
156
+
```compare title-plus="URL.createObjectURL(blob)" title-minus="Da Blob a data url"
157
+
+ Dobbiamo revocarli per mantenere pulita la memoria.
158
+
+ Accesso diretto al Blob, no "encoding/decoding".
159
+
- Non dobbiamo ricordarci di revocare nulla.
160
+
- Abbiamo perdite di performance e memoria su grandi oggetti di tipo `Blob` a causa dell'encoding.
161
161
```
162
162
163
-
## Image to blob
163
+
## Da image a blob
164
164
165
-
We can create a `Blob`of an image, an image part, or even make a page screenshot. That's handy to upload it somewhere.
165
+
Possiamo creare un `Blob`relativo ad un immagine, o addirittura fare uno screenshot della pagina. Può essere molto utile se abbiamo la necessità di caricarla da qualche parte.
166
166
167
-
Image operations are done via `<canvas>` element:
167
+
Le operazioni sulle immagini sono fatte tramite l'elemento `<canvas>`:
168
168
169
-
1.Draw an image (or its part) on canvas using[canvas.drawImage](mdn:/api/CanvasRenderingContext2D/drawImage).
170
-
2.Call canvas method [.toBlob(callback, format, quality)](mdn:/api/HTMLCanvasElement/toBlob)that creates a `Blob`and runs `callback`with it when done.
169
+
1.Disegniamo un'immagine (o una usa parte) su un canvas utilizziando[canvas.drawImage](mdn:/api/CanvasRenderingContext2D/drawImage).
170
+
2.Invochiamo il metodo sui canvas [.toBlob(callback, format, quality)](mdn:/api/HTMLCanvasElement/toBlob)il quale crea un `Blob`ed esegue la `callback`al termine dell'operazione.
171
171
172
-
In the example below, an image is just copied, but we could cut from it, or transform it on canvas prior to making a blob:
172
+
Nell'esempio sotto, un'immagine è appena stata copiata, ma potremmo volerla tagliare, o trasformarla utilizzando un canvas, prima di creare un blob:
173
173
174
174
```js run
175
-
//take any image
175
+
//prendiamo un'immagine
176
176
let img =document.querySelector('img');
177
177
178
-
//make <canvas> of the same size
178
+
//creiamo un <canvas> delle stesse dimensioni
179
179
let canvas =document.createElement('canvas');
180
180
canvas.width=img.clientWidth;
181
181
canvas.height=img.clientHeight;
182
182
183
183
let context =canvas.getContext('2d');
184
184
185
-
//copy image to it (this method allows to cut image)
185
+
//ci copiamo l'immagine al suo interno (questo metodo consente di tagliare l'immagine)
186
186
context.drawImage(img, 0, 0);
187
-
//we can context.rotate(), and do many other things on canvas
187
+
//possiamo context.rotate(), ed effettuare molte altre operazioni tramite il canvas
188
188
189
-
// toBlob is async operation, callback is called when done
189
+
190
+
// toBlob è un'operazione asincrona, verrà invocata la funzione di callback al termine
190
191
canvas.toBlob(function(blob) {
191
-
// blob ready, download it
192
+
//il blob è pronto, lo scarichiamo
192
193
let link =document.createElement('a');
193
194
link.download='example.png';
194
195
195
196
link.href=URL.createObjectURL(blob);
196
197
link.click();
197
198
198
-
//delete the internal blob reference, to let the browser clear memory from it
199
+
//cancelliamo il riferimento interno al blob, per consentire al browser di rimuoverlo dalla memoria
199
200
URL.revokeObjectURL(link.href);
200
201
}, 'image/png');
201
202
```
202
203
203
-
If we prefer `async/await`instead of callbacks:
204
+
Se preferiamo, possiamo utilizzare `async/await`al posto delle callback:
204
205
```js
205
206
let blob =awaitnewPromise(resolve=>canvasElem.toBlob(resolve, 'image/png'));
206
207
```
207
208
208
-
For screenshotting a page, we can use a library such as <https://github.com/niklasvh/html2canvas>. What it does is just walks the page and draws it on`<canvas>`. Then we can get a `Blob` of it the same way as above.
209
+
Per effettuare lo screenshot di una pagina, possiamo utilizzare una libreria come <https://github.com/niklasvh/html2canvas>. Ciò che fa è semplicemente attraversare la pagina e disegnarla su un`<canvas>`. Successivamente possiamo ottenere un `Blob`, come descritto sopra.
209
210
210
-
## From Blob to ArrayBuffer
211
+
## Da Blob a ArrayBuffer
211
212
212
-
The `Blob`constructor allows to create a blob from almost anything, including any`BufferSource`.
213
+
Il costruttore del `Blob`consente di creare un `Blob` per qualsiasi cosa, inclusi i`BufferSource`.
213
214
214
-
But if we need to perform low-level processing, we can get the lowest-level `ArrayBuffer` from it using`FileReader`:
215
+
Se abbiamo bisogno di eseguire operazioni di basso livello, possiamo ottenere il livello più basso, un `ArrayBuffer`, utilizzando`FileReader`:
While`ArrayBuffer`, `Uint8Array`and other `BufferSource`are "binary data", a[Blob](https://www.w3.org/TR/FileAPI/#dfn-Blob)represents "binary data with type".
233
+
Mentre`ArrayBuffer`, `Uint8Array`e gli altri `BufferSource`sono "dati binari", un[Blob](https://www.w3.org/TR/FileAPI/#dfn-Blob)rappresenta "un dato binario con tipo".
233
234
234
-
That makes Blobs convenient for upload/download operations, that are so common in the browser.
235
+
Questo rende i `Blob` convenienti per le operazioni di upload/download, che sono piuttosto comuni nei browser.
235
236
236
-
Methods that perform web-requests, such as [XMLHttpRequest](info:xmlhttprequest), [fetch](info:fetch)and so on, can work with `Blob`natively, as well as with other binary types.
237
+
I metodi che eseguono richieste web, come [XMLHttpRequest](info:xmlhttprequest), [fetch](info:fetch)e così via, sono in grado di operare con i `Blob`nativamente, come con tutti gli altri tipi di dato binari.
237
238
238
-
We can easily convert between`Blob`and low-level binary data types:
239
+
Possiamo convertire molto rapidamente da`Blob`a dati binari a basso livello:
239
240
240
-
-We can make a Blob from a typed array using `new Blob(...)` constructor.
241
-
-We can get back `ArrayBuffer`from a Blob using`FileReader`, and then create a view over it for low-level binary processing.
241
+
-Possiamo creare un `Blob` da un `TypedArray` utilizzando il costruttore `new Blob(...)`.
242
+
-Possiamo ricostruire un `ArrayBuffer`da un `Blob` utilizzando`FileReader`, e successivamente creare un visualizzatore per visualizzare ed elaborare i dati binari a basso livello.
0 commit comments