How to convert image from path to Base64 in flutter? - flutter

I'm trying to capture an image, then send path of the image to a function that returns the image in Base64. For capturing an image I'm using the example on Flutter website.
Future _takePhoto(BuildContext context) async {
try {
await _initializeControllerFuture;
final path = join(
(await getTemporaryDirectory()).path,
'${DateTime.now()}.png',
);
await _cameraController.takePicture(path);
setState(() {
_imagePath = path;
});
} catch (e) {
print(e);
}
}
It's working well. I can see the captured image in widget Image.file(File(_imagePath))
The problem starts when I'm trying to convert the image into Base64.
File file = File(_imagePath);
final _imageFile = ImageProcess.decodeImage(
file.readAsBytesSync(),
);
String base64Image = base64Encode(ImageProcess.encodePng(_imageFile));
print(base64Image);
I copy and paste the printed message into an online tool that generates an image from Base64 and either it's all black or there is tiny top layer of the image and the rest is black.

print function did not print everything.
you can see full result with debug mode
and copy paste full result in debug mode to online tool

This should print your image as a base64 string
import 'dart:typed_data';
import 'dart:async';
import 'dart:io';
import 'dart:convert';
File file = File(_imagePath);
Uint8List bytes = file.readAsBytesSync();
String base64Image = base64Encode(bytes);
print(base64Image);

To show base64 print:
import 'dart:developer' as developer;
developer.log(
'log me',
name: 'my.app.category',
error: jsonEncode(base64Image),
);

Related

Using Flutter Camera package, how do I convert a photo to a base64 string?

Using the Flutter Camera package (v0.9.4+5), how do I convert a captured photo into a base64 string?
I believe the following code will work, but welcome to any thoughts on how the code can be improved.
import 'dart:convert' as convert;
void capturePhoto() async {
// Note: `controller` being initialized as shown in readme
// https://pub.dev/packages/camera#example
XFile photo = await controller.takePicture();
List<int> photoAsBytes = await photo.readAsBytes();
String photoAsBase64 = convert.base64Encode(photoAsBytes);
}
Try this.
var image = await ImagePicker.pickImage(source: ImageSource.gallery);
final bytes = Io.File(image.path).readAsBytesSync();
String img64 = base64Encode(bytes);
print (img64);

Send picture to server api with post request [FLUTTER]

I want to take picture, which should contain just a few letters, with my phone and then send it to a server where it will convert the picture to a text string.
My imported packages:
import 'dart:io';
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:image_picker/image_picker.dart';
I currently have this camera function:
// Camera implementation
File? _image;
final ImagePicker _picker = ImagePicker();
Future getImage() async {
final image = await _picker.pickImage(source: ImageSource.camera);
setState(() {
_image = File(image!.path);
});
}
And I use it in this button:
// Camera button
ElevatedButton.icon(
onPressed: getImage,
icon: const Icon(Icons.camera_alt_rounded),
label: const Text('Scan'),
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(Colors.green[500]),
textStyle: MaterialStateProperty.all(const TextStyle(fontSize: 26)),
)
)
I have tested to just send some data to jsonplaceholder and it works, but I can't get understand how to implement it to a picture that should be sent to my server.
// Send Data to the Server (TEST VERSION)
postDataTest() async{
try{
var response = await http.post(Uri.parse("https://jsonplaceholder.typicode.com/posts"),
body: {
"id": 1.toString(),
"name": "Hax",
}
);
print(response.body);
} catch(e){
print(e);
}
}
TLDR. I want to take a picture and send it to a server.
Use multipart
Upload(File img) async {
var uri = Uri.parse(uploadURL);
var request = new http.MultipartRequest("POST", uri);
request.files.add( new http.MultipartFile.fromBytes("file", img.readAsBytesSync(), filename: "Photo.jpg", contentType: new MediaType("image", "jpg")));
var response = await request.send();
print(response.statusCode);
response.stream.transform(utf8.decoder).listen((value) {
print(value);
});
}
Picture to text for archive this you need to convert image into base64. Check this link
However, it's generally a bad idea to store large blobs of binary data in your database. you will end up wasting bandwidth transmitting data.it also decrease mobile app performance while you read large blob data. you don't need as well as unnecessary encoding and decoding.
You can send picture to server using multipart api request.
So you can archive mutipart request with api in various packages
https - dart documentation
Dio
You can also check multipartRequest on Stackoverflow.
I managed to solve it with this function:
// Upload camera photo to server
Future uploadImage() async {
final uri = Uri.parse("url to the server");
var request = http.MultipartRequest('POST', uri);
var takenPicture = await http.MultipartFile.fromPath("image", _image!.path);
request.files.add(takenPicture);
var response = await request.send();
if(response.statusCode == 200){
print('Image uploaded!');
} else{
print('Image not uploaded');
}
}
file.path is path of image u can use file picker or image picker in flutter
baseimage = "";
if(file.path != '') {
List<int> imageBytes = file.readAsBytesSync();
baseimage = base64Encode(imageBytes);
}
send image as a string and decode base64 in your server
laravel exemple using spatie media
if (isset($request->image)) {
$fiche_client->addMediaFromBase64($request->image)
->usingFileName(Str::random(10).'.png')
->toMediaCollection('magasin');
}

