How to convert image class to file - image

I am actually trying to convert an image to a File with flutter. More precisely, I want to copy an image with the following code :
floatingActionButton: FloatingActionButton(
onPressed: () async {
final path = join(
// Store the picture in the temp directory.
// Find the temp directory using the `path_provider` plugin.
(await getTemporaryDirectory()).path,
'${DateTime.now()}.png',
);
final File localImage = await theImage.copy('path');
//convert our Image file to bytes
final bytes = await localImage.readAsBytes();
MyImage myImage = MyImage(
isLiked: false,
imgBase64: base64Encode(bytes),
);
),
But there is this error :
The method copy isn't defined for the clas 'Image'.
Is there a function like Image.file(File file) (which creates a widget that displays an ImageStream obtained from a File) to get a file from an Image ?
Thank you for your help !

Related

How to display a png image from api response in flutter?

I'm getting a PNG image (NOT URI) as a response to my api request as shown bellow:
Future PostToGetPostImages(String pic_id,String pic_type) async {
try {
var parms = {
'code': pic_type+"_"+pic_id,
};
Response response = await _dio.post(_get_post_image,
data: parms,
options: Options(contentType: Headers.formUrlEncodedContentType),
onSendProgress: (int sent, int total) {
print('sent : $sent // total : $total');
}, onReceiveProgress: (v, s) {
print('v : $v // s : $s');
});
print('***** Response body Download Profile Images: ${response.data} **********');
return response.data;
} catch (error, stacktrace) {
_handleError(error);
print("Exception occured A: $error stackTrace: $stacktrace");
}
}
This is what it print after execution:
I/flutter (12777): ***** Response body Download Profile Images: �PNG
I need to know how to display this response ( the png image ) in flutter, I'm using this code but it's not working:
FutureBuilder(
future: aptProvider().PostToGetProfileImages("1", "m"),
builder: (context, snapshot) {
return CircleAvatar(
radius: 65.0,
backgroundImage: backgroundImage: NetworkImage(snapshot.data
.toString()));
}),
The problem here that you is not using a URL image, confirm to use a URL end with (.png, jpg, ..etc.) and also confirm it by open it in your browser.
then
to display it in you widget use one of this ways
First
Image.network('URL')
// ex: Image.network('https://picsum.photos/250?image=9')
Second
Container( height : 100 , width :100 , decoration : Box decoration (
image : Decoration image ( Network image ('URL'), ),
), ), ),
Perhaps the png is like a dummy image like a 404 like the one in the image attached so you have to copy and try check it with Image.network if everything works fine you proceed with image.network
It seems like you get the image as a byte array, base64 string.
Here is how I solve that.
var base64 = response.split(';base64,')[1];
base64 = base64.replaceFirst('binary data/', '');
Uint8List bytes = base64Decode(base64);
// Image Widget which you can put in anywhere.
Image.memory(bytes, fit: BoxFit.contain)
I'm not sure if you got it to work but I wanted to leave this for future reference:
You are receiving raw bytes as part of the response; from there you will need to use those to create an image. For this you have two options:
Save the bytes to a file.
Show the image bytes straight from memory.
Option 1 is usually what you want, but if you need a quick test you can do option 2 without issues, keep in mind memory is limited. Both have different implementations depending on the packages you are using.
Here's a quick overview of what Option 2 might look like using just plain old http:
// MyRepository.dart
class Repository {
Future<Uint8List?> getImageBytes(<...some params>) async {
final streamResponse = await client.send(<...some req>);
final response = await Response.fromStream(streamResponse);
if (response.statusCode == 200) {
parsedResponse = response.bodyBytes;
}
return null;
}
}
// MyWidget.dart
class MyWidget extends StatelessWidget {
<... some other code>
final Uint8List imageRawBytes;
#override
Widget build(BuildContext context) {
return Image.memory(
imageRawBytes,
);
}
}
What's important here is that you use the raw response bytes instead of using a response body (which is usually an encoded String). This way you can build either a File or keep them in memory to be used.
If you are getting the image url from the response, then you can use the Image.network(imageUrl)
OR
If you are getting the imageData in the form of Uint8List, then you can use the Image.memory(imageData)

