Flutter convert image to binary data - flutter

How can i covert Image file to binary data ?
I'm using a library call image_picker for pick the image from gallery or camera.
And I want to convert the image that I picked to binary data.
File image = await ImagePicker.pickImage(source: ImageSource.gallery)
(image as Image).toByteData // the method toByteData here is not pop up.

toByteData() method allows converting the image into a byte array. We need to pass the format in the format argument which specifies the format in which the bytes will be returned. It'll return the future that completes with binary data or error.
final pngByteData = await image.toByteData(format: ImageByteFormat.png);
ImageByteFormat enum contains the following constants.
png
rawRgba
rawUnmodified
values
For more information about ImageByteFormat, please have a look at this documentation.
Update : If you want to convert the image file into bytes. Then use readAsByte() method.
var bytes = await ImagePicker.pickImage(source: ImageSource.gallery).readAsBytes();
For converting image into a file, Check out this answer.

simply use this method
var bytes = await File('filename').readAsBytes();

You might want to consider using the toByteData method.
It converts an image object into an array of bytes.
It returns a future which returns a binary image data or an error if the encoding fails.
Here is the implementation from this website: https://api.flutter.dev/flutter/dart-ui/Image/toByteData.html
Future<ByteData> toByteData({ImageByteFormat format = ImageByteFormat.rawRgba}) {
return _futurize((_Callback<ByteData> callback) {
return _toByteData(format.index, (Uint8List encoded) {
callback(encoded?.buffer?.asByteData());
});
});
}
The format argument specifies in which encoding format the bytes will be returned in.
Hope this helps!

Related

Flutter how to display an image from base64

I am using an API that brings data like this:
"photos": [
{
"id": 6,
"name": "Seguridad",
"base64Image": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD...",
}
]
What I need to do is to display the photos in a screen in my App. I've searched how to do it but I kept having the same error message: Exception: Invalid Image Data. I've read that what I need to do is to encode my base64 String, then decode that and then use it on Image.Memory, like this:
String image = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD...';
var bs64 = base64.encode(utf8.encode(example));
Uint8List decodedImage = base64.decode(bs64);
// --------
Image.memory(decodedImage)
I've tried using different base64 strings but the error is always there. I appreciate any help with this.
Because you are not decoding base64 string.
You have to remove data:image/jpeg;base64, (comma included)
you have to remove that because that data:image/jpeg;base64, just indicates that the string is image data with jpeg format which is encoded as base64 string.
So, the actual base64 data starts after it and you have to decode that.

Decoding base64 string to image in flutter (Invalid character exception)

Basically I'm trying to convert a base64 jpeg image to normal image in flutter using
Image.memory(base64Decode(stringBase64))
the image initially used to be jp/2 format which isn't supported by flutter so i converted the jp/2 base64 string to bitmap in java and then to base64 string jpeg to be able to decode it in flutter using this code :
public static String encodeToBase64(Bitmap image)
{
Bitmap immagex=image;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
immagex.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);
return imageEncoded;
}
how ever when i try to decode this base64 string in flutter i'm getting this error
Invalid character (at character 77)
/9j/4AAQSkZJRgABAQAAAQABAAD/4gIoSUNDX1BST0ZJTEUAAQEAAAIYAAAAAAIQAABtbnRyUkdC
which is pointing to the last C in the given line.
i don't seem understand where does the issue come from since i can convert my base64 string to image online but in flutter it throws that exception every time
thank you very much #Jamesdlin for the solution that was given in the comments
The issue was due to whitespace in the base64 string , solved by using
base64.decode(photoBase64.replaceAll(RegExp(r'\s'), '')),
If your URI contains data after the comma as it is defined by RFC-2397. Dart's Uri class is based on RFC-3986, so you can't use it.
Split the string by a comma and take the last part of it:
String uri = 'data:image/gif;base64,...';
Uint8List _bytes = base64.decode(uri.split(',').last);
REFERENCE: https://stackoverflow.com/a/59015116/12382178

How to get file extension from base64 String in Flutter | Dart

