I am converting png to Jpeg using this code but it is getting stuck on encoder.FlushAsync() and never returns. I have tried several ways to resolve this but nothing works. encoder.FlushAsync() doesn't even give exceptions. Without await debug gets passed but the image is not correct and with await, application freezed. I have mentioned the link and code below:
https://www.syncfusion.com/kb/7918/how-to-convert-jpeg-image-from-png-image-and-draw-those-jpeg-image-into-pdf-document
public async Task<Stream> ConvertPngToJpeg2(Stream s)
{
byte[] resultArray = null;
//Convert stream into byte array
byte[] image = new byte[s.Length];
s.Read(image, 0, image.Length);
//Create An Instance of WriteableBitmap object
WriteableBitmap resultBitmap = new WriteableBitmap(1, 1);
using (IRandomAccessStream ms = new InMemoryRandomAccessStream())
{
await ms.WriteAsync(image.AsBuffer());
ms.Seek(0);
//Set the source for WriteableBitmap
resultBitmap.SetSource(ms);
}
//Get the image data
using (IRandomAccessStream ms = new InMemoryRandomAccessStream())
{
try
{
byte[] bytes;
// Open a stream to copy the image contents to the WriteableBitmap's pixel buffer
using (Stream stream = resultBitmap.PixelBuffer.AsStream())
{
bytes = new byte[(uint)stream.Length];
await stream.ReadAsync(bytes, 0, bytes.Length);
}
// Create an encoder with the Jpeg format
BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, ms);
// WriteableBitmap uses BGRA format
encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)resultBitmap.PixelWidth, (uint)resultBitmap.PixelHeight, 96, 96, bytes);
//Terminate the encoder bytes
await encoder.FlushAsync();
resultArray = new byte[ms.AsStream().Length];
await ms.AsStream().ReadAsync(resultArray, 0, resultArray.Length);
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine(e.Message);
}
}
//Store the image into memory stream
Stream imgStream = new MemoryStream(resultArray);
//Return the Jpeg image as stream
return imgStream;
}
gone through some links:
BitmapEncoder FlushAsync() never returns
BitmapEncoder FlushAsync throws Argument Exception - c#
We have attached the runnable sample for your reference. Please try this on your end and let us know the result.
Sample: https://www.syncfusion.com/downloads/support/directtrac/general/ze/UWP_Sample-1957906502
Related
Hello i try to send Image to Web api from my xamarin-forms app and save it in my database but i have problem with convert to base 64
i Used plugin to pick image and i try to convert it to Image base 64 and it didnt give me corect string image base 64
_aktFile = await CrossMedia.Current.PickPhotoAsync();
if (_aktFile == null)
return;
ImageSource = ImageSource.FromStream(() =>
{
ImageStream = _aktFile.GetStream();
ImageMessageByteArray = new byte[_ImageStream.Length];
ImageStream.Read(_ImageMessageByteArray, 0, (int)_ImageStream.Length);
ImageMessageBase64 = System.Convert.ToBase64String(_ImageMessageByteArray);
return _aktFile.GetStream();
});
_aktFile = await CrossMedia.Current.PickPhotoAsync();
if (_aktFile == null)
return;
else
{
string Base64String = ConvertStreamToBase64(_aktFile);
}
private string ConvertStreamToBase64(Stream stream)
{
if (stream != null)
{
byte[] bytes;
using (var memoryStream = new MemoryStream())
{
stream.Seek(0, SeekOrigin.Begin);
stream.CopyTo(memoryStream);
bytes = memoryStream.ToArray();
}
base64selectedImage = Convert.ToBase64String(bytes);
stream.Seek(0, SeekOrigin.Begin);
}
return base64selectedImage;
}
How can I load a bitmap into an ImageViewAsync on Xamarin Android Native?
You can use LoadStream method, here you will see how to use this method:
ImageService.Instance
.LoadStream (GetStreamFromImageByte)
.Into (imageView);
Here is the GetStreamFromImageByte:
Task<Stream> GetStreamFromImageByte (CancellationToken ct)
{
//Here you set your bytes[] (image)
byte [] imageInBytes = null;
//Since we need to return a Task<Stream> we will use a TaskCompletionSource>
TaskCompletionSource<Stream> tcs = new TaskCompletionSource<Stream> ();
tcs.TrySetResult (new MemoryStream (imageInBytes));
return tcs.Task;
}
About imageInBytes, you can look here, convert the bitmap to byte[]:
MemoryStream stream = new MemoryStream();
bitmap.Compress(Bitmap.CompressFormat.Png, 100, stream);
byte[] bitmapData = stream.ToArray();
I have posted my demo on github.
I'm using xamarin SignaturePad.
How to use GetImageAsync properly? because the output is not the same with my input.
I use this code:
var imageStream = await signature.GetImageStreamAsync(SignatureImageFormat.Jpeg);
public static byte[] ConvertStreamToByte(Stream stream)
{
if (stream != null)
{
using (MemoryStream memoryStream = new MemoryStream())
{
stream.CopyTo(memoryStream);
return memoryStream.ToArray();
}
}
return null;
}
Convert Byte[] to Image.
this.SignatureImage = ImageSource.FromStream(() => new MemoryStream(signatureData.Data));
My input on top.
Bottom pic is the retrieved data.
Is it misuse of GetImageAsync or Wrong Conversion? Help.
var imageStream = await signature.GetImageStreamAsync(SignatureImageFormat.Jpeg
, Color.Black, Color.White);
Need to add color for stroke and backround else it will default to black.
I am getting error width cannot be null , when passing image to inputstream.As i didn't find any alterante method . Basically i want to convert image to Pdf format in Xamarin.forms which supports UWP platform .
I am using xfinium pdf library for this.
public void ConvertJpegToPdf()
{
try
{
PdfFixedDocument document = new PdfFixedDocument();
Xfinium.Pdf.PdfPage page = document.Pages.Add();
page.Width = 800;
page.Height = 600;
var imageStream = GetStream();
PdfJpegImage jpeg = new PdfJpegImage(imageStream);//<-Error
PdfStandardFont helvetica = new PdfStandardFont(PdfStandardFontFace.Helvetica, 24);
PdfBrush brush = new PdfBrush(PdfRgbColor.Red);
page.Graphics.DrawImage(jpeg, 0, 0, page.Width, page.Height);
Stream pdfStream = null;
document.Save(pdfStream);
}
catch (Exception ex)
{
throw ex;
}
}
protected Stream GetStream()
{
byte[] byteArray = Encoding.UTF8.GetBytes("http://david.qservicesit.com/images/3.jpg");
MemoryStream stream = new MemoryStream(byteArray);
return stream;
}
Please suggest some alternate to do this
byte[] byteArray = Encoding.UTF8.GetBytes("http://david.qservicesit.com/images/3.jpg");
You could not get image stream in this way. The method you have used can only get the Bytes of string. For your scenario, you could use http client to acquire image stream. Please refer to the following code:
public async Task<Stream> GetStream()
{
HttpClient client = new HttpClient();
HttpResponseMessage res = await client.GetAsync(new Uri("http://david.qservicesit.com/images/3.jpg"));
Stream stream = await res.Content.ReadAsStreamAsync();
return stream;
}
public async Task ConvertJpegToPdf()
{
try
{
PdfFixedDocument document = new PdfFixedDocument();
Xfinium.Pdf.PdfPage page = document.Pages.Add();
page.Width = 800;
page.Height = 600;
var imageStream = await GetStream();
PdfJpegImage jpeg = new PdfJpegImage(imageStream);
PdfStandardFont helvetica = new PdfStandardFont(PdfStandardFontFace.Helvetica, 24);
PdfBrush brush = new PdfBrush(PdfRgbColor.Red);
page.Graphics.DrawImage(jpeg, 0, 0, page.Width, page.Height);
Stream pdfStream = new MemoryStream();
document.Save(pdfStream);
}
catch (Exception ex)
{
throw ex;
}
}
May I know how to convert image (take from folder/take from Camera) to Byte Array?
& also convert Byte Array to image?
Take Photo From Camera
async void TakePhoto()
{
try
{
var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
{
Directory = "Sample",
Name = "test.jpg",
//SaveToAlbum = saveToGallery.IsToggled
});
if (file == null)
return;
// await DisplayAlert("File Location", (saveToGallery.IsToggled ? file.AlbumPath : file.Path), "OK");
img.Source = ImageSource.FromStream(() =>
{
var stream = file.GetStream();
file.Dispose();
return stream;
});
}
catch
{
}
}
Take Photo From Folder
async void FromFolder()
{
try
{
Stream stream = null;
var file = await CrossMedia.Current.PickPhotoAsync().ConfigureAwait(true);
if (file == null)
return;
stream = file.GetStream();
file.Dispose();
img.Source = ImageSource.FromStream(() => stream);
}
catch
{
}
}
I dont know where are the location of Image, and where to get the image.
I'm trying to save image into Azure database. But i'm facing problem to convert MediaFile into Byte[]. I'm using Xam.Plugin.Medie ( http://www.nuget.org/packages/Xam.Plugin.Media ) to access camera and gallery. Please kindly guide me how to convert MedieFile into Byte[]. Thank you.
Any sample source code for references