SignaturePad Xamarin Forms PCL unable to capture Image - xamarin

I am using SignaturePad Nuget for PCL.
How do i convert this System.IO.Stream into an Image?
Any idea would be appreciated.. Thank you.

Here's what I found after 2 weeks of research about this.
This is the code in c# to save an signature to a png file on android phone.
async void Enregistrer(object sender, EventArgs e)
{
// This is the code to get the image (as a stream)
var img = padView.GetImage(Acr.XamForms.SignaturePad.ImageFormatType.Png); // This returns the Bitmap from SignaturePad.
img.Seek(0,0); // This is to have the current position in the stream
// create a new file stream for writing
FileStream fs = new FileStream(Android.OS.Environment.ExternalStorageDirectory + "/imagefilename.png", FileMode.Create,FileAccess.Write); // create a new file stream for writing
await img.CopyToAsync(fs); // have the image stream to disk
fs.Close(); // close the filestream
img.Dispose(); // clear the ressourse used by the stream
}
have fun !

Related

Signature Pad Xamarin.Forms Saving signature as a file

I am a beginner in Xamarin.
I tried to write a simple app to save the signature with the help of Signature Pad.
A piece of code from MainPage.xaml
<controls:SignaturePadView x:Name="SignaturePAD"
Grid.Row="1"
StrokeColor="Black"
StrokeWidth="3"
BackgroundColor="Gray"
CaptionTextColor="Black"
PromptTextColor="Black"
SignatureLineColor="Black"
CaptionText="Podpis odbiorcy">
</controls:SignaturePadView>
<Button Grid.Row="2"
x:Name="SaveButton"
Text="Potwierdź"
Clicked="SaveSignature"/>
and a fragment from MainPage.xaml.cs
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
public async void SaveSignature(object sender, EventArgs e)
{
Stream image = await SignaturePAD.GetImageStreamAsync(SignatureImageFormat.Png);
}
}
And my question is how can I save it into the my phone gallery?
I will be grateful for any help
the SignaturePad returns a stream - so you can write it to a file using normal C# I/O, like FileStream
Stream image = await SignaturePAD.GetImageStreamAsync(SignatureImageFormat.Png);
using (FileStream file = new FileStream(file_path, FileMode.Create, System.IO.FileAccess.Write))
{
image.CopyTo(file);
}
You might be able to find a plugin somewhere that would do this for you, but I would convert the stream to a byte[] like so:
using (image)
using (var memoryStream = new MemoryStream())
{
await image.CopyToAsync(memoryStream);
var picture = memoryStream.ToArray();
}
Then convert the byte[] to the native picture on each platform.
For Android use:
BitmapFactory.DecodeByteArray(picture, 0, picture.Length);
And for iOS use:
var nsData = NSData.FromArray(picture);
var uiImage = UIImage.LoadFromData(nsData);
Then you would need to add the image to the underlying gallery. Here is an example of how to achieve something like that on iOS: https://developer.xamarin.com/recipes/ios/media/video_and_photos/save_photo_to_album_with_metadata/
For Android, this post might help: Xamarin.Forms Android save image to gallery

