Converting Image FlutterWebImagePicker Output to File - flutter

I'm using Flutter web for a webapp and having trouble converting an image from the image picker to a file in order to upload it to my server. I display the image in Image.file(xxx) but I get the error:
Error while trying to load an asset: FormatException: Illegal scheme
character (at character 6)
Image(image:%20MemoryImage(Uint8List%234267a,%20scale:%201),%20frameBuilder...
Here is the code I'm trying:
Future getImage(bool isCamera) async {
Image image;
if (isCamera) {
image = await FlutterWebImagePicker.getImage;
} else {
}
var bytes = await rootBundle.load('$image');
String tempPath = (await getTemporaryDirectory()).path;
File file = File('$tempPath/profile.png');
await file.writeAsBytes(
bytes.buffer.asUint8List(bytes.offsetInBytes, bytes.lengthInBytes));
setState(() {
currentSelfie = file;
_accDetails['customer_selfie'] = currentSelfie;
});
}
Thanks in advance

I've tested this package and was very happy with the result imagePickerWebit returns 3 different types it can be in the form of Image(widget for preview), byte, File(upload)
then you can use this to get the values
html.File _cloudFile;
var _fileBytes;
Image _imageWidget;
Future<void> getMultipleImageInfos() 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});
if (mediaFile != null) {
setState(() {
_cloudFile = mediaFile;
_fileBytes = mediaData.data;
_imageWidget = Image.memory(mediaData.data);
});
}

I havent used the plugin although your code has 2 issues. One is the if statement and the second one is using Rootbundle. If you are picking from the filesystem, my assumption isCamera would be false. You have not added any logic for the falsy condition.
if (isCamera) {// This would be true if the source was camera
image = await FlutterWebImagePicker.getImage;
} else {
}
Additionally,
var bytes = await rootBundle.load('$image');
From the flutter documentation, rootbundle contains the resources that were packaged with the application when it was built. Those are assets that you define in your pubspec. yaml. You are selecting an image at runtime hence its not bundled as an asset.
Since the package appears to return an image object, use the toByteData method on the image i.e
image = await FlutterWebImagePicker.getImage;
await image.toByteData();//This method has some parameters. Look into them

Related

Flutter Image form Image Picker to Document Path

