效果图:
相册
拍照
拍照后的照片显示在界面上
一丶 调用原生硬件Api实现照相机拍照和相册选择
导入第三方库:image_picker
拍照
_takePhoto() async {
var image = await ImagePicker.pickImage(source: ImageSource.camera);
setState(() {
_imgPath = image;
});
}
相册
_openGallery() async {
var image = await ImagePicker.pickImage(source: ImageSource.gallery);
setState(() {
_imgPath = image;
});
}
二丶 拍照上传到服务器
导入第三方库:上传图片到服务器
上传图片代码
_uploadData(imageFile) async{
FormData formData = new FormData.from({
"name": "wendux",
"age": 25,
'file': new UploadFileInfo(imageFile, "imageFileName.jpg")
});
var response = await Dio().post("http://jd.itying.com/imgupload", data: formData);
print(response);
}
完整代码:
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:dio/dio.dart';
class ImagePickerPage extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return _ImagePickerState();
}
}
class _ImagePickerState extends State<ImagePickerPage> {
var _imgPath;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("ImagePicker"),
),
body: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
_ImageView(_imgPath),
RaisedButton(
onPressed: _takePhoto,
child: Text("拍照"),
),
RaisedButton(
onPressed: _openGallery,
child: Text("选择照片"),
),
],
),
));
}
/*图片控件*/
Widget _ImageView(imgPath) {
if (imgPath == null) {
return Center(
child: Text("请选择图片或拍照"),
);
} else {
return Image.file(
imgPath,
);
}
}
/*拍照*/
_takePhoto() async {
var image = await ImagePicker.pickImage(source: ImageSource.camera,maxWidth: 400);
_uploadData(image); //上传
setState(() {
_imgPath = image;
});
}
/*相册*/
_openGallery() async {
var image = await ImagePicker.pickImage(source: ImageSource.gallery);
setState(() {
_imgPath = image;
});
}
_uploadData(imageFile) async{
FormData formData = new FormData.from({
"name": "wendux",
"age": 25,
'file': new UploadFileInfo(imageFile, "imageFileName.jpg")
});
var response = await Dio().post("http://jd.itying.com/imgupload", data: formData);
print(response);
}
}