reviving image through sockets [Windows Store Apps - C# ]

I'm receiving an image on a Metro app through network socket every 1 second, loading it in an array of bytes, then convert it to a BitmapImage and display it later. All of this work fine.
The image is changing constantly on the other side. For some reason, it throws an OutOfMemory exceptions from now and then(like 1 in 10) . I fixed it by clearing the array of bytes every time the image is received. Now it works like charm.
See below for my main issue:
public static BitmapImage imag;
public static byte[] save = new byte[1];
if(recieved)
{
await reader.LoadAsync(4);
var sz = reader.ReadUInt32(); //read size
await reader.LoadAsync(sz); //read content
save = new byte[sz];
reader.ReadBytes(save);
await ImgSrcFromBytes(save)
Array.Clear(save, 0, save.Length); //issue here !!
}
public async Task<ImageSource> ImgSrcFromBytes(byte[] a)
{
imag = new BitmapImage();
var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream();
await stream.WriteAsync(a.AsBuffer());
stream.Seek(0);
imag.SetSource(stream);
return imag;
}
Now, i'm implementing a new function to save the image as a file if requested by the user with the code below, however, if i clear the array of bytes above, i get an unreadable image, but if i don't clear the array, i get a perfect image.
Note that no exceptions are thrown and both images have the same size.
FileSavePicker picker = new FileSavePicker();
picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
picker.SuggestedFileName = "capture.png";
picker.FileTypeChoices.Add("Png File", new List<string>() { ".png" });
StorageFile file = await picker.PickSaveFileAsync();
if (file != null)
{
CachedFileManager.DeferUpdates(file);
await FileIO.WriteBytesAsync(file, save);
await CachedFileManager.CompleteUpdatesAsync(file);
await new Windows.UI.Popups.MessageDialog("Image Saved Successfully !").ShowAsync();
}
I hope i'm clear. It's a trade-off, if i clear the array, i will get no exceptions while receiving streams over sockets, but i won't be able to get a readable image when saving. and vice versa.

Getting stream from file absolute path

This may sound very simple but I've lost a lot of time looking for answer
In my Windows phone 8 app I use the PhotoChooserTask to let the user choose the photo, and i get the path of the photo by using
string FileName = e.OriginalFileName;
where e is the PhotoResult argument of the Task. , let's say: FileName=
"C:\Data\SharedData\Comms\Unistore\data\18\k\2000000a00000018700b.dat" (selected from the cloud) or
"D:\Pictures\Camera Roll\WP_20140110_10_40_42_1_Smart.jpg" (from camera roll)
I want to save that string path and open it up and show the image again when the users reopen the app. But I cannot find a method to convert those string into Image data (BitmapImage or Stream)
Any idea?
private void PhotoChooserTaskCompleted(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
var image = new BitmapImage();
image.SetSource(e.ChosenPhoto);
SaveImageAsync(image);
}
}
public async void SaveImageAsync(BitmapImage image)
{
await Task.Run(SaveImage(image));
}
public async Task SaveImage(BitmapImage image)
{
IStorageFolder folder = await ApplicationData.Current.LocalFolder
.CreateFolderAsync("Images", CreationCollisionOption.OpenIfExists);
IStorageFile file = await folder.CreateFileAsync(
imageFileName, CreationCollisionOption.ReplaceExisting);
using (Stream stream = await file.OpenStreamForWriteAsync())
{
var wrBitmap = new WriteableBitmap(image);
wrBitmap.SaveJpeg(stream, image.PixelWidth, image.PixelHeight, 100, 100);
}
}
At Windows Phone 8.1 you can try "StorageFolder.GetFolderFromPathAsync" static method (if this API is available at your app flavor) and then get a stream for a necessary file from that folder.

Exporting a teechart chart to stream

I want to save a image to file and the documentation mentions ImageExportFormat method: Chart1.getExport().getImage().getJPEG().save(javax.imageio.stream.ImageOutputStream ios)
Doco: http://www.steema.com/files/public/teechart/java/v1/docs/JavaDoc/com/steema/teechart/exports/ImageExportFormat.html
This method is not recognised by my code. Has this been removed ? Is there an alternate way I can do this via a stream?
Regards, Clayton
The example below shows how to export to a jpeg file in Swing. A stream could be used natively instead of using ‘File’.
public void save() throws IOException {
Image img = chart1.image(chart1.getWidth(), chart1.getHeight());
RenderedImage rendImage = (RenderedImage) img;
Iterator iter = ImageIO.getImageWritersByFormatName("jpg");
File outfile = new File("c:\\output\\testjavaChart.jpg");
ImageOutputStream ios = ImageIO.createImageOutputStream(outfile);
ImageWriter writer = (ImageWriter) iter.next();
ImageWriteParam format = new javax.imageio.plugins.jpeg.JPEGImageWriteParam(java.util.Locale.getDefault());
writer.setOutput(ios);
// Write the image
writer.write(null, new IIOImage(rendImage, null, null), format);
// Cleanup
ios.flush();
ios.close();
writer.dispose();
}
If you are using SWT, don't hesitate to let us know.

How to upload image wp7 serverside.?

hello I have IsolatedStorageFile and this file is image so I want to upload this image to the serverside for the use of Avatar so how I can upload my byte[] of image.
my code like this.
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
// Open the file - error handling omitted for brevity
// Note: If the image does not exist in isolated storage the following exception will be generated:
// System.IO.IsolatedStorage.IsolatedStorageException was unhandled
// Message=Operation not permitted on IsolatedStorageFileStream
using (IsolatedStorageFileStream isfs = isf.OpenFile("myImage.jpg", FileMode.Open, FileAccess.Read))
{
// Allocate an array large enough for the entire file
data = new byte[isfs.Length];
// Read the entire file and then close it
isfs.Read(data, 0, data.Length);
isfs.Close();
}
}
// Create memory stream and bitmap
MemoryStream ms = new MemoryStream(data);
BitmapImage bi = new BitmapImage();
// Set bitmap source to memory stream
bi.SetSource(ms);
how I can upload this byte[] into webClient or HttpwebRequest.?
Thank you.!
Have you checked out the following link: File Upload. This should work.

Resources