how to convert a file from file.path to base64 in flutter - flutter

I have used filepicker to choose file from internal storage:
Fresult = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: ['pdf', 'jpg'],
PlatformFile file = Fresult.files.first;
fiLeName=file.name.toString();
fiLePath=file.path.toString();
);
and to convert that file suppose a pdf to base64 I used
final bytes = io.File(fiLePath).readAsBytesSync();
String vbase= base64Encode(bytes);
When i print the base64 string which i have received and used an online converter to see if the file is corrupted or not. but fortunately the result is corrupted.
Is there any way to do it?
or have I done it wrong?
please help me with it

Related

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

Convert base64 to image and save it in temp folder flutter

I have base64 string of image like /9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAA0JCgsKCA0LCgsODg0PEyAVExISEyccHhcgLikxMC4pLSwzOko+MzZGNywtQFdBRkxOUlNSMj5aYVpQYEpRUk//....
What I want to do is to save this image in temp folder and use that file address for showing image in my app.
How can I do that?
import 'package:path_provider/path_provider.dart' as syspaths;
Decode your base64 string to bytes in memory.
Uint8List bytes = base64.decode(base64String);
Make a temporary directory and file on that directory
final appDir = await syspaths.getTemporaryDirectory();
File file = File('${appDir.path}/sth.jpg');
Write converted bytes on a file
await file.writeAsBytes(bytes)
then we can
Image.file(file);
OR ALTERNATIVELY
Decode your base64 string to bytes in memory.
Uint8List bytes = base64.decode(base64String);
then we can
Image.memory(bytes)

Read specific chunk of bytes in flutter / dart

Is there any way to read just a chunk of bytes from a file in flutter not the whole data?
For example from byte 50 to 150
I found the solution myself:
Directory directory = await getApplicationDocumentsDirectory();
File file = File('${directory.path}/myfile.txt');
RandomAccessFile raf= file.openSync(mode: FileMode.read);
raf.setPositionSync(50);
Uint8List data = raf.readSync(100);

Flutter convert image to binary data

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!

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