How can I convert it to base64? I able to store it, but how to get base64 from there?
I using this plugin https://pub.dev/packages/signature_pad/example
final image = await sign.getData();
var data = await image.toByteData(format: ui.ImageByteFormat.png);
var savedDir = await getApplicationDocumentsDirectory();
String appDocPath = savedDir.path;
await Directory('$appDocPath/Signature/').create(recursive: true);
var file = File(file).writeAsBytesSync(data.buffer.asInt8List());
I get the file and do like this
List<int> imageBytes = await File(file).readAsBytes();
String base64Image = base64Encode(imageBytes);
print(base64Image);
Full code
final image = await sign.getData();
var data = await image.toByteData(format: ui.ImageByteFormat.png);
var savedDir = await getApplicationDocumentsDirectory();
String appDocPath = savedDir.path;
await Directory('$appDocPath/Signature/').create(recursive: true);
var file = File(file).writeAsBytesSync(data.buffer.asInt8List());
List<int> imageBytes = await File(file).readAsBytes();
String base64Image = base64Encode(imageBytes);
print(base64Image);
Are there any cleaner way ?
Related
How to get the innerText from a <input> using XPath?
I have this to work but with CSS, but it do not work for me with XPath
IElementHandle ha = await page.QuerySelectorAsync(xpath);
IJSHandle ith = await ha.GetPropertyAsync("value");
string val = ith.RemoteObject.Value.ToString();
The following works for me:
using PuppeteerSharp;
using var browserFetcher = new BrowserFetcher();
await browserFetcher.DownloadAsync();
await using var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true });
using (var page = await browser.NewPageAsync())
{
await page.GoToAsync("http://www.google.de/");
var input = (await page.XPathAsync("/html/body/div[1]/div[3]/form/div[1]/div[1]/div[4]/center/input[1]"))[0];
var ith = await input.GetPropertyAsync("value");
var val = ith.RemoteObject.Value.ToString();
Console.Write(val);
}
Hello I've been trying to convert an Image to base64 and send it to a specified API but whenever I post an Image, it won't accept the data, but when the image is null the data gets in. These are the example of the API data that has an Image in it:
"PostedPicture": "Images/Posted/PostPhoto_659.jpg"
And this is me trying to post it (Camera function):
Future<void> _pickImageFromCamera() async {
final PickedFile pickedFile =
await picker.getImage(source: ImageSource.camera);
setState(() {
this.imageFile = File(pickedFile.path);
});
List<int> imageBytes = imageFile.readAsBytesSync();
print("Disini imageBytesnya: $imageBytes");
image = base64Encode(imageBytes);
}
Api post:
Future<HttpClientRequest> postNewsFeed() async {
print(
"Here is the post Type: $type, ID: $dataId, News: $news, SRCDOC: $sourceDocType, PRVCY: $privacyType, IMAGE: $image");
final client = HttpClient();
final request = await client.postUrl(Uri.parse(
"http://xxx.xx.xxx.xx:xxx/Services/SocMed/SocMedSvc.ashx?Type=$type&strEmpNo=$dataId&strNews=${news.text.toString()}&strGroupCode=['$dataGroupCode']&strSourceDocType=$sourceDocType&strPrivacyType=$privacyType&strCreatedBy=$dataId&strEncodedImage=$image"));
request.headers
.set(HttpHeaders.contentTypeHeader, "application/json; charset=UTF-8");
final response = await request.close();
response.transform(utf8.decoder).listen((contents) {
print(contents);
});
return request;
}
So basically I send the "image" to Params because the API uses params.
although, i have a token xamarin gives 401 error when i post to rest api, or get..have you any solution ?
public async Task<List<Gorev>> GetGorevlerAsync(Gorev Gorev, string accessToken)
{
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
var json = JsonConvert.SerializeObject(Gorev);
HttpContent content = new StringContent(json);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
string uri = Constants.BaseApiAddress + "http/GorevTeamLstStored";
var ReturnJson = await client.PostAsync(uri, content);
var ls = ReturnJson.Content.ReadAsStringAsync().Result;
var Gorevler = JsonConvert.DeserializeObject<List<Gorev>>(ls);
return Gorevler;
.
}
I'm trying to use the Azure OCR API in Xamarin Forms. Here is the important bits of code. I'm using the ComputerVisionClient .net client
await CrossMedia.Current.Initialize();
if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
{
return;
}
var file = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions
{
SaveToAlbum = false
});
Img = new Image
{
Source = ImageSource.FromStream(() =>
{
var stream = file.GetStream();
return stream;
}),
};
using (var photoStream = file.GetStream())
{
var text = await _client.RecognizePrintedTextInStreamAsync(true, photoStream);
}
The Img is bound to an image on the view and it shows up when I take a picture so there is definetly an image. However RecognizePrintedTextInStreamAsync returns back "System.IO.FileNotFoundException: 'Invalid Image'" and I'm not sure why. Any ideas?
Edit. Added _client code
public static ComputerVisionClient Authenticate(string endpoint, string key)
{
ComputerVisionClient client =
new ComputerVisionClient(new ApiKeyServiceClientCredentials(key))
{ Endpoint = endpoint };
return client;
}
Called from my constructor and set as a global var
_client = Authenticate(endpoint, subscriptionKey);
Thanks
I am getting an image stream from TakePhotoAsync Method? Where do I need to change the code?
await CrossMedia.Current.Initialize();
if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
{
await DisplayAlert("Alert", "No camera is available!", "OK");
return;
}
camreaFile = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions
{
PhotoSize = Plugin.Media.Abstractions.PhotoSize.Small,
//SaveToAlbum = true,
Directory = "Sample",
Name = "test.jpg"
});
//mediaFile = await CrossMedia.Current.TakePhotoAsync();
if (camreaFile == null)
return;
fileName.Text = camreaFile.AlbumPath;
await DisplayAlert("File Location", camreaFile.Path, "OK");
image.Source = ImageSource.FromStream(() =>
{
var stream = camreaFile.GetStream();
//camreaFile.Dispose();
return stream;
});
--Pass parameter for server
if(mediaFile !=null)
{
MultipartFormDataContent content = new
MultipartFormDataContent();
content.Add(new StringContent(AppSetting.UserName),
"userId");
content.Add(new StringContent(remark), "remarks");
content.Add(new StringContent(AppSetting.ConsignmentNumebr), "consignmentNo");
content.Add(new StringContent(AppSetting.TaskId), "jobId");
content.Add(new StreamContent(cameraFile.GetStream()),"\"file\"",$"\"{AppSetting.ConsignmentNumebr + ".png"}\"");
var httpClient = new HttpClient();
var uploadServiceBaseAddress = "myserver/api/UploadContainerImage/"; var uploadResponseMessage = await httpClient.PostAsync(uploadServiceBaseAddress, content);uploadResponseMessage.Content.ReadAsStringAsync(); }
--I expect the output that successfully reaches the server.
Dispose of the Media file after you send it to the server to avoid this exception.
If you do that before you are sending it to the server, of course, it will give you an ObjectDisposedException
If you want to dispose of this variable just do it after the service call something like below:
FooServiceMethod();
mediaFile.Dispose();