Flutter: Convert the cached (.file) file to mp4 file - flutter

I have a video file. I save to cache this video file. And I want to play this video in other page. But when I save this video to cache I dont play video. this video appear in cache like this.
/data/user/0/com.example.flutter_cache_manager/cache/libCachedImageData/fc65e4a0-0fb7-11eb-a1ed-53020f3249ad.file
I need to convert this video to .mp4 file.
Future addCacheFiles() async {
try {
Uint8List bytes;
String myPath = realPath + '/WhatCarCanYouGetForAGrand.mp4';
_readFileByte(myPath).then((bytesData) async {
bytes = bytesData;
var file = await DefaultCacheManager().putFile(realPath + "/WhatCarCanYouGetForAGrand.mp4", bytes);
print(file.path.toString() + " " + "kayıt etti");
});
} catch (e) {
print("hata");
print(e);
}
}
Future<Uint8List> _readFileByte(String filePath) async {
Uri myUri = Uri.parse(filePath);
File audioFile = new File.fromUri(myUri);
Uint8List bytes;
await audioFile.readAsBytes().then((value) {
bytes = Uint8List.fromList(value);
print('reading of bytes is completed');
}).catchError((onError) {
print('Exception Error while reading audio from path:' +
onError.toString());
});
return bytes;
}
thanks. by the way this code is running. I just need to convert to mp4 file.

Do you definitely want to convert the cached file?
Instead you could include the fileExtension argument when you call .putFile:
var file = await DefaultCacheManager().putFile(realPath + "/WhatCarCanYouGetForAGrand.mp4", bytes, fileExtension: 'mp4');
That way the cache won't change it to .file in the first place.

Related

how to download files from cache directory to Android download directory

I download files from FTP and store them in cache directory using path_provider package
Future<void> _fileMock(String strFileName) async {
try {
final Directory appDocDir = await getTemporaryDirectory()..createSync(recursive: true);
String appDocPath = appDocDir.path;
print('appDocPath : $appDocPath');
_file = File('$appDocPath/$strFileName');
setSavePath('$appDocPath/$strFileName');
print('file : $file');
}catch(e){
print('_fileMock Error : ${e.toString()}');
final File file = File('');
}
}
The path to the cache directory is /data/user/0/package name/cache/fileName
The file will download normally.
I want to copy or download files from the cache directory to the download directory. Attach an image.
Solved
Implement in JAVA and call with MethodChannel.
///JAVA
Map<String, String> arg = call.arguments();
String strPath = arg.get("path");
String strFileName = arg.get("fileName");
assert strPath != null;
File fP02 = new File(strPath);
File file;
try {
assert strFileName != null;
file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS), strFileName);
Files.copy(fP02.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING);
result.success(file.getPath());
} catch (IOException e) {
e.printStackTrace();
}

How can I download multiple images from Firestore Storage on a Flutter Web mobile app?

Following Firestore documentation and other posts, I arrived at the following function:
Future<void> downloadProductImages() async {
//TODO: modify on suppliers admin that images are saved with the correct name.
final storageRef = FirebaseStorage.instance.ref();
int count = 1;
for (final ref in product.imgsMap.keys.toList()) {
print(ref);
try {
final childRef = storageRef.child(ref);
const maxSize = 10 * 1024 * 1024;
final Uint8List data = (await childRef.getData(maxSize))!;
//check if file is jpeg
late String ext;
if (data[0] == 0xFF &&
data[1] == 0xD8 &&
data[data.length - 2] == 0xFF &&
data[data.length - 1] == 0xD9) {
ext = 'jpeg';
} else {
ext = 'png';
}
final content = base64Encode(data!.toList());
AnchorElement(href: "${product.imgsMap[ref]}")
..setAttribute("download", " ${product.name}_$count.$ext")
..setAttribute("type", "image/$ext")
..click();
count++;
} on FirebaseException catch (e) {
//TODO: HANDLE EXCEPTIONS
print(e);
} on Exception catch (e) {
// Handle any errors.
print(e);
}
}
// File file = // generated somewhere
// final rawData = file.readAsBytesSync();
}
I am able to download multiples files, however the images are not recognized as such on Chrome Mobile's downloads, which is my main target.
I am guessing that I am not building correctly the Anchor Element.
How can I fix this method or is there a different way to download multiple images on Flutter Web?

How can I download multiple images from Firebase Storage on Flutter Web?

