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

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());
}
}

Related

Rare error when trying to save data "unhandled exception on the current circuit"

I am using VS 2022, Blazor server project. When I trying to save data
async public static Task<bool> updateObject(Firecall obj)
{
Firecall r;
try
{
using (var context = new sptContext())
{
r = context.Firecalls.Where(c => c.Mguid == obj.Mguid).FirstOrDefault();
bool новое = (r == null);
if (новое)
{
r = new Firecall();
}
r.comment = obj.comment;
if (новое)
await context.Firecalls.AddAsync(r);
if (busy)
return false;
try
{
busy = true;
await context.SaveChangesAsync();
}
catch (Exception)
{
return false;
}
finally {
busy = false;
}
}
return true;
}
catch (Exception)
{
return false;
}
}
sometimes I get error:
Sometimes an error occurs, sometimes not. No error in debugger.
How to solve problem?
P.S. Data in each operation is saved as expected. Only after the operation is completed the indicated error message appear
And calling savechanges method from #code block of .razor view:
async private void SaveChanges()
{
bool rez = await firecallRepository.updateObject(_currentFireCall);
}

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?

Downloading images and save to device

I having some issues here with UnityWebRequest.
I tried to download and save the jpeg, but it seem that the download is a success but it does not save it, and does not show me Log from "saveToFile" function.
Did I did something wrong?
Here are my code.
public string folderPath;
void Start()
{
folderPath = Application.persistentDataPath + "/" + FileFolderName;
}
IEnumerator DownloadingImage(Uri url2)
{
Debug.Log("Start Downloading Images");
using (UnityWebRequest uwr = UnityWebRequestTexture.GetTexture(url2))
{
// uwr2.downloadHandler = new DownloadHandlerBuffer();
yield return uwr.SendWebRequest();
if (uwr.isNetworkError || uwr.isHttpError)
{
Debug.Log(uwr.error);
}
else
{
Debug.Log("Success");
Texture myTexture = DownloadHandlerTexture.GetContent(uwr);
byte[] results = uwr.downloadHandler.data;
saveImage(folderPath, results);
}
}
}
void saveImage(string path, byte[] imageBytes)
{
//Create Directory if it does not exist
if (!Directory.Exists(Path.GetDirectoryName(path)))
{
Directory.CreateDirectory(Path.GetDirectoryName(path));
Debug.Log("Creating now");
}
else
{
Debug.Log(path + " does exist");
}
try
{
File.WriteAllBytes(path, imageBytes);
Debug.Log("Saved Data to: " + path.Replace("/", "\\"));
}
catch (Exception e)
{
Debug.LogWarning("Failed To Save Data to: " + path.Replace("/", "\\"));
Debug.LogWarning("Error: " + e.Message);
}
}
You have wrong file name so give filename with extension,
If you don't give extension, 'Directory.Exists' doesn't know whether file or directory.
or you could separate parameters such as rootDirPath and filename.
IEnumerator DownloadingImage(Uri url2)
{
Debug.Log("Start Downloading Images");
using (UnityWebRequest uwr = UnityWebRequestTexture.GetTexture(url2))
{
// uwr2.downloadHandler = new DownloadHandlerBuffer();
yield return uwr.SendWebRequest();
if (uwr.isNetworkError || uwr.isHttpError)
{
Debug.Log(uwr.error);
}
else
{
Debug.Log("Success");
Texture myTexture = DownloadHandlerTexture.GetContent(uwr);
byte[] results = uwr.downloadHandler.data;
string filename = gameObject.name+".dat";
// saveImage(folderPath, results); // Not a folder path
saveImage(folderPath+"/"+filename, results); // give filename
}
}
}

Signature pad sending empty

Signature pad sending empty
I'm using a Signature Pad, and Canvas by SkiaSharp, but when I sending after drawing by user and encode to base 64, on server only shows an empty canvas
async void OnSaveButtonClicked(object sender, EventArgs args)
{
using (SKImage image = SKImage.FromBitmap(saveBitmap))
{
try
{
SKData data = image.Encode(SKEncodedImageFormat.Png, 100);
var bytesImg = data.ToArray();
string imageBase64 = Convert.ToBase64String(bytesImg);
var respuesta = await this.ApiService.PostSignature(
this.url,
this.Id,
imageBase64
);
Method to send on Services...
public async Task PostSignature(
string urlBase,
string folio,
string imageBase64)
{
try
{
var client = new HttpClient();
var response = await client.PostAsync(urlBase,
new StringContent(string.Format(
"idReporte={0}&imgFirma={1}",
folio, imageEncoded),
Encoding.UTF8, "application/x-www-form-urlencoded"));
if (!response.IsSuccessStatusCode)
{
return response.ToString();
}
else
{
var result = await response.Content.ReadAsStringAsync();
return result;
}
}
catch
{
return null;
}
}
END REQUEST...
catch (Exception ex)
{
await Application.Current.MainPage.DisplayAlert(
"Error",
"Image Is not Send, error: " + ex.Message,
"OK"
);
}
finally
{
completedPaths.Clear();
inProgressPaths.Clear();
UpdateBitmap();
canvasView.InvalidateSurface();
}
The image is empty, is decoded OK and loaded in folder path.
According to your description, you want to get image from signature pad, and converting it into base 64, I do one simple that you can take a look,just cast your imagestream to memorystream
<StackLayout>
<forms:SignaturePadView
x:Name="signaturepad"
BackgroundColor="Black"
HeightRequest="350"
StrokeColor="White"
StrokeWidth="3"
WidthRequest="250" />
<Button
x:Name="save"
Clicked="Save_Clicked"
HeightRequest="50"
Text="save"
WidthRequest="200" />
</StackLayout>
private async void Save_Clicked(object sender, EventArgs e)
{
string base64String;
using (var memoryStream = new MemoryStream())
{
var signature = await signaturepad.GetImageStreamAsync(SignatureImageFormat.Png);
signature.CopyTo(memoryStream);
var byteArray = memoryStream.ToArray();
base64String = Convert.ToBase64String(byteArray);
}
}