0

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.

Hax
  • 19
  • 1
  • 7

4 Answers4

2

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);
  });
}
Kaushik Chandru
  • 15,510
  • 2
  • 12
  • 30
  • Thanks! I have changed to my "uploadURL" and imported the http_parser package, but I'm still a bit lost how I should use this function to directly upload the taken picture to my server. I'm quite new to flutter and dart so this is a bit advanced. :) – Hax Nov 14 '21 at 14:21
  • Use a plugin named image picker or file picker. It allows you to pick images from gallery or camera. Once you finished picking the image file pass that file to the method written in my answer. – Kaushik Chandru Nov 14 '21 at 14:48
  • request.files.add( new http.MultipartFile.fromBytes("file", ... If I have understood it correctly I need to change "file" to my image name and pass that variable to the Upload() function? – Hax Nov 15 '21 at 16:28
  • Thanks, I managed to solve it after some altering. – Hax Nov 15 '21 at 17:58
  • Nice. Glad you solved it. Please accept my answer if it was helpful – Kaushik Chandru Nov 15 '21 at 19:22
  • Done. Just a follow-up question, if I want to print out the body from the api, how do I do that? You can see my code in the answer I posted here. – Hax Nov 17 '21 at 18:44
1

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

  1. https - dart documentation
  2. Dio

You can also check multipartRequest on Stackoverflow.

Vishal Zaveri
  • 1,372
  • 2
  • 5
  • 12
0

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');
  }
}
Hax
  • 19
  • 1
  • 7
  • 1
    Add this line just below var response = await.request.send(); response.stream.transform(utf8.decoder).listen((value) { print(value); }); – Kaushik Chandru Nov 17 '21 at 19:08
  • Thanks, I appreciate the helpfulness! I used that line + import 'dart:convert'. Mind explaining to me what the utf8.decoder means? Also, do you recommend me to convert the JSON data to JavaObject, so that I later can more easily use it for communication to the app user? – Hax Nov 17 '21 at 20:11
  • Utf8 is a list of integers. To convert it to a readable string we use utf8 decode. for more, check https://api.flutter.dev/flutter/dart-convert/Utf8Decoder-class.html – Kaushik Chandru Nov 17 '21 at 20:25
0

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');
          }