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);
Related
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;
}
}
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 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.
I am developing app in which i have check first the images is present in isolated storage.If image is not there then i download first and then store them in isolated storage .But I got exception "An exception of type 'System.ObjectDisposedException' occurred in mscorlib.ni.dll but was not handled in user code " at using (IsolatedStorageFileStream mystream = istore.CreateFile(item.ImageUrl)).
private void checkimage(Model item)
{
using (IsolatedStorageFile istore = IsolatedStorageFile.GetUserStoreForApplication())
{
if (istore.FileExists(item.ImageUrl))
{
}
else
{
BitmapImage imgage = new BitmapImage(new Uri(item.ImageUrl, UriKind.Absolute));
imgage.CreateOptions = BitmapCreateOptions.BackgroundCreation;
imgage.ImageOpened += (o, e) =>
{
using (IsolatedStorageFileStream mystream = istore.CreateFile(item.ImageUrl))
{
BitmapImage bitmap = new BitmapImage();
bitmap.SetSource(mystream);
WriteableBitmap wb = new WriteableBitmap(bitmap);
Extensions.SaveJpeg(wb, mystream, wb.PixelWidth, wb.PixelHeight, 0, 85);
mystream.Close();
}
};
}
}
}
It looks like istore has been destroyed at the time, when you trying to create the file. Try to create (istore) again in the event body or use global variable and handle dispose by hand.
For example: move BitmapImage imgage... outside the first using and create istore again.
private void SaveAsPicture_Click(object sender, RoutedEventArgs e)
{
WriteableBitmap bmp = new WriteableBitmap(MyUIElement, null);
var library = new MediaLibrary();
MemoryStream stream = new MemoryStream();
bmp.SaveJpeg(stream, 100, 100, 0, 90);
library.SavePicture("Certificate", stream);
}
This should save the rendering of the MyUIElement to a bmp then save that as a Jpeg in the medialibrary but i'm getting a value does not fall within expected range error on the line with library.SavePicture("Certificate", stream);
Any ideas?
I got the same error like the one you had. And I solved it by following the example on How to: Encode a JPEG for Windows Phone and Save to the Pictures Library on MSDN.
So your method should look as following
private void SaveAsPicture_Click(object sender, RoutedEventArgs e)
{
WriteableBitmap bmp = new WriteableBitmap(MyUIElement, null);
library.SavePicture("Certificate", stream);
String tempJPEG = "TempJPEG";
// Create a virtual store and file stream. Check for duplicate tempJPEG files.
var myStore = IsolatedStorageFile.GetUserStoreForApplication();
if (myStore.FileExists(tempJPEG))
{
myStore.DeleteFile(tempJPEG);
}
IsolatedStorageFileStream myFileStream = myStore.CreateFile(tempJPEG);
bmp.SaveJpeg(myFileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);
myFileStream.Close();
// Create a new stream from isolated storage, and save the JPEG file to the media library on Windows Phone.
myFileStream = myStore.OpenFile(tempJPEG, FileMode.Open, FileAccess.Read);
// Save the image to the camera roll or saved pictures album.
MediaLibrary library = new MediaLibrary();
// Save the image to the camera roll album.
library.SavePicture("Certificate", myFileStream);
}