how to set a picked image in flutter - image

I tried using this for picking and Saving Image->
File imageFile;
Future getImage(int type) async {
PickedFile pickedImage = await ImagePicker().getImage(
source: type == 1 ? ImageSource.camera :
ImageSource.gallery,
imageQuality: 50
);
if (pickedImage == null) return;
File tmpFile = File(pickedImage.path);
tmpFile = await tmpFile.copy(tmpFile.path);
setState(() {
imageFile = tmpFile;
});
}
imageFile != null
? Image.file(
imageFile,
height: MediaQuery.of(context).size.height / 5,
)
: Text("Pick up the image"),
But, Image is not saving. Nothing has been Displayed. What else I need to do?

This code is very ambiguous, it's very unclear where you are calling getImage and where you are setting the image.
I suppose you are not calling getImage() properly and not sure where you are using this if (pickedImage == null) return; it might be wrong.
Anyway, here's a proper explanation it should work.
Declare your getImage method inside the Widget class.
Future<File> getImage(int type) async {
PickedFile pickedImage = await ImagePicker().getImage(
source: type == 1 ? ImageSource.camera :
ImageSource.gallery,
imageQuality: 50
);
return pickedImage;
}
Declare the File state variable in the sate class
File imageFile;
Have a Button for the selecting action of the image in your widget.
...
IconButton(
icon: Icon(Icons.gallery),
onPressed: () {}
)
...
call the getImage method and setState the result in the onPressed handler.
...
IconButton(
icon: Icon(Icons.gallery),
onPressed: () async {
final tmpFile = await getImage(1);
setState(() {
imageFile = tmpFile;
});
)
...
Display your file in a widget
imageFile != null
?Image.file(
imageFile,
height: MediaQuery.of(context).size.height / 5,
): Text("Pick up the image"),

Related

Flutter: How do I select and display images

I cannot display selected images from gallery in a grid. In this code, I am displaying images in a list and I want to turn it into small grid type in 1 row but I don't know how. Can you please help?
Here's my code for selecting multiple images using file picker.
FileType fileType;
String imgName, _imgPath;
Map<String, String> imgPaths;
List<File> _imgList = List();
bool isLoadingPath = false;
_openFile() async {
setState(() => isLoadingPath = true);
try {
_imgPath = null;
imgPaths = await FilePicker.getMultiFilePath(
type: fileType != null ? fileType : FileType.custom,
allowedExtensions: ['jpg', 'png']);
_imgList.clear();
imgPaths.forEach((key, val) {
print('{ key: $key, value: $val}');
File file = File(val);
_imgList.add(file);
});
} on PlatformException catch (e) {
print("Unsupported operation" + e.toString());
}
if (!mounted) return;
setState(() {
isLoadingPath = false;
imgName = _imgPath != null
? _imgPath.split('/').last
: imgPaths != null
? imgPaths.keys.toString()
: '...';
});
}
Displaying images in a list. (How to display images as it is?)
Widget _fileBuilder() {
return Builder(
builder: (BuildContext context) => isLoadingPath
? Padding(
padding: const EdgeInsets.only(bottom: 4.0))
: _imgPath != null || imgPaths != null && (imgPaths.length > 1 && imgPaths.length < 5)
? new Container(
height: imgPaths.length > 1
? MediaQuery.of(context).size.height * 0.15
: MediaQuery.of(context).size.height * 0.10,
width: MediaQuery.of(context).size.width,
child: new Scrollbar(
child: new ListView.separated(
itemCount: imgPaths != null && imgPaths.isNotEmpty
? imgPaths.length
: 1,
itemBuilder: (BuildContext context, int index) {
final bool isMultiPath = imgPaths != null && imgPaths.isNotEmpty;
final int fileNo = index + 1;
final String name = 'File $fileNo : ' + (isMultiPath
? imgPaths.keys.toList()[index]
: _imgPath ?? '...');
final filePath = isMultiPath
? imgPaths.values.toList()[index].toString()
: _imgPath;
return new ListTile(
title: Transform.translate(
offset: Offset(-25, 0),
child: new Text(
name,
),
),
leading: Icon(Icons.attach_file_outlined, color: Color(0xFFF3A494),),
dense: true,
);
},
separatorBuilder:
(BuildContext context, int index) =>
new Divider(),
)),
)
: new Container(child: Text('4 photos is the maximum'),),
);
}
Dependencies:
file_picker: ^1.4.2
path:
mime:
async:
what you can do is, use the Image Picker dependency. You can find its documentation on pub.dev. after installing it, try using it and store the image uploaded in a file in the device. and with that file name, you can access the image.
You can try the below code, it worked for me. Also don't forget to import dart:io; for using file.
var _storedImage;
Future<void> _takePictureByCamera() async {
final picker = ImagePicker();
final imageFile =
await picker.getImage(source: ImageSource.camera, maxWidth: 600, imageQuality: 60);
setState(() {
_storedImage = File(imageFile!.path);
});
final appDir = await path_provider.getApplicationDocumentsDirectory();
final fileName = path.basename(imageFile!.path);
final savedImage = File(imageFile.path).copy('${appDir.path}/$fileName');
widget.onSelectImage(savedImage);
}
Future<void> _takePictureByGallery() async {
final picker = ImagePicker();
final imageFile =
await picker.getImage(source: ImageSource.gallery, maxWidth: 600);
if (imageFile == null) {
return;
}
setState(() {
_storedImage = File(imageFile.path);
});
final appDir = await path_provider.getApplicationDocumentsDirectory();
final fileName = path.basename(imageFile.path);
final savedImage = File(imageFile.path).copy('${appDir.path}/$fileName');
widget.onSelectImage(savedImage);
}
and after selecting or clicking the image, you can do this to display the image ->
void getImage() async {
final pickedImage = await showModalBottomSheet(
context: accountTabScaffoldMessengerKey.currentContext!,
backgroundColor: Colors.transparent,
enableDrag: true,
// elevation: 0,
builder: (context) => AccountImageUpdateBottomSheet(_selectImage),
);
_selectImage(pickedImage);
}
void _selectImage(File pickedImage) {
setState(() {
_pickedImage = pickedImage;
});
}
The image you selected is stored in the _pickedImage and you can access it by Image.file(_pickedImage).

Convert Uint8List image data to ImageGallerySaver saveFile String

how can I convert the Uint8List imagedata of the Screenshot Package to save it with the ImageGallerySaver package saveFile command, which needs a string?
TextButton(
onPressed: () {
_imageFile = null;
screenshotController
.capture()
.then((Uint8List image) async {
//print("Capture Done");
setState(() {
_imageFile = image;
});
final result = await ImageGallerySaver.saveFile();
print("File Saved to Gallery");
}).catchError((onError) {
print(onError);
});
I found a solution:
TextButton(
onPressed: () {
_imageFile = null;
screenshotController
.capture()
.then((Uint8List image) async {
//print("Capture Done");
String dir =
(await getApplicationDocumentsDirectory()).path;
File file = File("$dir/" +
DateTime.now().millisecondsSinceEpoch.toString() +
".png");
await file.writeAsBytes(image);
setState(() {
_imageFile = image;
});
final result =
await ImageGallerySaver.saveFile(file.path);
print("File Saved to Gallery");
}).catchError((onError) {
print(onError);
});
},
child: Icon(Icons.change_history),
), // Thi

Flutter web image_picker no implementation found

I am using version 0.6.7+22 of the image_picker Flutter package to pick an image from the device in my Flutter web app. I call getImage function in a pop-up:
class _ImageVerificationPopUpState extends State<ImageVerificationPopUp> {
File _image;
final picker = ImagePicker();
#override
Widget build(BuildContext context) {
return AlertDialog(
title: Text("Upload screenshot"),
content: SizedBox(
width: MediaQuery.of(context).size.width * 0.3,
child: Center(
child: _image != null
? SelectedImage(kIsWeb ? Image.network(_image.path) : Image.file(_image), () {
setState(() {
_image = null;
});
})
: SelectImageButton(_getImage),
),
),
actions: [
TextButton(onPressed: () => Navigator.of(context).pop(), child: Text("Cancel")),
TextButton(
onPressed: () {
final ImageCubit imageCubit = BlocProvider.of<imageCubit>(context);
imageCubit.uploadImage(_image);
Navigator.pop(context);
},
child: Text("Upload"))
],
backgroundColor: Color(0xFF333D81),
);
}
Future<void> _getImage() async {
final PickedFile pickedFile = await picker.getImage(source: ImageSource.gallery);
setState(() {
if (pickedFile != null) {
_image = File(pickedFile.path);
} else {
print("No image selected");
}
});
}
}
After I press the button, it throws the following error:
Error: MissingPluginException(No implementation found for method pickImage on channel plugins.flutter.io/image_picker)
at Object.throw_ [as throw] (http://localhost:7357/dart_sdk.js:5331:11)
at platform_channel.MethodChannel.new._invokeMethod (http://localhost:7357/packages/flutter/src/services/system_channels.dart.lib.js:954:21)
at _invokeMethod.next (<anonymous>)
at http://localhost:7357/dart_sdk.js:39029:33
at _RootZone.runUnary (http://localhost:7357/dart_sdk.js:38886:58)
at _FutureListener.thenAwait.handleValue (http://localhost:7357/dart_sdk.js:33872:29)
at handleValueCallback (http://localhost:7357/dart_sdk.js:34432:49)
at Function._propagateToListeners (http://localhost:7357/dart_sdk.js:34470:17)
at _Future.new.[_completeWithValue] (http://localhost:7357/dart_sdk.js:34312:23)
at async._AsyncCallbackEntry.new.callback (http://localhost:7357/dart_sdk.js:34335:35)
at Object._microtaskLoop (http://localhost:7357/dart_sdk.js:39173:13)
at _startMicrotaskLoop (http://localhost:7357/dart_sdk.js:39179:13)
at http://localhost:7357/dart_sdk.js:34686:9
I already tried calling flutter clean, flutter pub get and rerunning my app, but it didn't help.
How can I solve this issue?
Thanks for your help in advance!
Try adding the package image_picker_for_web to your pubspec.yaml file.
...
dependencies:
...
image_picker: ^0.6.7
image_picker_for_web: ^0.1.0
...
...
then modify your _getImage method:
Future<void> _getImage() async {
final PickedFile pickedFile = await picker.getImage(source: ImageSource.gallery);
setState(() {
if (pickedFile != null) {
if (kIsWeb) { // Check if this is a browser session
_image = Image.network(pickedFile.path);
} else {
_image = Image.file(File(pickedFile.path));
}
} else {
print("No image selected");
}
});
}
I think this is what made it work for me. I was getting the same error message as you.

Flutter image_picker "'PickedFile'" can't be assigned to the parameter type 'File'

I'm calling a widget in my code to display the selected image through image-picker plugin; following is my code:
Widget _imagePlaceHolder() {
if (imageSelected == null){
return Text("No File Selected!!");
} else {
Image.file(imageSelected, width: 400, height: 400);
}
}
but I'm getting this error:
The argument type "'PickedFile'" can't be assigned to the parameter type 'File'
on imageSelected under else statement.
I'm picking an image like this from gallery:
Future _openGallery(BuildContext context) async {
var picture = await picker.getImage(source: ImageSource.gallery);
this.setState(() {
imageSelected = picture;
});}
I've defined:
PickedFile imageSelected;
final picker = ImagePicker();
what's going wrong here? Please help..
Image.file() accepts a property of type File class, whereas the ImagePicker().getImage() method returns a type PickedFile.
We have to utilise the getter .path of the returned PickedFile argument and pass that file path to the create a File object as follows:
void _setImage() async {
final picker = ImagePicker();
PickedFile pickedFile = await picker.getImage(source: ImageSource.gallery);
imageFile = File(pickedFile.path);
}
This may be done in one line as follows:
void _setImage() async {
imageFile = File(await ImagePicker().getImage(source: ImageSource.gallery).then((pickedFile) => pickedFile.path));
}
After this, you can use the variable imageFile and pass it inside Image.file() like Image.file(imageFile), or FileImage() like FileImage(imageFile) as required.
For more, see the image_picker documentation on pub.dev
//many time when user import dart.html package than it throw error so keep note that we have to import dart.io
import 'dart.io';
final imagePicker = ImagePicker();
File imageFile;
Future getImage() async {
var image = await imagePicker.getImage(source: ImageSource.camera);
setState(() {
imageFile = File(image.path);
});
}
Change PickedFile imageSelected to File imageSelected and use ImagePicker.pickImage(source: ImageSource.gallery) instead of picker.getImage(source: ImageSource.gallery);
import 'package:image_picker/image_picker.dart';
import 'dart:io';
var image;
void imagem() async {
PickedFile picked = await ImagePicker().getImage(
preferredCameraDevice: CameraDevice.front, source: ImageSource.camera);
setState(() {
image = File(picked.path);
});
}
Or case you need of code full:
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
class Photos extends StatefulWidget {
#override
_PhotosState createState() => _PhotosState();
}
class _PhotosState extends State<Photos> {
var image;
void imagem() async {
PickedFile picked = await ImagePicker().getImage(
preferredCameraDevice: CameraDevice.front, source: ImageSource.camera);
setState(() {
image = File(picked.path);
});
}
#override
Widget build(BuildContext context) {
return SingleChildScrollView(
child: Center(
child: Column(
children: [
RaisedButton(
onPressed: imagem,
child: Text("Imagem"),
),
image != null ? Image.file(image) : Text("I")
],
),
));
}
}
Morpheus answer is correct.
Just pass in the PickedFile variable path to File().
Example:
final picker = ImagePicker();
PickedFile pickedFile = await picker.getImage(source: ImageSource.gallery);
imageFile = File(pickedFile.path);
Try converting your imageFile type to PickedImage and return the file in type Casting the imageFile to File, Like:-
// Declaring the variable here
PickedImage imageFile;
And at the time of returning:-
return Image.file(File(imageFile.path),width: 400,height: 400,);
I personally faced this problem, and this solution solved it.
Try this way...
Future pickImageFromGallery() async {
try {
final pickedFile = await picker.pickImage(
source: ImageSource.gallery,
);
setState(() {
widget.imageFile = File(pickedFile!.path);
});
if (pickedFile == null) {
throw Exception('File is not available');
}
} catch (e) {
print(e);
}

Flutter qrImage convert to Image

I'm using qr_flutter to create QrImage. It's ok but I would like to convert QrImage into image in order to create a PDF file to print on the printer. Please kindly help!
QrImage(
data: qrString,
size: 300.0,
version: 10,
backgroundColor: Colors.white,
),
Use a RepaintBoundary widget with a key to export the widget to a a b64 string which then you can export as an image.
Example:
Future<Uint8List> _getWidgetImage() async {
try {
RenderRepaintBoundary boundary =
_renderObjectKey.currentContext.findRenderObject();
ui.Image image = await boundary.toImage(pixelRatio: 3.0);
ByteData byteData =
await image.toByteData(format: ui.ImageByteFormat.png);
var pngBytes = byteData.buffer.asUint8List();
var bs64 = base64Encode(pngBytes);
debugPrint(bs64.length.toString());
return pngBytes;
} catch (exception) {}
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(children: [
RepaintBoundary(
key: _renderObjectKey,
child: QrImage(
data: "some text",
size: 300.0,
version: 10,
backgroundColor: Colors.white,
),
),
RaisedButton(onPressed: () {
_getWidgetImage();
})
]));
}
Future<Uint8List> toQrImageData(String text) async {
try {
final image = await QrPainter(
data: text,
version: QrVersions.auto,
gapless: false,
color: hexToColor('#000000'),
emptyColor: hexToColor('#ffffff'),
).toImage(300);
final a = await image.toByteData(format: ImageByteFormat.png);
return a.buffer.asUint8List();
} catch (e) {
throw e;
}
}
A more updated typed answer, that adds responsibility seggregation and null-safety, extending the correct one from #Zroq would be:
Future<Uint8List> createImageFromRenderKey({GlobalKey<State<StatefulWidget>>? renderKey}) async {
try {
final RenderRepaintBoundary boundary = renderKey?.currentContext?.findRenderObject()! as RenderRepaintBoundary;
final ui.Image image = await boundary.toImage(pixelRatio: 3);
final ByteData? byteData = await image.toByteData(format: ui.ImageByteFormat.png);
return byteData!.buffer.asUint8List();
} catch(_) {
rethrow;
}
}
The idea is based on the same principle: using the global render key to create the ByteData that allows you to create the Uint8List buffer. However, the new versions of Flutter change the type of the boundary to become a RenderyObject? instead of a RenderRepaintBoundary.
The rethrow is (dirty) way of bypassing the limitation/small bug where RepaintBoundary may be being used in the UI to repaint the boundary (exposed as boundary.debugNeedsPaint), so it can potentially throw an unhandled exception or create a low-quality image buffer. So if the view is being used I rethrow the method.
More details about the stack trace: https://github.com/theyakka/qr.flutter/issues/112

Resources