问题
I am new to the windows phone 7 application development. I am accessing the picture library by using the PhotoChooserTask class. After selecting one of the picture from picture library I want to add that image (.jpg file) from picture library to the images folder of my application. How to do this ? I am using the following code
public partial class MainPage : PhoneApplicationPage
{
PhotoChooserTask photoChooserTask;
// Constructor
public MainPage()
{
InitializeComponent();
photoChooserTask = new PhotoChooserTask();
photoChooserTask.Completed += new EventHandler<PhotoResult>(photoChooserTask_Completed);
}
private void button1_Click(object sender, RoutedEventArgs e)
{
photoChooserTask.Show();
}
void photoChooserTask_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
BitmapImage bmp = new BitmapImage();
bmp.SetSource(e.ChosenPhoto);
}
}
}
I want to add the the selected image dynamically to images folder of my application. how to do this? Can you please provide me any code or link through which I can resolve the above issue ?
回答1:
Here's an example of saving the selected picture to IsolatedStorage and then reading it out to display it on the page:
void photoChooserTask_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
var contents = new byte[1024];
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
using (var local = new IsolatedStorageFileStream("image.jpg", FileMode.Create, store))
{
int bytes;
while ((bytes = e.ChosenPhoto.Read(contents, 0, contents.Length)) > 0)
{
local.Write(contents, 0, bytes);
}
}
// Read the saved image back out
var fileStream = store.OpenFile("image.jpg", FileMode.Open, FileAccess.Read);
var imageAsBitmap = PictureDecoder.DecodeJpeg(fileStream);
// Display the read image in a control on the page called 'MyImage'
MyImage.Source = imageAsBitmap;
}
}
}
回答2:
You can refer to the RTM release notes on the revised Photo Chooser API or the doco a bit further down the page here.
How to: Create a Photo Extras Application for Windows Phone
回答3:
In fact, once you obtain the stream, you can convert it to byte and store locally. Here is what you should have in your Task_Completed event handler:
using (MemoryStream stream = new MemoryStream())
{
byte[] contents = new byte[1024];
int bytes;
while ((bytes = e.ChosenPhoto.Read(contents, 0, contents.Length)) > 0)
{
stream.Write(contents, 0, bytes);
}
using (var local = new IsolatedStorageFileStream("myImage.jpg", FileMode.Create, IsolatedStorageFile.GetUserStoreForApplication()))
{
local.Write(stream.GetBuffer(), 0, stream.GetBuffer().Length);
}
}
来源:https://stackoverflow.com/questions/4253438/how-to-copy-the-selected-image-from-picture-library-to-the-images-folder-dynamic