Covert xamarin.image into base 64 format - image

I need to Convert a xamarin forms image into a base64 format, Can anyone help me with this?
This is how i've being trying to do it, but it doesent work.
var inputStream = signatureImage.Source.GetValue(UriImageSource.UriProperty);
//Getting Stream as a Memorystream
var signatureMemoryStream = inputStream as MemoryStream;
if (signatureMemoryStream == null)
{
signatureMemoryStream = new MemoryStream();
inputStream.CopyTo(signatureMemoryStream);
}
//Adding memorystream into a byte array
var byteArray = signatureMemoryStream.ToArray();
//Converting byte array into Base64 string
base64String = Convert.ToBase64String(byteArray);
"signatureImage" is the image name.

Once you get your file path , you can use the following code that worked for me.
var stream = file.GetStream();
var bytes = new byte [stream.Length];
await stream.ReadAsync(bytes, 0, (int)stream.Length);
string base64 = System.Convert.ToBase64String(bytes);
I found it here

Image is just a control in Xamarin forms to display the image.
It is not something from which you can get your image byte array out.
You will be better of using the Media Plugin and save it to disk. Then load it via memory stream and convert.
You can also use FFImageLoading. It has 2 methods which can be of use for you :
GetImageAsJpgAsync(int quality = 90, int desiredWidth = 0, int desiredHeight = 0)
GetImageAsPngAsync(int desiredWidth = 0, int desiredHeight = 0)
The SO question - Convert Image into byte array in Xamarin.Forms shows how to do it in Platform specific code here.
The forum thread (Convert Image to byte[]) has a good discussion on why you can't get it from the control.

You can do this as below as well
var base64String = Convert.ToBase64String(File.ReadAllBytes(file.Path))

Related

Convert from Android.Media.Image to Android.Graphics.Bitmap (possibily with Xamarin)

I have a Android.Media.Image frame acquired from Camera2 API Preview (in a Xamarin app), that I want to process.
The image format is YUV_420_888.
In a previous iteration I was able to get a Android.Graphics.Bitmap from the CameraPreview (but not anymore), and with that bitmap I was able to:
crop it
convert it to JPEG, save it or send it to server
convert it to a Mat to process with Emgu in real time
I searched for how to convert from Android.Media.Image to Android.Graphics.Bitmap thinking it was going to be quite straightforward, but it's not.
I found mostly java code that I tried to convert to C# Xamarin but without success.
First step is supposed to be to convert to a YuvImage (found 2 different versions, hence the comments):
private static byte[] YUV_420_888toNV21(Android.Media.Image image)
{
byte[] nv21;
ByteBuffer yBuffer = image.GetPlanes()[0].Buffer;
ByteBuffer uBuffer = image.GetPlanes()[1].Buffer;
ByteBuffer vBuffer = image.GetPlanes()[2].Buffer;
int ySize = yBuffer.Remaining();
int uSize = uBuffer.Remaining();
int vSize = vBuffer.Remaining();
nv21 = new byte[ySize + uSize + vSize];
//yBuffer.Get(nv21, 0, ySize);
//vBuffer.Get(nv21, ySize, vSize);
//uBuffer.Get(nv21, ySize + vSize, uSize);
yBuffer.Get(nv21, 0, ySize);
uBuffer.Get(nv21, ySize, uSize);
vBuffer.Get(nv21, ySize + uSize, vSize);
return nv21;
}
And then the saving:
var bbitmap = YUV_420_888toNV21(image);
YuvImage yuv = new YuvImage(bbitmap, ImageFormatType.Nv21, image.Width, image.Height, null);
var ms = new MemoryStream();
yuv.CompressToJpeg(new Android.Graphics.Rect(0, 0, image.Width, image.Height), 100, ms);
File.WriteAllBytes("/sdcard/Download/testFrame.jpg", ms.ToArray());
But this is the result:
This was just a test to actually save and check the captured frame, because at the end of this I still don't have a Bitmap (even if it was working).
In cas of real time processing, I don't want/need the JPG conversion becaus it would only slow down everything.
I'd like to convert the Image to a Bitmap, crop it and feed it to Emgu as a Mat.
Any suggestion?
Thanks

How to decode the image which is a base64 string, in Dart?

