How to convert ImageSource to Byte array?
I use LeadTools for scanning.
I want to convert scanning image to byte.
void twainSession_AcquirePage(object sender, TwainAcquirePageEventArgs e)
{
ScanImage = e.Image.Clone();
ImageSource source = RasterImageConverter.ConvertToSource(ScanImage, ConvertToSourceOptions.None);
}
How to convert ImageSource to Byte array?
Solution 1:
Unless you explicitly need an ImageSource object, there's no need to convert to one. You can get a byte array containing the pixel data directly from Leadtools.RasterImage using this code:
int totalPixelBytes = e.Image.BytesPerLine * e.Image.Height;
byte[] byteArray = new byte[totalPixelBytes];
e.Image.GetRow(0, byteArray, 0, totalPixelBytes);
Note that this gives you only the raw pixel data.
If you need a memory stream or byte array that contains a complete image such as JPEG, you also do not need to convert to source. You can use the Leadtools.RasterCodecs class like this:
RasterCodecs codecs = new RasterCodecs();
System.IO.MemoryStream memStream = new System.IO.MemoryStream();
codecs.Save(e.Image, memStream, RasterImageFormat.Jpeg, 24);
Solution 2:
I ran into this issue in Xamarin.Forms where I needed to convert a taken photo from the camera into a Byte array. After spending days trying to find out how, I saw this solution in the Xamarin forums.
var photo = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions() { });
byte[] imageArray = null;
using (MemoryStream memory = new MemoryStream()) {
Stream stream = photo.GetStream();
stream.CopyTo(memory);
imageArray = memory.ToArray();
}
Source: https://forums.xamarin.com/discussion/156236/how-to-get-the-bytes-from-the-imagesource-in-xamarin-forms
Solution 3:
If you are using Xamarin, you can use this:
public byte[] ImageSourceToBytes(ImageSource imageSource)
{
StreamImageSource streamImageSource = (StreamImageSource)imageSource;
System.Threading.CancellationToken cancellationToken =
System.Threading.CancellationToken.None;
Task<Stream> task = streamImageSource.Stream(cancellationToken);
Stream stream = task.Result;
byte[] bytesAvailable = new byte[stream.Length];
stream.Read(bytesAvailable, 0, bytesAvailable.Length);
return bytesAvailable;
}