I am developing a Flutter Web application that, after clicking a download button, I need to download multiple images from Firebase Storage.
How can I don this on Flutter Web?
UPDATE:
After following Frank's suggestion on the comments, and other posts. I wrote the following function:
Future<void> downloadProductImages() async {
//TODO: modify on suppliers admin that images are saved with the correct name.
final storageRef = FirebaseStorage.instance.ref();
int count = 1;
for (final ref in product.imgsMap.keys.toList()) {
print(ref);
try {
final childRef = storageRef.child(ref);
const maxSize = 10 * 1024 * 1024;
final Uint8List data = (await childRef.getData(maxSize))!;
//check if file is jpeg
late String ext;
if (data[0] == 0xFF &&
data[1] == 0xD8 &&
data[data.length - 2] == 0xFF &&
data[data.length - 1] == 0xD9) {
ext = 'jpeg';
} else {
ext = 'png';
}
// Data for "images/island.jpg" is returned, use this as needed.
final content = base64Encode(data!.toList());
AnchorElement(
href:
"data:application/octet-stream;charset=utf-16le;base64,$content")
//href: "image/$ext;charset=utf-16le;base64,$content")
..setAttribute("download", "${product.name}_$count.$ext")
..click();
count++;
} on FirebaseException catch (e) {
//TODO: HANDLE EXCEPTIONS
print(e);
} on Exception catch (e) {
// Handle any errors.
print(e);
}
}
// File file = // generated somewhere
// final rawData = file.readAsBytesSync();
}
On chrome mobile, the files are downloaded but are not recognized as pictures. It seems that the AnchorElment doesn't have the correct href.
Any ideas?

Flutter app keeps stoping when i'm trying to extarct text from image using google_ml_vision: ^0.0.7

I'm trying to extract Arabic text from an image using google_ml_vision: ^0.0.7,
I wrote the function below, but when I call it the app crashed(its crashed in this point await textRecognizer.processImage(visionImage)) without providing any logs
the image path is correct but it still didn't work
Future _extarctArabicTexFromImage() async {
try {
// final File imageFile = File(imgPath);
final GoogleVisionImage visionImage =
GoogleVisionImage.fromFilePath(imgPath);
final TextRecognizer textRecognizer =
GoogleVision.instance.textRecognizer();
late VisionText visionText;
try {
visionText = await textRecognizer.processImage(visionImage);
} catch (e) {
print(e.toString());
}
// String text = visionText.text;
for (var block in visionText.blocks) {
final List<RecognizedLanguage> languages = block.recognizedLanguages;
for (var line in block.lines) {
for (var textElement in line.elements) {
txt = txt + " " + textElement.text.toString();
}
txt = txt + '\n';
}
}
} catch (e) {
print(e.toString());
}
}

Flutter, dart:io - convert Uint8List (from websocket) to a jpeg file I can draw

I've written a simple nodejs ws websocket server that is serving a binary jpeg file when a client connects as follows:
import WebSocket = require("ws");
console.log("Websocket is starting...");
// Setup websocket
const wss = new WebSocket.Server({ port: 8080 });
wss.on("connection", function connection(webSocket) {
console.log("Connected");
webSocket.on("message", function incoming(message) {
console.log("received: %s", message);
});
webSocket.on("error", function error(err) {
console.log(err.error);
});
webSocket.send(binaryJpegFile);
});
There was an error in this code as it sends as text by default so I replaced:
webSocket.send(binaryJpegFile);
with:
webSocket.send(binaryJpegFile, {binary: true});
Now my flutter codes receives the binary jpeg file as a Uint8List using the following code:
WebSocket socket;
void handleWebSocket(data) {
// Listen for incoming data. We expect the data to be a JSON-encoded String.
print("WebSocket data received");
if (data.runtimeType == String) {
print("String received");
String dataString = data;
print(dataString.length);
print(dataString);
} else if (data.runtimeType == Uint8List) {
print("Binary received");
Uint8List binaryIntList = data;
print(binaryIntList.lengthInBytes);
} else {
print("Unknown datatype recieved : " + data.runtimeType.toString());
}
}
connect() async {
if (socket == null) {
socket = await WebSocket.connect('ws://localhost:8080');
socket.listen(handleWebSocket);
}
socket.add('Hello, World!');
}
#override
void initState() {
super.initState();
connect();
}
Can anyone give tips on how to convert Uint8List to a jpeg file I can draw?
First try using Uint8List directly with Image.memory widget.
example:
new Image.memory(binaryIntList);
If that doesn't work as expected.
You can use the image dart package to first decode the bytes to Image object and the encode it to the format you wish.
example:
import 'package:image/image.dart' as I; //So that this does not conflict with the Image widget
then
I.Image _img = I.decodeImage(binaryIntList);
_img = I.encodeJpg(_img);
then use it as
new Image.memory(_img.getBytes());
Hope that helped!
Image.memory(binaryIntList);
Is always useful,good luck