I have some Uint8lists and I want to save them as jpg files. Can anyone help?
Asked
Active
Viewed 2.1k times
16
-
`File` class from `dart.io` has methods to save that list – pskink Dec 05 '20 at 07:53
-
I don't wanna save the list – M.Taha Basiri Dec 05 '20 at 07:59
-
*"and I wanna save them in storage"* - so what do you want to do actually? – pskink Dec 05 '20 at 08:00
-
sorry for the bad explanation! edited now. – M.Taha Basiri Dec 05 '20 at 08:02
-
question is hard to understand. explain your question better – Cem Kaan Dec 05 '20 at 08:07
-
Is it understandable now?! – M.Taha Basiri Dec 05 '20 at 10:23
2 Answers
23
By 'storage', do you mean write to a file? You don't really need "flutter" to do this. Just use the libraries provided by dart. Here is an example of downloading my gravatar which you can get as Uin8List
and then saving it to a file.
import 'dart:io';
import 'dart:typed_data';
import 'package:http/http.dart' as http;
void main() {
http.get('https://www.gravatar.com/avatar/e944138e1114aefe4b08848a46465589').then((response) {
Uint8List bodyBytes = response.bodyBytes;
File('my_image.jpg').writeAsBytes(bodyBytes);
});
}

lsiu
- 2,297
- 1
- 17
- 20
-
1'my_image.jpg', where it will be stored? How can we set specific folder to store the file? – djalmafreestyler May 04 '21 at 11:46
-
2You can save to a specific path like `final dir = await getExternalStorageDirectory(); final myImagePath = dir!.path + "/myimg.png"; File imageFile = File(myImagePath); if(! await imageFile.exists()){ imageFile.create(recursive: true); } imageFile.writeAsBytes(image);` – Maseed May 17 '21 at 17:37
-
@djalmafreestyler - it will be stored at the "current working directory" which you ran the program. – lsiu May 19 '21 at 12:57
-
2Note that this only works because the Uint8List is already storing image data in JPEG format. As such, the question doesn't answer how to save RAW image bytes (which is what I came here for), as these would need to be encoded as PNG or JPEG or similar, first. I believe the missing step here is: `ByteData byteData = await image.toByteData(format: ImageByteFormat.png); Uint8List pngBytes = byteData.buffer.asUint8List();` where `image` is from the `dart:ui` package. – LZM Aug 15 '22 at 17:56
2
Here is a simple and short solution of your problem. Use this line in your code as I did:
"SettableMetadata(contentType: "image/jpeg"),"
Code:
if (kIsWeb) {
await ref.putData(
await imageFile.readAsBytes(),
SettableMetadata(contentType: "image/jpeg"),
);
url = await ref.getDownloadURL();
}

Jeremy Caney
- 7,102
- 69
- 48
- 77

Rana Ali Ashar
- 21
- 1