I have a base64 string of a document from api. I want to know which extension/file format is that. Because if it is in jpg/jpeg/png i want to show it in image widget. Or if it is in pdf format i want to show it in PdfView widget. So is there any way to get file extension from base64. Is there any package for it?
If you have a base64 string you can detect file type by checking the first character of your base64 string:
'/' means jpeg.
'i' means png.
'R' means gif.
'U' means webp.
'J' means PDF.
I wrote a function for that:
String getBase64FileExtension(String base64String) {
switch (base64String.characters.first) {
case '/':
return 'jpeg';
case 'i':
return 'png';
case 'R':
return 'gif';
case 'U':
return 'webp';
case 'J':
return 'pdf';
default:
return 'unknown';
}
}
If you don't have the original filename, there's no way to recover it. That's metadata that's not part of the file's content, and base64 encoding operates only on the file's content. It'd be best if you could save the original filename.
If you can't, you can use package:mime to guess the MIME type of the file from a small amount of binary data. You could decode the first nĂ—4 characters from the base64 string (a valid base64 string must have a length that's a multiple of 4), decode it, and call lookupMimeType.
package:mime has a defaultMagicNumbersMaxLength value that you can use to compute n dynamically:
import 'dart:convert';
import 'package:mime/mime.dart' as mime;
String? guessMimeTypeFromBase64(String base64String) {
// Compute the minimum length of the base64 string we need to decode
// [mime.defaultMagicNumbersMaxLength] bytes. base64 encodes 3 bytes of
// binary data to 4 characters.
var minimumBase64Length = (mime.defaultMagicNumbersMaxLength / 3).ceil() * 4;
return mime.lookupMimeType(
'',
headerBytes: base64.decode(base64String.substring(0, minimumBase64Length)),
);
}
For the types that package:mime supports as of writing, mime.defaultMagicNumbersMaxLength is 12 (which translates to needing to decode the first 16 bytes from the base64 string).

format exception when using Image.memory to load base64 image in flutter

Now I am using this code to load a base64 image stream in flutter:
var foregroundImage;
if(counter.value.iconData != null && counter.value.iconData != "") {
Uint8List base64Decode(String source) => base64.decode(source);
Uint8List uint8list = base64Decode(counter.value.iconData);
foregroundImage = Image.memory(uint8list);
}else{
foregroundImage = defaultImage;
}
when the stream like this:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAACXElEQVR4XsWXTU8TURSGu/AHuOnMlMbYWorKt1sVKDGiIf4BdUUQXWHiAnDXlERd4oJ+4rbFFa5w1fYvNE0wuJIFf8E0bZr2OO+UO7T3ozMEO3OSd3PPued5Z+a2995AQBKaFtV1PfRB041KUAudBzWjbYquqDbmoofVy+zJc4RIJBI3NM1ImpP+ShpeS+iJ3mDwXCsikcjN3hOLk/+nwABrAG49uQdwJrAG3gReDV80aoF5AY/qo/jmTuqtCXNhYoXySa8EdiCoG1U+4ZWwFgIXv3MhyWtyaloYU8l9bejcNDD8T2Z27gGdnPyibrdLpcPvpBtjQg0TcsXSoVWLOZjL13BqwwA/aAsN/pydUX8cHf2QmsAYcv2RyWQpNj4h1PZLaUAGZ8GbkMHz+QKlUrv06fOXoSakBnh4s9mk4+Ofl93p0oQKvrz8hHK5vKVhJgQDMvjLV6+tHBqzOD39Tfcnp6Rw1D58tEDpdMbRxICBmdl5JZwJAMCnZ+aUcKbHC4uCiTuxuNpAsViym7VaLQHOFJ+45whXmdh4+05toHDwzW7Y6XRoc/O90FD1zfk6pqcrzymbzdkG1tbW1QbG43epXq/bjXkT14Unkym6HYmqDahMrL/ZGAlcakBmAmvhKvCVZ+7gSgMQM1Gr1QR4oXAg1DMtLiVcwyGlAQgmyuWyazi0vf3RNRxy3IxgolKtUqPRoL29r0Ke1+rqC9pPp2lra8cRHuxtRu6247HwLWFMJSMUFsbkMrdjLw+jvKwDie9HMt8Ppb4fyxG+X0wQvl7NWPh6Oe0PL6/n/wCHXSY6hk0RUwAAAABJRU5ErkJggg==
show error formatexception: invalid character:
when I am parse the stream in web, it could parse successfully. why would this happen? what should I do to fix it?
The problem is that the actual base64 encoded image is after the "base64," word.
Since base64 can not contain comma symbol - you can just split the string by it and take the last part:
counter.value.iconData.split(',').last
base64Decode decodes pure base64, remove data:image/png;base64, and give rest to base64Decode function

base64.encode Not Encoding The whole File , Missing Parts file Encoding Flutter Dart ERROR

i am using following code to encode PDF file to base 64
File f = new File(_path);
// String base64pdf = base64Encode(f.readAsBytesSync());
String base64pdf = base64.encode(f.readAsBytesSync());
String fileName = _fileName;
print('base64pdf: '+base64pdf);
I tried to encode the pdf file on here: encoding website
the result from the website shows that the base64 encoder inside flutter(dart) is trimming a big section of the String Generated and give only little first part of it ?
how to solve that , is this related with byte type?
RaisedButton(
onPressed: () async {
List<int> imageBytes = await sampleImage.readAsBytes();
base64Image = base64Encode(imageBytes);
print(base64Image);},),
SizedBox(height: 30,),
Image.memory(base64Decode(base64Image)),
Base 64 code in my git hub repo