so I have a simple question that I can't seem to figure out after a lot of trying out different things. So I have this ImagePicker Flutter function that picks image from gallery. I want to be able to click button to change background of the whole screen. Here is the function for Image Picker and it works fine.
Future _getImage() async {
final pickedFile = await picker.getImage(source: ImageSource.gallery);
setState(() {
if (pickedFile != null) {
_image = File(pickedFile.path);
print('_image: $_image');
} else {
print('No image selected');
}
});
}
The issue is that I can't seem to add that picked image in the BoxDecoration in the Scaffold, there is always an error, something in the vein of: 'The argument type 'Image' can't be assigned to the parameter type 'ImageProvider'
body: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: Image(_image),
),
),
I tried converting to string, linking direct path, but nothing seems to work. Is there a workaround around this or is there some other simple solution? Thank you!
You can copy paste run full code below
You can check _image == null and to show TransparentImage or FileImage
code snippet
import 'package:transparent_image/transparent_image.dart';
...
body: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: _image == null
? MemoryImage(kTransparentImage)
: FileImage(_image),
),
)),
working demo
full code
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:transparent_image/transparent_image.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
File _image;
final picker = ImagePicker();
Future _getImage() async {
final pickedFile = await picker.getImage(source: ImageSource.gallery);
setState(() {
if (pickedFile != null) {
_image = File(pickedFile.path);
print('_image: $_image');
} else {
print('No image selected');
}
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: _image == null
? MemoryImage(kTransparentImage)
: FileImage(_image),
),
)),
floatingActionButton: FloatingActionButton(
onPressed: _getImage,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
please try this ...
Container(
width: 100,
height: 200,
decoration: BoxDecoration(
image:DecorationImage(
image: new FileImage(file)
)
),
),
Related
I am using image_picker ^0.8.6+1 package for uploading a picture, after I added that dependency into the project, when I click in the floatingActionButton it suppose to open the image folder but it do nothing I don not know what wrong with my code, please help me with it :(
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
void main() => runApp(FourthUI());
class FourthUI extends StatefulWidget {
const FourthUI({super.key});
#override
State<StatefulWidget> createState() => _FourthUI();
}
class _FourthUI extends State<FourthUI> {
final ImagePicker _picker = ImagePicker();
File? pickedImage;
felchImage() async {
final XFile? image = await _picker.pickImage(source: ImageSource.gallery);
if (image == null) {
return;
}
setState(() {
pickedImage = File(image.path);
});
}
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
themeMode: ThemeMode.light,
theme: ThemeData(primarySwatch: Colors.blue, canvasColor: Colors.white),
title: 'my first UI application',
home: Scaffold(
appBar: AppBar(
title: Text(''),
),
body: Center(
child: pickedImage == null ? null : Image.file(pickedImage!),
),
floatingActionButton: FloatingActionButton(
onPressed: felchImage,
tooltip: 'Increment',
child: const Icon(Icons.photo_album),
),
));
}
}
I was expecting to open the image folder but when I click the FloatingActionButton nothing happen
I have used the exact code snippet given in the examples. Still it throws the error :Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'String' over the line
List<Face> _faces = await client.detect(
image: _image,
returnFaceAttributes: FaceAttributeType.values,
returnFaceLandmarks: true,
);
Can someone please tell how to rectify this and obtain faceAttribute values from the API whatever client.detect is returning.
Here is the full code:
final endpoint = "https://westcentralus.api.cognitive.microsoft.com/face/v1.0";
final key = "3080b54bd7c64a27801465608ca06a3e";
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
File image;
List<Face> faces = [];
bool isLoading = false;
final client = FaceServiceClient(key, serviceHost: endpoint);
void _incrementCounter() async {
setState(() {
image = null;
faces = [];
});
var maxWidth = MediaQuery.of(context).size.width;
File _image = await ImagePicker.pickImage(
source: ImageSource.gallery,
maxWidth: maxWidth,
);
if (_image != null) {
_getImageSize(Image.file(_image, fit: BoxFit.fitWidth)).then((Size size) {
print('CROPPED IMAGE WIDTH: ${size.width} HEIGHT: ${size.height}');
});
setState(() {
image = _image;
isLoading = true;
});
List<Face> _faces = await client.detect(
image: _image,
returnFaceAttributes: FaceAttributeType.values,
returnFaceLandmarks: true,
);
print('DETECTED FACES: ${_faces.length}');
setState(() {
faces = _faces;
isLoading = false;
});
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Column(
children: <Widget>[
_buildImage(context),
FlatButton(
child: Text('Clear'),
onPressed: () {
setState(() {
image = null;
faces = null;
});
},
)
],
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
Widget _buildImage(BuildContext context) {
if (image != null) {
return Container(
// height: MediaQuery.of(context).size.width,
width: MediaQuery.of(context).size.width,
child: FutureBuilder<Size>(
future: _getImageSize(Image.file(image, fit: BoxFit.fitWidth)),
builder: (BuildContext context, AsyncSnapshot<Size> snapshot) {
if (snapshot.hasData) {
return Stack(children: [
Container(
width: snapshot.data.width,
height: snapshot.data.height,
foregroundDecoration: FaceDetectDecoration(
faces,
snapshot.data,
),
child: Image.file(
image,
fit: BoxFit.fitWidth,
),
),
isLoading
? Center(
child: CircularProgressIndicator(),
)
: Container(),
]);
} else {
return Text('Please wait...');
}
},
),
);
}
return Container(
height: MediaQuery.of(context).size.height - 250.0,
alignment: Alignment.center,
child: Text('no picture'),
);
}
Future<Size> _getImageSize(Image image) {
Completer<Size> completer = new Completer<Size>();
image.image.resolve(new ImageConfiguration()).addListener(
(ImageInfo info, bool _) => completer.complete(
Size(info.image.width.toDouble(), info.image.height.toDouble())));
return completer.future;
}
}
It seems the problem was caused by type mismatch of FaceAttributeType.values in your code.
You change the code to:
Map data= new Map<String, dynamic>.from(FaceAttributeType.values);
List<Face> _faces = await client.detect(
image: _image,
returnFaceAttributes: data,
returnFaceLandmarks: true,
);
and then try again.
I am using ImagePickerWeb to allow users to upload photos from my app
Future<void> getPhotos() async {
var imageFile = await ImagePickerWeb.getImage(outputType: ImageType.file);
print(imageFile);
if (imageFile != null) {
setState(() {
currentSelfie = imageFile;
_accDetails['customer_selfie'] = currentSelfie;
});
}
When I try to display the image via Image.File
Image.file(
currentSelfie,
height: screenAwareSize(100, context),
width: screenAwareSize(100, context),
fit: BoxFit.fill,
),
I get this error
File$ ([object File]) :<getObject: NoSuchMethodError: The
getter 'uri' was called on null.>
I am using the file format for my because I am passing the image to my back end server and it receives the data as a file. Any help would be appreciated.
You can copy paste run full code below
According to owner's description https://github.com/Ahmadre/image_picker_web#how-do-i-get-all-informations-out-of-my-imagevideo-eg-image-and-file-in-one-run
You can use ImagePickerWeb.getImageInfo and show image with Image.memory
code snippet
Future<void> getPhotos() async {
var mediaData = await ImagePickerWeb.getImageInfo;
String mimeType = mime(Path.basename(mediaData.fileName));
html.File mediaFile =
new html.File(mediaData.data, mediaData.fileName, {'type': mimeType});
print("imageFile ${mediaData.toString()}");
if (mediaData != null) {
currentSelfie = mediaData.data;
setState(() {});
}
}
...
currentSelfie == null
? Container()
: Image.memory(
(currentSelfie),
fit: BoxFit.fill,
),
working demo
full code
import 'dart:async';
import 'dart:io';
import 'package:mime_type/mime_type.dart';
import 'package:path/path.dart' as Path;
import 'package:flutter/material.dart';
import 'package:image_picker_web/image_picker_web.dart';
import 'dart:html' as html;
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
var currentSelfie;
Future<void> getPhotos() async {
var mediaData = await ImagePickerWeb.getImageInfo;
String mimeType = mime(Path.basename(mediaData.fileName));
html.File mediaFile =
new html.File(mediaData.data, mediaData.fileName, {'type': mimeType});
print("imageFile ${mediaData.toString()}");
if (mediaData != null) {
currentSelfie = mediaData.data;
setState(() {});
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
currentSelfie == null
? Container()
: Image.memory(
(currentSelfie),
fit: BoxFit.fill,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: getPhotos,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
I want to select image from gallery, but when I tried to save it in shared preferences. I found that image_picker gives temporary location like tmp/image_picker_4415467867A964-791E-4AFA995BA-18295-0003861F9255294A.jpg
This is not real path of the image. How should I get original location path of the image for later use?
Or I want to save the whole image in database.. what to do?
pickimage() is deprecated now?
Please help
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Fluter demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
File _image;
String _imageloc;
#override
void initState() {
super.initState();
LoadImage();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Image Picker'),
),
body: Container(
alignment: Alignment.center,
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
_imageloc != null
? CircleAvatar(
backgroundImage: FileImage(File(_imageloc)),
radius: 80,
)
: CircleAvatar(
backgroundImage: _image != null
? FileImage(_image)
: NetworkImage(
'https://www.publicdomainpictures.net/pictures/320000/velka/background-image.png'),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: RaisedButton(
onPressed: () {
PickImage();
},
child: Text('Pick Image'),
),
),
RaisedButton(
onPressed: () {
saveImage(_image.path);
},
child: Text('saved'),
),
],
),
),
);
}
void PickImage() async {
var image = await ImagePicker.pickImage(source: ImageSource.gallery);
print(image.path);
setState(() {
_image = image;
});
}
void saveImage(_imageloc) async {
SharedPreferences preferences = await SharedPreferences.getInstance();
setState(() {
preferences.setString('imageloc', _imageloc);
});
}
void LoadImage() async {
SharedPreferences saveimage = await SharedPreferences.getInstance();
setState(() {
saveimage.getString('imageloc');
});
}
}
Well, if you need the image later, you need to copy it and save it somewhere. The actual image, not just the path. If I select an image in your app, I want it to be saved. I don't want it to be gone when I delete the picture from my gallery, or switch phones.
The path you have is sufficient to read the image and save it wherever you want. Your backend most likely, since I want to have my picture, even on another phone.
How you do this is highly dependent on your specific backend, but I'm sure there will be a tutorial for it.
I'm quite newbie in Flutter,
I have wrote a simple app which opens the gallery, so the user will pick an image,
but both on emulator and physical device i get the same error:
════════ Exception caught by image resource service ════════
following assertion was thrown resolving an image codec: Unable to
load asset:
/data/user/0/com.example.upload_image_example/cache
/image_picker915145764706640017.jpg
Image provider: AssetImage(bundle: null, name:
"/data/user/0/com.example.upload_image_example/cache/image_picker915145764706640017.jpg")
Image key: AssetBundleImageKey(bundle: PlatformAssetBundle#c486d(),
name:
"/data/user/0/com.example.upload_image_example/cache/image_picker915145764706640017.jpg",
scale: 1.0)
I have checked the path, the photo indeed exists in this path.
I have updated the pubspec.yaml for using other images in my assets directory.
but the problem arrives when i pick a photo with the image picker:
var photo = await ImagePicker.pickImage(source: ImageSource.gallery);
setState(() {
imageFile = photo;
});
Widget _ImageView() {
if (imageFile == null) {
return CircleAvatar(
radius: 80.0,
backgroundImage: AssetImage('assets/images/avatar_blank.jpeg'),
);
} else {
return CircleAvatar(
radius: 80.0,
backgroundImage: AssetImage(imageFile.path), // <---- HERE I receive the ERROR!!
);
}
}
What am I doing wrong?
Does anybody have some suggestion?
You can copy paste run full code below
You need FileImage
code snippet
return CircleAvatar(
radius: 80.0,
backgroundImage: FileImage(imageFile),
);
working demo
full code
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
File imageFile;
void _incrementCounter() async{
var photo = await ImagePicker.pickImage(source: ImageSource.gallery);
setState(() {
imageFile = photo;
});
setState(() {
_counter++;
});
}
Widget _ImageView() {
if (imageFile == null) {
return CircleAvatar(
radius: 80.0,
backgroundImage: AssetImage('assets/images/avatar_blank.jpeg'),
);
} else {
return CircleAvatar(
radius: 80.0,
backgroundImage: FileImage(imageFile),
);
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
_ImageView(),
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
The problem is that Flutter interprets the images of the storage differently than the assets, you can solve it like this:
Widget _ImageView() {
if (imageFile == null) {
return CircleAvatar(
radius: 80.0,
backgroundImage: AssetImage('assets/images/avatar_blank.jpeg'),
);
} else {
return CircleAvatar(
radius: 80.0,
backgroundImage: FileImage(imageFile), // storageImage
);
}
}
This Worked for me: https://stackoverflow.com/a/60368338/8168140
simplified code is:
image: new DecorationImage(
image: FileImage(_image),
fit: BoxFit.cover,
),