I am creating an app that saves images locally through sqflite, I have soon found out that the images are being saved as temp which means that it will be deleted by the device and i'm not able to retrieve those images anymore. I have been coding to save it to the document directory of the app but it seems to fail and throw error
[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: FileSystemException: Cannot copy file to '/data/user/0/com.example.e4psmap/cache/scaled_0d5d5070-70da-4f42-9055-c31a6ed8d3d51761448072222030817.jpg', path = '/data/user/0/com.example.e4psmap/app_flutter/scaled_0d5d5070-70da-4f42-9055-c31a6ed8d3d51761448072222030817.jpg' (OS Error: No such file or directory, errno = 2)
this is my code:
void getpic(ImageSource src) async{
Uint8List byte;
final picfile = await _imagepicker.getImage(
source: src, imageQuality: 25
);
if(picfile != null){
Directory appDir = await getApplicationDocumentsDirectory();
String appdoc = appDir.path;
final filename = path.basename(picfile.path);
final local = File('${appdoc}/$filename');
final lclfile = await local.copy(picfile.path);
}
// converted = picfile!.path;
// setState(() {
// _imgfile = picfile!;
// });
Navigator.pop(context);
}
Anyone knows why I am having this errors, and any fix for this error, Thank you
The copy() function expects the source file to be passed as an argument, but in your code, you're passing picfile.path instead of the File object.
try to replace local.copy(picfile.path) with picfile.saveTo(local.path), which should save the image to the desired directory.
If you replace final with the corresponding class, the error will be very obvious.

How do i open srt file on flutter?

I am trying to load subtitle to a video using the flutter video player package it works good for short files but it stopped as the file get bigger
I trayed subtitle_wrapper package but it has many bugs
Future<ClosedCaptionFile> getSubtitle(String url) async {
final data = NetworkAssetBundle(Uri(path: url));
final newdata = await data.load(url);
String fileContents = getStringFromBytes(newdata);
return captionFile = SubRipCaptionFile(fileContents);
}
this is getStringFromBytes function
getStringFromBytes(ByteData data) { final buffer = data.buffer;
var list = buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
return utf8.decode(list); }
it wasn't the size after all I tested on some srt files that have a blank space for some duration and the flutter converter do a check on every element if the length is<3 it break on get out of the loop

How to record a video with Camera Plugin in flutter?

I have this page where the camera is initialized and ready with a button that will record and stop the video, so I tried this :
FlatButton(
onPressed: () => {
!isRecording
? {
setState(() {
isRecording = true;
}),
cameraController.prepareForVideoRecording(),
cameraController.startVideoRecording('assets/Videos/test.mp4')
}
: cameraController.stopVideoRecording(),
},
............
but throws this error : nhandled Exception: CameraException(videoRecordingFailed, assets/Videos/test.mp4: open failed: ENOENT (No such file or directory)).
I don't understand, I don't want to open this file I want to save it there, Is there sth wrong with my code ?
In the new version, static method startRecordingVideo doesn't take any string parameter.
When you want to start the recording just see whether a video is already getting recorded, if not start
if (!_controller.value.isRecordingVideo) {
_controller.startVideoRecording();
}
and when you want to finish the recording you can call the static method stopVideoRecording() and it will give you a object of the class XFile, it will have the path to your video.
if (_controller.value.isRecordingVideo) {
XFile videoFile = await _controller.stopVideoRecording();
print(videoFile.path);//and there is more in this XFile object
}
This thing has worked for me. I am new to flutter please improve my answer if you know more.
You are trying to save a video in your assets folder which is not possible ,
What you need to do is to save to device locally either common folders like downloads or app directory.
Here is an example of how to go about it
dependencies:
path_provider:
Flutter plugin for getting commonly used locations on host platform
file systems, such as the temp and app data directories.
We will be saving the video to app directory.
We need to get the path to the directory where the file is or will be. Usually a file is put in the application's document directory, in the application's cache directory, or in the external storage directory. To get the path easily and reduce the chance of type, we can use PathProvider
Future<String> _startVideoRecording() async {
if (!controller.value.isInitialized) {
return null;
}
// Do nothing if a recording is on progress
if (controller.value.isRecordingVideo) {
return null;
}
//get storage path
final Directory appDirectory = await getApplicationDocumentsDirectory();
final String videoDirectory = '${appDirectory.path}/Videos';
await Directory(videoDirectory).create(recursive: true);
final String currentTime = DateTime.now().millisecondsSinceEpoch.toString();
final String filePath = '$videoDirectory/${currentTime}.mp4';
try {
await controller.startVideoRecording(filePath);
videoPath = filePath;
} on CameraException catch (e) {
_showCameraException(e);
return null;
}
//gives you path of where the video was stored
return filePath;
}

Store image uploaded by user into Flutter Web as an actual .jpg file

I am using the flutter_web_image_picker package to allow the user to select -and then upload to Firebase- an image.
However, the package returns an image widget, which I can display, but I cannot upload to Firebase. Therefore, I am trying to read the package's code and update it to fit my needs.
In general, I think the packages main functionalities are:
It gets the file
//...
final reader = html.FileReader();
reader.readAsDataUrl(input.files[0]);
await reader.onLoad.first;
final encoded = reader.result as String;
Then it 'strippes' it
final stripped = encoded.replaceFirst(RegExp(r'data:image/[^;]+;base64,'), '');
final imageName = input.files?.first?.name;
//...
To finally return it as a Widget:
final imageName = imageName;
final imageData = base64.decode(stripped);
return Image.memory(imageData, semanticLabel: imageName);
As I said, it works perfectly, however, I need to adapt it to my needs:
I would like to get the image as a .jpg file so that I can upload it to Firebase.
Is any of the variables above the actual .jpg file? Is there any transformation that I should perform to get a .jpg file?
Thanks!
I based my answer on this post.
Basically, on the flutter_web_image_picker package, before the code I posted, there were a few lines that get an actual html file:
final html.FileUploadInputElement input = html.FileUploadInputElement();
input..accept = 'image/*';
input.click();
await input.onChange.first;
if (input.files.isEmpty) return null;
Then using firebase's pacakge, I uploaded the image as follow:
import 'package:firebase/firebase.dart' as fb;
fb.StorageReference storageRef = fb.storage().ref('myLocation/filename.jpg');
fb.UploadTaskSnapshot uploadTaskSnapshot = await storageRef.put(input.files[0]).future;
Uri imageUri = await uploadTaskSnapshot.ref.getDownloadURL();
return imageUri;

Flutter: How to convert URI to File?

I want to convert path "content://media/external/images/media/138501" to File and set in the Image.
Code:
File imageFile = File("content://media/external/images/media/138501");
is not working on:
DecorationImage(image: ExactAssetImage(imageFile.path),fit: BoxFit.fill)
You can use uri_to_file package. It supports content:// URI.
Simple to use (Updated)
import 'package:uri_to_file/uri_to_file.dart';
try {
String uriString = 'content://sample.txt';
// Don't pass uri parameter using [Uri] object via uri.toString().
// Because uri.toString() changes the string to lowercase which causes this package to misbehave
// If you are using uni_links package for deep linking purpose.
// Pass the uri string using getInitialLink() or linkStream
File file = await toFile(uriString);
} on UnsupportedError catch (e) {
print(e.message);
} on IOException catch (e) {
print(e);
} catch (e) {
print(e);
}
then you can use this file as you want
Important note
Don't pass uri value like this
File file = await toFile(uri.toString());
Use like this if you are using uni_links package for deep linking purpose. Use getInitialLink() or linkStream
String? uriString = await getInitialLink();
if (uriString != null) {
File file = await toFile(uriString);
}
linkStream.listen((uriString) async {
if (uriString != null) {
File file = await toFile(uriString!);
}
});
This will not modify the uri string as we are not using uri.toString()
So this package will work fine
Working example:
Working example
For more details: uri_to_file
According to the doc you can use the fromUri constructor: File.fromUri(Uri uri).
Your case:
File imageFile = File.fromUri("content://media/external/images/media/138501");
You can use Absolute path plugin.
final filePath = await FlutterAbsolutePath.getAbsolutePath(uriString);
and then show the image by using Image.file:
Image.file(
File(filePath),
);
Make use of flutter_absolute_path package.
flutter_absolute_path: ^1.0.6 In pubsec.yaml

To convert file path from this format : “content://media/external/images/media/5275” To
"/storage/emulated/0/DCIM/Camera/IMG_00124.jpg”
final filePath = await FlutterAbsolutePath.getAbsolutePath("Any path
here");
File tempFile = File(filePath);
if (tempFile.existsSync()) {
//add your logic here.
}
define your URL:
final url = "Your Image Url";
then convert the Image Url to File in flutter :
XFile _xFile = XFile(url);
Done.
You could use Image.file constructor.
DecorationImage(
image: Image.file(File("content://media/external/images/media/138501")),
fit: BoxFit.fill
)
Please take a note: On Android, this may require the android.permission.READ_EXTERNAL_STORAGE permission.