I tried to get the image from clipboard when I press ctrl+v on a page, with the code from a gist, which will console.log the image content it gets.
I found the image content is a long base64 string with a special prefix:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEEAAAAUCAYAAADStFABAAAJHElEQVRYCXVXWXObVxl+Pu2yFsuyLMnxHtdpY8c4pHXptOkEGKBlYDowYXLLLeGSX8D/gBvuErhgmElpJkCZNsswjhPZsbHGJo6Rl1pybMuyZEnWyvsc9xVfMvCOj8457/K8y9k+W5lMpi0EJcuywDn7ZrMJh8OBVqulYsMnT2WqSx3ylWivdnZM6lOPPRuJcpIdQ23IVz2Oyadvl8tlevLUL2XEUFv1Qx2S8lXnjAu4yPhfAdGARJmCaTAMgqS2drkGQrmOKVf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95I6RI9CWYyqNY/IoiyCJi2OXO/EQk4utuTI+a35+vs3KqhOOKeCZPtnaQvbhA3ikEOfemEAsmZSo5I3ezeKr9eeoyb2RvHoNgUHZmmKjBaUD4hBDC0zHxfwmcmt/hd+dRf9QAjH52iTt7+2ZD5xqox/xie/KzhsxiROTOFpQYiiRv1fYwbONR6ghj9GBEcS/xssJ3sZ2Bt52N2bGryIR+W98xCQRU3O1UqlUWxNQh6w2HXrl5ke5jPzKCg7X1+WOyBqAUCKJqNwZPZOT5sKsyCtBYiHZiGNfPXXokye2WSsi/9UiDrMrKBd3jF0gPIiexCSiAzNwyD3BS8serNpTmXz6IBGv1qpifWcZ2/vrck3JHSZfc9FIAkPxNzDWPymXpV9ejXoHj7aKzUUyeHNzc20NXFdQnZJPxUAgYBzqSlDvVHZHqVRCVb4Z7CtOGxaAPOqRFJ9j8kOhEDwejzmX9MUgmfjJyYnBUxv604DJ0wIQQ4k6QXkluGAaH/HouyAfdfqtQVsuDmNRHO3Nv9K6LdQRewZHJYIQlA50p5Cvcl4wTFoLRxmDVAfkK3FMPAZHIh5xGbBiaME4Vz/kaSMG9dmTxzHjI5b6JTZt6cvOo402xTZ2ymSvRAGVlBiQBkWeBsTx63rkKRb1mCTn1GMjj8GpHuck9pRrUZRPv4yHRLnGpjyNi3MtDnXteelYMSknkU+b/wD4ldY7nz0NzAAAAABJRU5ErkJggg==
How to decode it to binary? I tried to remove the prefix data:image/png;base64, and use a base64 library to decode the rest into binary, and save it to a image.png file. But the file can't be displayed, with invalid format error.
But if I paste the whole string to http://base64online.org/decode/, it can play the image as well.
The base64 library I used is https://github.com/wstrange/base64, and my code is:
import 'package:base64_codec/base64_codec.dart';
var body = /* the long str above */;
var prefix = "data:image/png;base64,";
var bStr = body.substring(prefix.length);
var bs = Base64Codec.codec.decodeList(bStr.codeUnits);
var file = new File("image.png");
file.writeAsBytesSync(bs);
I don't know where is wrong :(
Try using the crypto package from the Dart SDK. This creates an image.png that opens fine (I believe it's this image... )
library foo;
import 'package:crypto/crypto.dart';
import 'dart:io';
void main() {
var body = "data:image/png;base64,iVBORw0KGgoAAAANSUh... snip";
var prefix = "data:image/png;base64,";
var bStr = body.substring(prefix.length);
var bytes = CryptoUtils.base64StringToBytes(bStr); // using CryptoUtils from Dart SDK
var file = new File("image.png");
file.writeAsBytesSync(bytes);
}
You'll need to add crypto to your pubspec.yaml :
dependencies:
crypto: any
The library linked at https://github.com/wstrange/base64, also notes in the README:
Deprecated
Note: The Dart SDK now includes a Base64 codec with url safe options. Unless you need streaming support, you should use the SDK methods as they are slightly faster.
See CryptoUtils
See also How to native convert string -> base64 and base64 -> string
Decoding as a string and then writing the bytes works:
var prefix = "data:image/png;base64,";
var bStr = body.substring(prefix.length);
var bs = Base64Codec.codec.decodeString(bStr);
var file = new File("image.png");
file.writeAsBytesSync(bs.codeUnits);
The easiest approach is:
import 'dart:convert';
final result = base64Decode(stringValue);

Converting image to bytes

I am using the below code for converting a png image in local path(D:\CURR PROJECT\NewUIChanges\Htmlfile\round1.png)to bytes.I am getting a null execption ie)img stream is null.Plz hep me.
Stream imgStream;
imgStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("NewUIChanges.Htmlfile.round1.png");
byte[] data = new byte[(int)imgStream.Length];
int offset = 0;
while (offset < data.Length)
{
int bytesRead = imgStream.Read(data, offset, data.Length - offset);
if (bytesRead <= 0)
{
throw new EndOfStreamException("Stream wasn't as long as it claimed");
}
offset += bytesRead;
}
Change the build action of the image to Embedded Resource.
This line generating a problem. imgStream is null.
imgStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("NewUIChanges.Htmlfile.round1.png");
Check your image path. Probably is wrong.

Image to Byte array conversion

I need to convert image to Byte array as I have to upload to server, have seen many articles but i am not able to understand ho wit is done, forgive me if you think my question is up-to be asked in this forum
If you have a WriteableBitmap, for example called LoadedPhoto, you can try:
using (MemoryStream ms = new MemoryStream()
{
LoadedPhoto.SaveJpeg(ms, LoadedPhoto.PixelWidth, LoadedPhoto.PixelHeight, 0, 95);
ms.Seek(0, 0);
byte[] data = new byte[ms.Length];
ms.Read(data, 0, data.Length);
ms.Close();
}
If you're using WriteableBitmapEx library from CodePlex, it can do a conversion to byte array, too
http://writeablebitmapex.codeplex.com/
I assume that it is a Bitmap (however it works for all image types) :
System.Drawing.Bitmap bmp = GetYourImage();
System.IO.MemoryStream stream = new System.IO.MemoryStream();
bmp.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
stream.Position = 0;
byte[] data = stream.ToArray();

Is there a way to change the Transmission size when ftp'ing in .NET 2.0?

My ftp is truncating data. Using a different product we are able to change the tranmissions size and it works. But I can't figure out hwo to do it in .NET.
// FTP the file
FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpfullpath);
ftp.Credentials = new NetworkCredential(user, pwd);
ftp.KeepAlive = true;
ftp.UseBinary = false; //Use ascii.
ftp.Method = WebRequestMethods.Ftp.UploadFile;
FileStream fs = File.OpenRead(inputfilepath + ftpfileName);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
fs.Close();
Stream ftpstream = ftp.GetRequestStream();
ftpstream.Write(buffer, 0, buffer.Length);
ftpstream.Close();
Just a thought...Before closing your streams, try to Flush them to see if it helps. I'm not sure if changing your transmission size will really do anything.

Resources