I have a class that uses the devices camera to capture an image. My aim is to pass the captured image to a canvas on another layout.
This layout will then be saved along with a note entered into a textbox.I have figured out how to save the note and title and allow it to be opened but I'm not sure how I would go about passing the captured image to the layout and saving it along with the note.
Does anyone have any advice or pointers as to how I would go about this?
At the moment this is how I'm attempting to read the image file back to the layout after it is saved,but I'm not sure how to read a file into the canvas so obviously this solution isn't working yet:
if (NavigationContext.QueryString.ContainsKey("note"))
{
string s2 = ".jpg";
string filename = this.NavigationContext.QueryString["note"];
if (!string.IsNullOrEmpty(filename)) {
using (var store = System.IO.IsolatedStorage.IsolatedStorageFile .GetUserStoreForApplication())
using (var stream = new IsolatedStorageFileStream(filename, FileMode.Open, FileAccess.ReadWrite, store))
/*
if(filename.Contains(s2))
{
StreamReader reader = new StreamReader(stream);
this.capturedNoteCanvas = reader.ReadToEnd();
this.noteNameTb.Text = filename; reader.Close();
}
else
*/
{
StreamReader reader = new StreamReader(stream);
this.noteDataTb.Text = reader.ReadToEnd();
this.noteNameTb.Text = filename; reader.Close();
}
}
}
What I'm thinking is something like this:
Working wit CameraCaptureTask and Bitmaps
//Taking a writableBitmap object from cameracapturetask
void cameracapturetask_Completed(object sender, PhotoResult e)
{
try
{
if (e.TaskResult == TaskResult.OK)
{
BitmapImage bmp = new BitmapImage();
bmp.SetSource(e.ChosenPhoto);
WritableBitmap wb=new WritableBitmap (bmp.PixelWidth,bmp.PixelHeight);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
saving wb in storage
using (MemoryStream stream = new MemoryStream())
{
wb.SaveJpeg(stream, (int)bmp.PixelWidth, (int)bmp.PixelHeight, 0, 100);
using (IsolatedStorageFileStream local = new IsolatedStorageFileStream(App.PageName, FileMode.Create, mystorage))
{
local.Write(stream.GetBuffer(), 0, stream.GetBuffer().Length);
}
}
//Taking a WritableBitmap from canvas
If your canvas is containing the image, and also the canvas it attributed with some height and width properties then
WritableBitmap wb= new WritableBitmap(canvascontrol,null);
takes the canvas and saves it inside a writablebitmap object which can then be used for further image manipulations.
Related
Im new to Xamarin Android. Now I was trying to capture the image by camera and displaying in imageview but I was facing the problem which is the image quality that captured from camera is low. And I was doing the research from google and i only found the solution which is save the image that captured in to file and retrieve from file. But the solution is only for android studio and xamarin form.
This is the coding for the intent that calling image captured
Intent intent = new Intent(MediaStore.ActionImageCapture);
StartActivityForResult(intent, 1000);
This is the coding for onactivityresult,
if ((requestCode == PickImageId) && (resultCode == Android.App.Result.Ok) && (data != null))
{
base.OnActivityResult(requestCode, resultCode, data);
bitmap = (Bitmap)data.Extras.Get("data");
var dir = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDcim);
string filename = System.DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".jpg";
string filePath = System.IO.Path.Combine(dir + "/Camera/", filename);
using (var stream = new MemoryStream())
{
bitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, stream);
byte[] bitmapData = stream.ToArray();
try
{
System.IO.File.WriteAllBytes(filePath, bitmapData);
bitmap = BitmapFactory.DecodeByteArray(bitmapData, 0, bitmapData.Length);
imgview.SetImageBitmap(bitmap);
}
catch (Exception ex)
{
System.Console.WriteLine(ex.ToString());
}
}
}
I have try to save the image into phone folder which is 'DCIM/Camera/xxx.jpg'. The image that captured and save in folder is success but the image quality still low.
Is there have any solution to increase the quality of the image?
Sorry for my poor english, please provide me suggestion or solution.
Thanks for giving helps
Hello you can use Xamarin Essential Media Picker to take photo.
Here is an example code:
using Xamarin.Essentials;
string PhotoPath="";
public async Task TakePhotoAsync()
{
try
{
var photo = await MediaPicker.CapturePhotoAsync();
await LoadPhotoAsync(photo);
}
catch (FeatureNotSupportedException fnsEx)
{
// Feature is not supported on the device
}
catch (PermissionException pEx)
{
// Permissions not granted
}
catch (Exception ex)
{
Console.WriteLine($"CapturePhotoAsync THREW: {ex.Message}");
}
}
public async Task LoadPhotoAsync(FileResult photo)
{
// canceled
if (photo == null)
{
PhotoPath = null;
return;
}
// save the file into local storage
var newFile = Path.Combine(FileSystem.CacheDirectory, photo.FileName); //or any other Storage Directory
using (var stream = await photo.OpenReadAsync())
using (var newStream = File.OpenWrite(newFile))
await stream.CopyToAsync(newStream);
PhotoPath = newFile;
}
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 have searched all over the internet for this but i haven't really got the answer to this.
Part of the app am creating requires the user to take a photo and this photo is saved to the local database. i tried doing this as below but the method requires me to pass a bitmap (System.Windows.Media.Imaging) and the image control is well Image (System.Windows.Controls.Image)
public byte[] convertToByte(BitmapImage img)
{
using (MemoryStream ms = new MemoryStream())
{
WriteableBitmap btmap = new WriteableBitmap(img.PixelWidth, img.PixelHeight);
Extensions.SaveJpeg(btmap, ms, img.PixelWidth, img.PixelHeight, 0, 100);
ms.Seek(0, SeekOrigin.Begin);
return ms.ToArray();
};
}
the other solution i tried assumes my image is located within the app which is not the case as it is captured by the camera
public byte[] convertToByte(Image img)
{
BitmapImage image = new BitmapImage();
image.CreateOptions = BitmapCreateOptions.None;
image.UriSource = new Uri(img.Source.ToString(), UriKind.Relative);
WriteableBitmap wbmp = new WriteableBitmap(image);
MemoryStream ms = new MemoryStream();
wbmp.SaveJpeg(ms, wbmp.PixelWidth, wbmp.PixelHeight, 0, 100);
return ms.ToArray();
}
How can i redefine either of the methods to save the image? or is there a better way to do this?
Thanks in advance.
So i finally figured the answer to this a while back.
The things i've been through in the pursuit of this!
public Byte[] ImageToByteArray(Image img)
{
try
{
MemoryStream ms = new MemoryStream();
WriteableBitmap bmp = new WriteableBitmap(img.Source as BitmapSource);
bmp.SaveJpeg(ms, bmp.PixelWidth, bmp.PixelHeight, 0, 100);
Byte[] bytImage = ms.GetBuffer();
return bytImage;
}
catch (Exception ex)
{
return null;
}
}
Hope anyone who gets a similar problem gets helped!
i've been doing a essay about windowsphone. i created a address variable include a uri to add a image into address. There is a error when i use Isolate storage to save data. I don't know why.
Please help me!
Thank you so much.
class Address
{
private string name;
private Uri icon;
.....
}
......
public void save()
{
XmlWriterSettings xmlwritersetting = new XmlWriterSettings();
xmlwritersetting.Indent = true;
using (IsolatedStorageFile myisolatedstiragefile = IsolatedStorageFile.GetUserStoreForApplication())
{
if (myisolatedstiragefile.FileExists(filename))
{
myisolatedstiragefile.DeleteFile(filename);
}
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(filename, System.IO.FileMode.OpenOrCreate, myisolatedstiragefile))
{
XmlSerializer serializer = new XmlSerializer(typeof(List<Adress>));
using (XmlWriter writer = XmlWriter.Create(stream, xmlwritersetting))
{
serializer.Serialize(writer, listadress);
}
}
}
}
It's a little difficult for me to understand your question, but I'll try. You really should indicate what error you specifically get in the debugger and where it occurs.
But just by looking, it seems that you might be trying to use the XmlSerializer to write binary image data to iso-storage and that probably won't work. You can find many examples of using iso-storage for various purposes including writing image files here:
http://www.windowsphonegeek.com/tips/All-about-WP7-Isolated-Storage---Read-and-Save-Images
For example, it shows that you can save a JPG image to isolated storage by doing this:
// Create a filename for JPEG file in isolated storage.
String tempJPEG = "logo.jpg";
// Create virtual store and file stream. Check for duplicate tempJPEG files.
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication()) {
if (myIsolatedStorage.FileExists(tempJPEG)) {
myIsolatedStorage.DeleteFile(tempJPEG);
}
IsolatedStorageFileStream fileStream = myIsolatedStorage.CreateFile(tempJPEG);
StreamResourceInfo sri = null;
Uri uri = new Uri(tempJPEG, UriKind.Relative);
sri = Application.GetResourceStream(uri);
BitmapImage bitmap = new BitmapImage();
bitmap.SetSource(sri.Stream);
WriteableBitmap wb = new WriteableBitmap(bitmap);
// Encode WriteableBitmap object to a JPEG stream.
Extensions.SaveJpeg(wb, fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);
//wb.SaveJpeg(fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85); fileStream.Close();
}
I'm trying load image from Picture Hub through this...
void photoChooser_Completed(object sender, PhotoResult e)
{
try
{
var imageVar = new BitmapImage();
imageVar.SetSource(e.ChosenPhoto);
var b = new WriteableBitmap(imageVar.PixelWidth, imageVar.PixelHeight);
b.LoadJpeg(toStream(imageVar));//here comes the exception
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Stream toStream(BitmapImage img)
{
WriteableBitmap bmp = new WriteableBitmap((BitmapSource)img);
using (MemoryStream stream = new MemoryStream())
{
bmp.SaveJpeg(stream, bmp.PixelWidth, bmp.PixelHeight, 0, 100);
return stream;
}
}
Giving an error occurred when accessing the isolotedstorage. please help !
If I understand correctly, you are trying to:
Get image from a chooser (stream)
Create a bitmap object
Write it to another stream
Create a WriteableBitmap from that second stream
This is seriously convoluted. All you have to do is this:
var imageVar = new BitmapImage();
imageVar.SetSource(e.ChosenPhoto);
var b = new WriteableBitmap(imageVar.PixelWidth, imageVar.PixelHeight);
b.SetSource(e.ChosenPhoto);
This will get you the photo, but have in mind that if you first create a BitmapImage using the SetSource method, it will limit the size of your photo to be under 2000x2000. Then the WriteableBitmap will also be of that smaller, reduced size.
If you wish to create a full sized WriteableBitmap using LoadJpeg method, you need to do this:
//DO SOMETHING TO GET THE PIXEL WIDTH AND PIXEL HEIGHT OF PICTURE BASED JUST ON THE STREAM, FOR EXAMPLE USE EXIF READER: http://igrali.com/2011/11/01/reading-and-displaying-exif-photo-data-on-windows-phone/ OR SEE MORE ABOUT LOADING A LARGE PHOTO HERE: http://igrali.com/2012/01/03/how-to-open-and-work-with-large-photos-on-windows-phone/
var b = new WriteableBitmap(PixelWidth, PixelHeight);
b.LoadJpeg(e.ChosenPhoto);
That will load you the full sized JPEG.
The code you've used looks okay !
void photoChooser_Completed(object sender, PhotoResult e)
{
try
{
var imageVar = new BitmapImage();
imageVar.SetSource(e.ChosenPhoto);
var b = new WriteableBitmap(imageVar.PixelWidth, imageVar.PixelHeight);
b.LoadJpeg(toStream(imageVar));//here comes the exception
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Stream toStream(BitmapImage img)
{
WriteableBitmap bmp = new WriteableBitmap((BitmapSource)img);
using (MemoryStream stream = new MemoryStream())
{
bmp.SaveJpeg(stream, bmp.PixelWidth, bmp.PixelHeight, 0, 100);
return stream;
}
}
Try reconnecting USB !
You didnot specify, what you want to perform after fetching the Image.
If all you want is to display the image in your app, then you follow this code:
In your try block, simply add this
var imageVar = new BitmapImage();
imageVar.SetSource(e.ChosenPhoto);
Image img = new Image();
img.Source = imageVar;
this.ContentPanel.Children.Add(img);