How to store image on button click in windows phone 8? - c#

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();
}
}

Related

C# TagLib raise 0xc00d36c4 after add Album Image From Url

I try to add album image to my mp3 audio file use TagLib.
but if I open mp3 file after adding album art, the player raises the error 0xc00d36c4.
this is the code I tried...
var wReq = (HttpWebRequest)WebRequest.Create(procItem.Thumbnail);
var wRes = (HttpWebResponse)wReq.GetResponse();
byte[] buffer = new byte[1024];
using (MemoryStream ms = new MemoryStream())
{
using (Stream s = wRes.GetResponseStream())
{
int data;
while ((data = s.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, data);
}
}
TagLib.File tagFile = TagLib.File.Create(procItem.DownloadDirectory);
IPicture newArt = new Picture(ms.ToArray());
tagFile.Tag.Pictures = new IPicture[1] { newArt };
tagFile.Save();
}
one of interesting thing is if I load an mp3 file info in my program, the image control draw album art.
It just raised when mp3 file open.
procitem.Thumbnail is the album image Url

Loading Image from memory in Windows Phone

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);
}
}
}
}
}

Adding Text on Image

I am trying to add some text on top of a photo take by the camera, and here is the method I am using, but unfortunately I either get a closedStream error, or that there is cross-thread access when I try use the dispatcher. Could someone please explain me what is going wrong?
void cam_CaptureImageAvailable(object sender, Microsoft.Devices.ContentReadyEventArgs e)
{
DateTime dt = DateTime.Now;
string fileName = dt.Year.ToString() + dt.Month.ToString() + dt.Day.ToString() + dt.Hour.ToString() + dt.Minute.ToString() + dt.Second.ToString() + ".jpg";
try
{
// Save picture to the library camera roll.
library.SavePictureToCameraRoll(fileName, e.ImageStream);
// Set the position of the stream back to start
e.ImageStream.Seek(0, SeekOrigin.Begin);
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
// load photo to writable bitmap
WriteableBitmap writeableBitmap = PictureDecoder.DecodeJpeg(e.ImageStream);
writeableBitmap.Invalidate();
var renderText = new TextBlock
{
Text = "Hello World",
FontSize = 72,
Foreground = new SolidColorBrush(Colors.White),
FontWeight = FontWeights.Black,
Width = 500,
Height = 100
};
writeableBitmap.Render(renderText, new TranslateTransform() { X = 100, Y = 300 });
writeableBitmap.Invalidate();
using (var ms = new MemoryStream())
{
writeableBitmap.SaveJpeg(ms, 1024, 768, 0, 100);
ms.Seek(0, SeekOrigin.Begin);
library.SavePicture("x" + fileName, ms);
}
// e.ImageStream.Close();
});
// Save picture as JPEG to isolated storage.
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 isolated storage.
while ((bytesRead = e.ImageStream.Read(readBuffer, 0, readBuffer.Length)) > 0)
{
targetStream.Write(readBuffer, 0, bytesRead);
}
}
}
}
finally
{
// Close image stream
e.ImageStream.Close();
}
}
With the code above I get the following error: Cannot access a closed Stream.
If i remove the Dispatcher, I get this error: Invalid cross-thread access.
Thanks.
place ui less code outside dispatcher scope.
or save your e.ImageStream to other stream can be gotted in dispatcher scope.
First, what is occurring?
Dispatcher.BeginInvoke postpones your code and tells the UI thread to execute it whenever it's available. Therefore, your e.ImageStream.Close(); line is executed before the code inside of the BeginInvoke. So when you're trying to read the contents of the stream, it's already closed.
Two ways to solve that:
Remove the e.ImageStream.Close(); from the finally block. But I don't know if the stream will remain open anyway.
If 1. doesn't work, copy the contents of the stream to a MemoryStream, then use this stream to create the WriteableBitmap:
var stream = new MemoryStream();
e.ImageStream.CopyTo(stream);
In both case, don't forget to close the stream when you're done creating the WriteableBitmap.

How can I reduce the size of an image

I am trying to reduce the size of an Image I am taking from the camera before I save it to Isolated Storage. I already have it reduced to the lowest resolution (640x480) How can I reduce the bytes to 100kb instead of what they are coming out at almost 1mb.
void cam_CaptureImageAvailable(object sender, Microsoft.Devices.ContentReadyEventArgs e)
{
string fileName = folderName+"\\MyImage" + savedCounter + ".jpg";
try
{
// Set the position of the stream back to start
e.ImageStream.Seek(0, SeekOrigin.Begin);
// Save picture as JPEG to isolated storage.
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 isolated storage.
while ((bytesRead = e.ImageStream.Read(readBuffer, 0, readBuffer.Length)) > 0)
{
targetStream.Write(readBuffer, 0, bytesRead);
}
}
}
}
finally
{
// Close image stream
e.ImageStream.Close();
}
}
I have nothing about Windows Phone, but maybe this link will help you:
http://msdn.microsoft.com/en-us/library/ff769549(v=vs.92).aspx
1) load your jpeg
2) copy to bitmap
3) save as bitmap with quality settings
http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.extensions.savejpeg(v=vs.92).aspx

Read Xml file and save content into memory WP7

I have a xml with data, in this case images stored in the internet..i want to read the xml in windows phone and save it to the memory.. how can i do that? any tutorial?
Lets divide your task into two parts
1. Downloading XML file containing image path
2. Reading that XML file and binding image control to that dynamic path
Lets Proceeds with first case:
1. Downloading XML file containing image path
here Path=http://server_adrs/XML_FILE
iso_path=Path inside Isolated Storage where u want to save XML file.
public void GetXMLFile(string path)
{
WebClient wcXML = new WebClient();
wcXML.OpenReadAsync(new Uri(path));
wcXML.OpenReadCompleted += new OpenReadCompletedEventHandler(wc);
}
void wc(object sender, OpenReadCompletedEventArgs e)
{
var isolatedfile = IsolatedStorageFile.GetUserStoreForApplication();
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(iso_path, System.IO.FileMode.Create, isolatedfile))
{
byte[] buffer = new byte[e.Result.Length];
while (e.Result.Read(buffer, 0, buffer.Length) > 0)
{
stream.Write(buffer, 0, buffer.Length);
}
stream.Flush();
System.Threading.Thread.Sleep(0);
}
}
2. Reading XML file and binding image control to the dynamic path
here i am having an List which is showing an images, so i will a function to bind images to this list as per below.
public IList<Dictionary> GetListPerCategory_Icon(string category, string xmlFileName)
{
using (var storage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (storage.FileExists(xmlFileName))
{
using (Stream stream = storage.OpenFile(xmlFileName, FileMode.Open, FileAccess.Read))
{
try
{
loadedData = XDocument.Load(stream);
var data = from query in loadedData.Descendants("category")
where query.Element("name").Value == category
select new Glossy_Test.Dictionary
{
Image=GetImage((string)query.Element("iconpress")),//This is a function which will return Bitmap image
};
categoryList = data.ToList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString(), (((PhoneApplicationFrame)Application.Current.RootVisual).Content).ToString(), MessageBoxButton.OK);
return categoryList = null;
}
}
}
}
return categoryList;
}
and here the definition for above function
public BitmapImage GetImage(string imagePath)
{
var image = new BitmapImage();
imagePath = "/Glossy" + imagePath;
using (var storage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (storage.FileExists(imagePath))
{
using (Stream stream = storage.OpenFile(imagePath, FileMode.Open, FileAccess.Read))
{
image.SetSource(stream);
}
}
}
return image;
}
you could use WebClient to pull the xml from the server and then save it as an XDocument in your callback.

Categories