I'd like to be able to take a photo, display it, and keep the location so I can save it to a record and be able to display it at a later point.
I've been able to display it fine using the code
BitmapImage bmp = newBitmapImage();
bmp.SetSource(e.ChosenPhoto);
myImage.Source = bmp2;
When myImage is the image being displayed, and e is a PhotoResult object. However, as I need to save this in a record, I tried to use this code to display the photo based on the location.
string imageLoc = e.OriginalFileName;
Uri imageUri = new Uri(imageLoc, UriKind.Relative);
StreamResourceInfo resourceInfo = Application.GetResourceStream(imageUri);
BitmapImage bmp = BitmapImage();
bmp.SetSource(resourceInfo.Stream);
myImage.Source = bmp;
When I run this code, I get a System.NullReferenceException. I assume it's to do with the Application.GetResourceStream, but I'm just not certain what's going wrong.
For clarification, I'd like to be able to load and display a photo from a location such as
'C:\Data\Users\Public\Pictures\Camera Roll\imageExample.jpg'
if you want to save image in windows phone device, you need to user IsolatedStorage.
Save Image =>
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();
}
Read Image =>
BitmapImage bi = new BitmapImage();
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile("logo.jpg", FileMode.Open, FileAccess.Read))
{
bi.SetSource(fileStream);
this.img.Height = bi.PixelHeight;
this.img.Width = bi.PixelWidth;
}
}
this.img.Source = bi;
If you want to get pictures from MediaLibrary (Camera roll, Saved Pictures ..) then you can accomplish your task:
using PhotoChooserTask
or using MediaLibrary and here is good example
Your code can look for example like this (I've edited it to use only Images from Camera Roll):
You get your picture stream with line picture.GetImage() - this method return Stream which you can use for example to copy to IsolatedStorage.
private void MyImg()
{
using (MediaLibrary mediaLibrary = new MediaLibrary())
foreach (PictureAlbum album in mediaLibrary.RootPictureAlbum.Albums)
{
if (album.Name == "Camera Roll")
{
PictureCollection pictures = album.Pictures;
foreach (Picture picture in pictures)
{
// example how to use it as BitmapImage
// BitmapImage image = new BitmapImage();
// image.SetSource(picture.GetImage());
// I've commented that above out, as you can get Memory Exception if
// you try to read all pictures to memory and not handle it properly.
// Example how to copy to IsolatedStorage
using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!storage.DirectoryExists("SavedImg"))
storage.CreateDirectory("SavedImg");
if (storage.FileExists("SavedImg" + #"\" + picture.Name))
storage.DeleteFile("SavedImg" + #"\" + picture.Name);
using (IsolatedStorageFileStream file = storage.CreateFile("SavedImg" + #"\" + picture.Name))
picture.GetImage().CopyTo(file);
}
}
}
}
}
Related
//Retrieve an image in Jpg format and store it into a variable.
var imgFile = (ImageFile)ScanerItem.Transfer(FormatID.wiaFormatJPEG);
var Path = #"D:\ScanImg.jpg";
// save the image in some path with filename.
imgFile.SaveFile(Path);
pictureBox1.ImageLocation = Path;
Based on the following SO answer, you can get the byte[] of the image with (byte[])imgFile.FileData.get_BinaryData():
converting .__comobj WIA to byte[] in C# application
A bitmap can be put as source into the PictureBox.
Therefore the byte[] as to put into a MemoryStream and create a Bitmap:
var imgFile = (ImageFile)ScanerItem.Transfer(FormatID.wiaFormatJPEG);
byte[] imageBytes = (byte[])imgFile.FileData.get_BinaryData();
Bitmap image;
using (MemoryStream stream = new MemoryStream(imageBytes))
{
image = new Bitmap(stream);
}
pictureBox1.Image = image;
I am developing an application which has many images & i want to implement that on clicking "save button" the Image should be stored to Photo Album.
Please reply i am new to app dev.
To work with this function you just need to pass needed Image as parameter in SaveImageToPhotoHub function.
private bool SaveImageToPhotoHub(WriteableBitmap bmp)
{
using (var mediaLibrary = new MediaLibrary())
{
using (var stream = new MemoryStream())
{
var fileName = string.Format("Gs{0}.jpg", Guid.NewGuid());
bmp.SaveJpeg(stream, bmp.PixelWidth, bmp.PixelHeight, 0, 100);
stream.Seek(0, SeekOrigin.Begin);
var picture = mediaLibrary.SavePicture(fileName, stream);
if (picture.Name.Contains(fileName)) return true;
}
}
return false;
}
Heres more to it http://www.codeproject.com/Articles/747273/How-to-Save-Image-in-Local-Photos-album-of-Windows
Try this code. This is in VB.Net but I am sure you can convert it yourself or through online tools for C#:
' Create a file name for the JPEG file in isolated storage.
Dim tempJPEG As String = "dummyImage1"
' Create a virtual store and file stream. Check for duplicate tempJPEG files.
Dim myStore = IsolatedStorageFile.GetUserStoreForApplication()
If myStore.FileExists(tempJPEG) Then
myStore.DeleteFile(tempJPEG)
End If
Dim myFileStream As IsolatedStorageFileStream = myStore.CreateFile(tempJPEG)
' Create a stream out of the sample JPEG file.
' For [Application Name] in the URI, use the project name that you entered
' in the previous steps. Also, TestImage.jpg is an example;
' you must enter your JPEG file name if it is different.
Dim sri As StreamResourceInfo = Nothing
Dim uri As New Uri("/projectName;component/Assets/1.jpg", UriKind.Relative)
sri = Application.GetResourceStream(uri)
' Create a new WriteableBitmap object and set it to the JPEG stream.
Dim bitmap As New BitmapImage()
bitmap.CreateOptions = BitmapCreateOptions.None
bitmap.SetSource(sri.Stream)
Dim wb As New WriteableBitmap(bitmap)
' Encode WriteableBitmap object to a JPEG stream.
wb.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.
Dim library As New MediaLibrary()
' Save the image to the saved pictures album.
Dim pic As Picture = library.SavePicture("dummyImage1.jpg", myFileStream)
MessageBox.Show("Image saved to saved pictures album")
myFileStream.Close()
I found on something like that:source https://msdn.microsoft.com.
// Informs when full resolution photo has been taken, saves to local media library and the local folder.
void cam_CaptureImageAvailable(object sender, Microsoft.Devices.ContentReadyEventArgs e)
{
string fileName = savedCounter + ".jpg";
try
{ // Write message to the UI thread.
Deployment.Current.Dispatcher.BeginInvoke(delegate()
{
txtDebug.Text = "Captured image available, saving photo.";
});
// Save photo to the media library camera roll.
library.SavePictureToCameraRoll(fileName, e.ImageStream);
// Write message to the UI thread.
Deployment.Current.Dispatcher.BeginInvoke(delegate()
{
txtDebug.Text = "Photo has been saved to camera roll.";
});
// Set the position of the stream back to start
e.ImageStream.Seek(0, SeekOrigin.Begin);
// Save photo as JPEG to the local folder.
using (IsolatedStorageFile isStore = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream targetStream = isStore.OpenFile(fileName, FileMode.Create, FileAccess.Write))
{
// Initialize the buffer for 4KB disk pages.
byte[] readBuffer = new byte[4096];
int bytesRead = -1;
// Copy the image to the local folder.
while ((bytesRead = e.ImageStream.Read(readBuffer, 0, readBuffer.Length)) > 0)
{
targetStream.Write(readBuffer, 0, bytesRead);
}
}
}
// Write message to the UI thread.
Deployment.Current.Dispatcher.BeginInvoke(delegate()
{
txtDebug.Text = "Photo has been saved to the local folder.";
});
}
finally
{
// Close image stream
e.ImageStream.Close();
}
}
// Informs when thumbnail photo has been taken, saves to the local folder
// User will select this image in the Photos Hub to bring up the full-resolution.
public void cam_CaptureThumbnailAvailable(object sender, ContentReadyEventArgs e)
{
string fileName = savedCounter + "_th.jpg";
try
{
// Write message to UI thread.
Deployment.Current.Dispatcher.BeginInvoke(delegate()
{
txtDebug.Text = "Captured image available, saving thumbnail.";
});
// Save thumbnail as JPEG to the local folder.
using (IsolatedStorageFile isStore = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream targetStream = isStore.OpenFile(fileName, FileMode.Create, FileAccess.Write))
{
// Initialize the buffer for 4KB disk pages.
byte[] readBuffer = new byte[4096];
int bytesRead = -1;
// Copy the thumbnail to the local folder.
while ((bytesRead = e.ImageStream.Read(readBuffer, 0, readBuffer.Length)) > 0)
{
targetStream.Write(readBuffer, 0, bytesRead);
}
}
}
// Write message to UI thread.
Deployment.Current.Dispatcher.BeginInvoke(delegate()
{
txtDebug.Text = "Thumbnail has been saved to the local folder.";
});
}
finally
{
// Close image stream
e.ImageStream.Close();
}
}
I am making a WP7 app which download all my twitter feed. In this I want to download all the profile images and store them locally and use them, so that they would be downloaded every time i open the app. Please suggest any of the methods to do so.
What I am doing: using a WebClient to download the image
public MainPage()
{
InitializeComponent();
WebClient client = new WebClient();
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
client.DownloadStringAsync(new Uri("http://www.libpng.org/pub/png/img_png/pnglogo-blk.jpg"));
}
and store it to a file.
void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (myIsolatedStorage.FileExists(fileName1))
myIsolatedStorage.DeleteFile(fileName1);
var fileName1 = "Image.jpg";
using (var fileStream = new IsolatedStorageFileStream(fileName1, FileMode.Create, myIsolatedStorage))
{
using (var writer = new StreamWriter(fileStream))
{
var length = e.Result.Length;
writer.WriteLine(e.Result);
}
var fileStreamLength = fileStream.Length;
fileStream.Close();
}
}
Now I am trying to set the image to a BitMapImage
BitmapImage bi = new BitmapImage();
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(fileName1, FileMode.Open, FileAccess.Read))
{
var fileStreamLength2 = fileStream.Length;
bi.SetSource(fileStream);
}
}
But I am not able to set source of the BitmapImage. It is throwing System.Exception and nothing specific. Am I doing it the right way? I mean the procedure.
EDIT Another observation is the fileStreamLength and fileStreamLength2 are different.
You're not supposed to use DownloadString to download a binary file. Use OpenReadAsync instead, and save the binary array to the isolated storage.
DownloadString will try to convert your data to UTF-16 text, which of course can't be right when dealing with a picture.
I am using visual studio 2010, (desktop application) and using LINQ to SQL to save image/video or audio files to database in dataType VarBinary (MAX). This I can do... Problem is, I can't get them and display them in xaml because I can't get the converting part correct. Here is what I have so far (though its not working);
private void bt_Click (object sender, RoutedEventArgs e)
{
databaseDataContext context = new databaseDataContext();
var imageValue = from s in context.Images
where s.imageID == 2
select s.imageFile;
value = imageValue.Single().ToString();
//convert to string and taking down to next method to get converted in image
}
public string value { get; set; }
public object ImageSource //taking from http://stackoverflow.com/
{
get
{
BitmapImage image = new BitmapImage();
try
{
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
image.UriSource = new Uri(value, UriKind.Absolute);
image.EndInit();
Grid.Children.Add(image);
}
catch { return DependencyProperty.UnsetValue; } return image;
}
}
I not even sure if I am on the correct track? And I am assuming that video or audio is quite similar methods?
Since your image is stored in binary format in the database, you want to "stream" this into an image object by leveraging the MemoryStream object.
Looking at your code, your solution will look something like this:
BitmapImage bmpImage = new BitmapImage();
MemoryStream msImageStream = new MemoryStream();
msImageStream.Write(value, 0, value.Length);
bmpCardImage.BeginInit();
bmpCardImage.StreamSource = new MemoryStream(msImageStream.ToArray());
bmpCardImage.EndInit();
image.Source = bmpCardImage;
It's very easy, if you have a binary data and want to create an Image object, use this code:
public Image BinaryToImage(byte[] binaryData)
{
MemoryStream ms = new MemoryStream(binaryData);
Image img = Image.FromStream(ms);
return img;
}
If you already have the bytes, to verify that what you saved is correct you can save the bytes to a file and open it....
string tempFile = Path.GetTempFileName();
MemoryStream ms = new MemoryStream(bytes); //bytes that was read from the db
//Here I assume that you're reading a png image, you can put any extension you like is a file name
FileStream stream = new FileStream(tempFile + ".png", FileMode.Create);
ms.WriteTo(stream);
ms.Close();
stream.Close();
//And here we open the file with the default program
Process.Start(tempFile + ".png");
And later you can use the answer of Dillie-O and stream....
Dillie-O's code makes for a very nice extension method:
// from http://stackoverflow.com/questions/5623264/how-to-convert-varbinary-into-image-or-video-when-retrieved-from-database-in-c:
public static BitmapImage ToImage(this Binary b)
{
if (b == null)
return null;
var binary = b.ToArray();
var image = new BitmapImage();
var ms = new MemoryStream();
ms.Write(binary, 0, binary.Length);
image.BeginInit();
image.StreamSource = new MemoryStream(ms.ToArray());
image.EndInit();
return image;
}
In a Silverlight app, I save a Bitmap like this:
public static void SaveBitmapImageToIsolatedStorageFile(OpenReadCompletedEventArgs e, string fileName)
{
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream isfs = new IsolatedStorageFileStream(fileName, FileMode.Create, isf))
{
Int64 imgLen = (Int64)e.Result.Length;
byte[] b = new byte[imgLen];
e.Result.Read(b, 0, b.Length);
isfs.Write(b, 0, b.Length);
isfs.Flush();
isfs.Close();
isf.Dispose();
}
}
}
and read it back out like this:
public static BitmapImage LoadBitmapImageFromIsolatedStorageFile(string fileName)
{
string text = String.Empty;
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!isf.FileExists(fileName))
return null;
using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream isoStream = isoStore.OpenFile(fileName, FileMode.Open))
{
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.SetSource(isoStream);
return bitmapImage; // "Catastrophic Failure: HRESULT: 0x8000FFFF (E_UNEXPECTED))"
}
}
}
}
but this always gives me a "Catastrophic Failure: HRESULT: 0x8000FFFF (E_UNEXPECTED))" error.
I've seen this error before when I tried to read a png file off a server which was actually a text file, so I assume the Bitmap is not being saved correctly, I got the code here.
Can anyone see how the BitmapImage is not being saved correctly? Or why it would be giving me this error?
Update:
When the BitmapImage is created, I see that the array of bytes that gets written is 1876 bytes long and they are all 0. Why would that be?
I got it to work but am unclear exactly why. I was calling SaveBitmapImageToIsolatedStorageFile(...) after this code:
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.SetSource(e.Result);
Image image = new Image();
image.Source = bitmapImage;
If I call it before that code, then it works.
Apparently SetSource() zeroes out the bytes in e.Result but keeps the length?