Flutter how to convery image in base64 string and show image again

I am simply picking image from image_picker package like this
_imgFromCamera() async {
File image = await ImagePicker.pickImage(
source: ImageSource.camera, imageQuality: 50
);
final bytes = image.readAsBytesSync();
String base64Image = base64Encode(bytes);
print(base64Image);
setState(() {
_image = image;
});
}
You can see I have convert image in the string also. I need to know how can I show this string as an image? Because I save this string on other page now I need to show is an image
You can convert the base64 string into a file using
import `dart:covert`
Uint8List bytes = base64decode(_base64);
and then display it using the widget
Image.memory(bytes),
You can just write it in a single line but I split it for the sake of readability
Image.memory(base64Decode(base64String));

Printing Image with Bluetooth Printer in Flutter

I want to print the screenshot image of first page in Flutter. So far I have come up to the part where I need to parse that image into function that would print it, here is the code:
FIRST PAGE
_screenshot() {
screenshotController.capture().then((File image) {
//Capture Done
setState(() {
_screenshot = image;
});
print('Successful Screenshot => $_screenshot');
Navigator.push(
context, MaterialPageRoute(builder: (context) => Print(_screenshot)));}
So this is the page that screenshots that whole page and pushes that screenshot to the second screen. Here is the second screen:
SECOND PAGE
class Print extends StatefulWidget {
final File screenshot;
Print(this.screenshot);
#override
_PrintState createState() => _PrintState();
}
Here I initialize that image from the first page, and then I created the function for printing that should print the ticket, but I am getting an error:
Future<Ticket> _ticket(PaperSize paper) async {
final ticket = Ticket(paper);
//this is a working option, but I don't want to load from assets, but load screenshot file from first page
//final ByteData data = await rootBundle.load(assets/store.png');
final File img = await rootBundle.load(widget.screenshot); //here parse the image from first page **ERROR HERE**
final Uint8List bytes = data.buffer.asUint8List();
final Image image = decodeImage(bytes);
ticket.image(image);
return ticket;
}
I am getting an error that Byte data cannot be assigned to variable type File which I understand, but how would I go around making this work? I am using the esc_pos_bluetooth: ^0.2.8 library for bluetooth printing.
You don't need to load data from rootBundle instead, you can use readAsBytes() class method from File class which returns Uint8List.
Uint8List bytes = await widget.screenshot.readAsBytes();
Your final code should look like.
Future<Ticket> _ticket(PaperSize paper) async {
final ticket = Ticket(paper);
final Uint8List bytes = await widget.screenshot.readAsBytes();
final Image image = decodeImage(bytes);
ticket.image(image);
return ticket;
}

Flutter - Network Image to File

I have an Image URL like "https://example.com/xyz.jpg". Now I want to put the image in a File type variable;
Something along these lines:
File f = File("https://example.com/xyz.jpg");
The whole point is to get the image from the given URL and save it as a File variable. How can I do so?
I searched for many solutions on the internet but there was no straightforward way to do so.
PS: I could have missed something where the question was similarly answered so please let me know the link where I can find it.
Edit: I am using the File type variable to pass it in the share function.
This is the library that I am using.
Here is my current on share button click code
if (file != null) {
ShareExtend.share(file.path, "image",
sharePanelTitle: "share image title",
subject: "share image subject");
}
Thanks for your help.
You need to download image and create an empty file then fill the file with image data:
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
Future<File> _fileFromImageUrl() async {
final response = await http.get(Uri.parse('https://example.com/xyz.jpg)');
final documentDirectory = await getApplicationDocumentsDirectory();
final file = File(join(documentDirectory.path, 'imagetest.png'));
file.writeAsBytesSync(response.bodyBytes);
return file;
}
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
Future<File> getImage({required String url}) async {
/// Get Image from server
final Response res = await Dio().get<List<int>>(
url,
options: Options(
responseType: ResponseType.bytes,
),
);
/// Get App local storage
final Directory appDir = await getApplicationDocumentsDirectory();
/// Generate Image Name
final String imageName = url.split('/').last;
/// Create Empty File in app dir & fill with new image
final File file = File(join(appDir.path, imageName));
file.writeAsBytesSync(res.data as List<int>);
return file;
}
Future<File> fileFromImageUrl() async {
String img='https://pps.whatsapp.net/v/t61.24694-24/160266256_1115367465775510_3546030680878251116_n.jpg?ccb=11-4&oh=01_AdSsrMGOPfs8CUJsEkYImMUu5L4DAzt2ym8eBrdsMG5O0Q&oe=63D7B45E';
final response = await http.get(Uri.parse(img));
final documentDirectory = await getApplicationDocumentsDirectory();
final file =
File(p.join(documentDirectory.path, 'File Name.jpg'));
file.writeAsBytesSync(response.bodyBytes);
return file;
}