Video file to image stream in flutter

I have a video file in my assets folder (like mp4). I want to read that video file as an image stream, like an image stream in the camera package https://pub.dev/documentation/camera/latest/camera/CameraController/startImageStream.html
I want to pass the image to Tflite model.
Something like that:
controller = loadVideo('assets/example.mp4'); // how to do that?!
controller.startImageStream((CameraImage img) {
Tflite.runPoseNetOnFrame(
bytesList: img.planes.map((plane) {
return plane.bytes;
}).toList(),
imageHeight: img.height,
imageWidth: img.width,
numResults: 1,
threshold: 0.1,
).then((recognitions) {
// ...
}
}
I tried to search in the image_picker and video_player packages, but did not find anything.
What I did is to split the images and save them as files and then send it to the tf model. It's not fast (because you make file and then read it) but it is working, tested on android and it should work on IOS :)
I made a PR in the package flutter_export_video_frame, now it have a function in the name of exportImagesFromFile. It is Returning a Stream of images from video file as Stream<File>.
To get the video file from the asset folder I use the following function:
import 'dart:async';
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:flutter/services.dart' show rootBundle;
import 'package:path/path.dart';
Future<File> getImageFileFromAssets(String path) async {
final byteData = await rootBundle.load('assets/$path');
final fileName = basename(path);
final file = new File('${(await getTemporaryDirectory()).path}/$fileName');
await file.writeAsBytes(byteData.buffer
.asUint8List(byteData.offsetInBytes, byteData.lengthInBytes));
return file;
}
And then to move it to the posenet/model, there is a function that gets File as input:
var results = await Tflite.runPoseNetOnImage(
path: path,
numResults: 1,
);
One possible improvement to this method is to make it works only on the RAM (after you read the video, of course)
Yes, sure you can do that in one of the following ways:
Use the export_video_frame plugin
Use video_thumbnail plugin
You can specify an exact frame by the time parameter.

How to save images from assets to the internal storage in flutter?

I am trying to save the image from assets to internal storage. But, I could not load the image from assets to file. Here is what I have done:
onTap: () async {
final String documentPath = (await getApplicationDocumentsDirectory()).path;
String imgPath = (galleryItems[currentIndex].assetName).substring(7);
File image = await getImageFileFromAssets(imgPath);
print(image.path);
}
I used substring(7) to eliminate assets/ as, my assetName comes as assets/images/foo.jpg.
Future<File> getImageFileFromAssets(String path) async {
final byteData = await rootBundle.load('assets/$path');
final file =
await File('${(await getApplicationDocumentsDirectory()).path}/$path')
.create(recursive: true);
await file.writeAsBytes(byteData.buffer
.asUint8List(byteData.offsetInBytes, byteData.lengthInBytes));
return file;
}
After I get image, I don't know how to proceed forward to create a directory with my name in internal storage. And, copy file there.
*Note:- I have editted the post, as some basic mistakes were pointed out.
Update
Here is what I came up with. And it saves image in the /storage/emulated/0/Android/data/com.example.my_project/files/Pics/foo.jpg path.
File image = await getImageFileFromAssets(imgPath);
final extDir = await getExternalStorageDirectory();
// Path of file
final myImagePath = '${extDir.path}/Pics';
// Create directory inside where file will be saved
await new Directory(myImagePath).create();
// File copied to ext directory.
File newImage =
await image.copy("$myImagePath/${basename(imgPath)}");
print(newImage.path);
Here are some links that really helped me:
Flutter How to save Image file to new folder in gallery?
How to Save Image File in Flutter ? File selected using Image_picker plugin
How to convert asset image to File?
Special thanks to #David for the help. Please see comments to understand full scene if you are here to solve your similar problem.
So, I am accepting the answer from #David.
You are trying to create a file object in a path that doesn't exist. You're using your asset path, the path relative to the root of your Flutter project. However, this path doesn't exist in the device's documents folder, so the file can't be created there. The file also doesn't exist in the assets folder because you're prepending the documents path.
To fix your issue, you should pass assetName to rootBundle.load(), without the documents path and open the File() somewhere like $documentPath/foo.jpg
Edit:
To create the file you still have to call File.create, so you need to run:
final file = await File('$documentPath/images/foo.jpg').create(recursive: true);
For future reference, this is just to update the solution of #Biplove which really helped me a lot as a newbie...
Future<File> getImageFileFromAssets(String unique, String filename) async {
ByteData byteData = await rootBundle.load(assets/filename));
// this creates the file image
File file = await File('$imagesAppDirectory/$filename').create(recursive: true);
// copies data byte by byte
await file.writeAsBytes(byteData.buffer.asUint8List(byteData.offsetInBytes, byteData.lengthInBytes));
return file;
}
Thanks.

how to convert image to byte and again convert it to image in flutter?

I am trying to use the image_picker plugin. I can get the image as file using this plugin. I need to convert this image to bytes and send to a api. So I tried to use dart:convert to convert the image to byte string. Now when I decode I am getting a Uint8List type. How to convert this to a file and display in a Image.file(). I couldn’t proceed from here. Can someone help me with this.
consider i am getting this decodedBytes i am getting from a api response, how can i convert them to display in a Image widget
This is the code I tried so far.
var image = await ImagePicker.pickImage(source: ImageSource.camera);
setState(() {
imageURI = image;
final bytes = image.readAsBytesSync();
String img64 = base64Encode(bytes);
print(bytes);
print(img64);
final decodedBytes = base64Decode(img64);
print(decodedBytes);
//consider i am getting this decodedBytes i am getting from a api response, how can i convert them to display in a Image widget
});
I am getting this error using writeAsBytesSync(),
Unhandled Exception: FileSystemException: Cannot open file, path = 'decodedimg.png'
You get this error, because you can't write to any arbitrary location in an application sandbox. You can use path_provider to look up a temporary directory.
But in your case, just use the image object, pickImage already returns a File object, so just use Image.file(image)
If you want to decode a base64 into a temporary directory you can use:
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as path;
Future<File> writeImageTemp(String base64Image, String imageName) async {
final dir = await getTemporaryDirectory();
await dir.create(recursive: true);
final tempFile = File(path.join(dir.path, imageName));
await tempFile.writeAsBytes(base64.decode(base64Image));
return tempFile;
}
with pubspec.yaml:
dependencies:
path: ^1.6.0
path_provider: ^1.6.7

Replace Image in PDF with another Image pdf box

How to replace Image in PDF with another Image pdf box. How to do that?
I want to change VisualSignature on the pdf with another image.
I get Visual Apereance like that:
PDDocument doc= PDDocument.load(new FileInputStream("c:\\temp\\template.pdf"));
File dir= new File("c:\\temp\\");
Iterator<Entry<COSObjectKey, Long>> xrefEntriesIt =
doc.getDocument().getXrefTable().entrySet().iterator();
while( xrefEntriesIt.hasNext() ) {
COSObject object = doc.getDocument().getObjectFromPool(
xrefEntriesIt.next().getKey() );
if ( object.getDictionaryObject( COSName.SUBTYPE ) == COSName.IMAGE ) {
changeImage( object, doc);
}
}
and method for to change image
private static void changeImage(COSObject obj, PDDocument doc) {
PDXObjectImage imageInPdf =
(PDXObjectImage) PDXObject.createXObject(
(COSStream) obj.getObject());
File inputFile = new File("C:\\temp\\SIGNATURE.jpg");
PDXObjectImage newImage = new PDJpeg(
doc, new FileInputStream(inputFile));
imageInPdf.getCOSStream().replaceWithStream(newImage.getCOSStream());
}
I tested. imageInPdf is rally image from visual appearance of a signed signature field.
now how to remove and add new visual appearance of a signed signature field?
I've just added doc.save(). that's all

Resources