16

I have some Uint8lists and I want to save them as jpg files. Can anyone help?

Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393
M.Taha Basiri
  • 612
  • 1
  • 6
  • 14

2 Answers2

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
  • 2
    You 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
  • 2
    Note 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