Hi I am developing a lockscreen app where I am using listbox of images.After selecting a image when i am clicking a button to set lockscreen,It should updated.But it bot updating .Here is my code
private async void ApplicationBarIconButton_Click(object sender, EventArgs e)
{
MediaLibrary mediaLibrary = new MediaLibrary();
//ImageSource im = image1.Source;
BitmapImage bitmap = new BitmapImage();
bitmap.SetSource(mediaLibrary.Pictures[imageList.SelectedIndex].GetImage());
String tempJPEG = "MyWallpaper1.jpg";
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);
WriteableBitmap wb = new WriteableBitmap(bitmap);
Extensions.SaveJpeg(wb, fileStream, wb.PixelWidth, wb.PixelHeight, 0, 90);
fileStream.Close();
}
LockScreenChange(tempJPEG);
}
private async void LockScreenChange(string filePathOfTheImage)
{
if (!LockScreenManager.IsProvidedByCurrentApplication)
{
await LockScreenManager.RequestAccessAsync();
}
if (LockScreenManager.IsProvidedByCurrentApplication)
{
var schema = "ms-appdata:///Local/";
var uri = new Uri(schema + filePathOfTheImage, UriKind.Absolute);
LockScreen.SetImageUri(uri);
var currentImage = LockScreen.GetImageUri();
MessageBox.Show("Success", "LockScreen changed", MessageBoxButton.OK);
}
else
{
MessageBox.Show("Background cant be changed. Please check your permissions to this application.");
}
}
Actually when first time the app is launched and when I am clicking set button,the current selected image is set as lockscreen,after that when i am selecting another image,it is showing lockscreen changed ,success.No error and no exception.I dont know where is the problem.
Please help........
It got solved by changing temporary file name to original file name i.e. string tempJpeg
Related
I have a custom UserControl with an Image control in it. I'm trying to fetch an image from web[network server] and show it in my control, refreshing the source using a dispatcher timer. Here is the code:
void StartSourceRefresh()
{
if (timeinterval < 1) timeinterval = 1;
tmrRefresh.Tick += new EventHandler(dispatcherTimer_Tick);
tmrRefresh.Interval = new TimeSpan(0, 0, timeinterval); //in hour-minute-second
tmrRefresh.Start();
}
public void ChangeImageSource(string newSource)
{
//newSource = "http://192.168.1.3/abc/imagetobeshown.png"
WebImg.Source = null;
if (newSource.Trim() == "")
WebImg.Source = new BitmapImage(new Uri(#imagePlaceholder, UriKind.Absolute));
else
{
BitmapImage image = new BitmapImage();
image.BeginInit();
image.UriSource = new Uri(#newSource, UriKind.Absolute);
image.EndInit();
WebImg.Source = image;
}
}
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
ChangeImageSource(txtImgSrc.Text.Trim());
}
the problem is the image wont change. Its showing the same one which was fetched at the first time. Timer is running fine. But the image just won't change. What am i doing wrong here?
Edit: Network Source gets refreshed after certain interval, so have to fetch the same source
You are apparently reloading from the same image URL, which is cached by default.
Disable caching by setting BitmapCreateOptions.IgnoreImageCache:
var image = new BitmapImage();
image.BeginInit();
image.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
image.UriSource = new Uri(newSource);
image.EndInit();
I need to copy an image from my windows universal app, I was able to pick an image from my gallery but i don't how to copy it in another folder.
Although I was able to display the image in my UWP interface, so I think that I succeed to get it as a stream.
Any help would be appreciated, I'm lost here ... here is the code I used:
public MainPage()
{
this.InitializeComponent();
// Scenario4WriteableBitmap = new WriteableBitmap((int)Scenario4ImageContainer.Width, (int)Scenario4ImageContainer.Height);
Scenario2DecodePixelHeight.Text = "100";
Scenario2DecodePixelWidth.Text = "100";
}
private async void buttonUpload_Click(object sender, RoutedEventArgs e)
{
int decodePixelHeight=150;
int decodePixelWidth=150;
// Try to parse an integer from the given text. If invalid, default to 100px
if (!int.TryParse(Scenario2DecodePixelHeight.Text, out decodePixelHeight))
{
Scenario2DecodePixelHeight.Text = "100";
decodePixelHeight = 100;
}
// Try to parse an integer from the given text. If invalid, default to 100px
if (!int.TryParse(Scenario2DecodePixelWidth.Text, out decodePixelWidth))
{
Scenario2DecodePixelWidth.Text = "100";
decodePixelWidth = 100;
}
FileOpenPicker open = new FileOpenPicker();
open.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
open.ViewMode = PickerViewMode.Thumbnail;
// Filter to include a sample subset of file types
open.FileTypeFilter.Clear();
open.FileTypeFilter.Add(".bmp");
open.FileTypeFilter.Add(".png");
open.FileTypeFilter.Add(".jpeg");
open.FileTypeFilter.Add(".jpg");
// Open a stream for the selected file
StorageFile file = await open.PickSingleFileAsync();
// Ensure a file was selected
if (file != null)
{
// Ensure the stream is disposed once the image is loaded
using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.Read))
{
// Set the image source to the selected bitmap
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.DecodePixelHeight = decodePixelHeight;
bitmapImage.DecodePixelWidth = decodePixelWidth;
await bitmapImage.SetSourceAsync(fileStream);
Scenario2Image.Source = bitmapImage;
}
}
}
private async void submit_Click(object sender, RoutedEventArgs e)
{
String url = "http://localhost/mydatabase/add.php";
var values = new List<KeyValuePair<String, String>>
{
new KeyValuePair<string, string>("UserName",UserName.Text),
new KeyValuePair<string, string>("UserImage",UserImage.Text),
};
HttpClient client = new HttpClient();
HttpResponseMessage response = new HttpResponseMessage();
try
{
response = await client.PostAsync(url, new FormUrlEncodedContent(values));
/*client.DefaultRequestHeaders.Add("content_type", "binary/octet_stream");
responseImage = client.PostAsync("", FileChooser.FileName);*/
if (response.IsSuccessStatusCode)
{
Debug.WriteLine(response.StatusCode.ToString());
var dialog = new MessageDialog("added succesfully ");
await dialog.ShowAsync();
}
else
{
// problems handling here
string msg = response.IsSuccessStatusCode.ToString();
throw new Exception(msg);
}
}
catch (Exception exc)
{
// .. and understanding the error here
Debug.WriteLine(exc.ToString());
}
}
`
you can use CopyAsync of StorageFile to copy the file you get from FileOpenPicker to a specific folder.
I am building my first app in windows phone 7 application. I have an image which comes from the web and when the image is clicked i am navigated to another page.
My xaml code is:
<Button Click="Image_Click" Name="image1" Margin="-33,-16,-26,-13">
<Button.Background>
<ImageBrush Stretch="Fill" ImageSource = "http://political-leader.vzons.com/ArvindKejriwal/images/icons/landing.png"/>
</Button.Background>
</Button>
My .cs code is
private void Image_Click(object sender, RoutedEventArgs e)
{
NavigationService.Navigate(new Uri("/AAP.xaml", UriKind.Relative));
}
Now the issue is that i want to store the image so that it can be even viewed while offline. Can anyone help me what modification should i do to for this purpose.
This is a working example on how to do that. The logic is as follow :
In the page's constructor, call LoadImage method.
The method will set imageBrush's ImageSource to image in Isolated storage if available.
If the image not exists in Isolated storage, LoadImage method will download the image from web and call an event handler when download completed.
The event handler (DownloadCompleted method) will then, save the image to Isolated Storage and call LoadImage again. Refer to point 2 for what happen next.
You may want to improve it later to implement MVVM and using DataBinding.
References: nickharris.net, geekchamp.com
string imageName = "myImage.jpg";
string imageUrl = "http://political-leader.vzons.com/ArvindKejriwal/images/icons/landing.png";
public MainPage()
{
InitializeComponent();
LoadImage();
}
private void LoadImage()
{
BitmapImage bi = new BitmapImage();
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
//load image from Isolated Storage if it already exist
if (myIsolatedStorage.FileExists(imageName))
{
using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(imageName, FileMode.Open, FileAccess.Read))
{
bi.SetSource(fileStream);
imageBrushName.ImageSource = bi;
}
}
//else download image to Isolated Storage
else
{
WebClient wc = new WebClient();
wc.OpenReadCompleted += new OpenReadCompletedEventHandler(DownloadCompleted);
wc.OpenReadAsync(new Uri(imageUrl, UriKind.Absolute), wc);
}
}
}
private void DownloadCompleted(object sender, OpenReadCompletedEventArgs e)
{
if (e.Error == null && !e.Cancelled)
{
try
{
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
IsolatedStorageFileStream fileStream = myIsolatedStorage.CreateFile(imageName);
BitmapImage bitmap = new BitmapImage();
bitmap.SetSource(e.Result);
WriteableBitmap wb = new WriteableBitmap(bitmap);
// Encode WriteableBitmap object to a JPEG stream.
Extensions.SaveJpeg(wb, fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);
fileStream.Close();
}
//after image saved to Iso storage, call LoadImage method again
//so the method will set imageBrush's ImageSource to image in Iso storage
LoadImage();
}
catch (Exception ex)
{
//Exception handle appropriately for your app
}
}
else
{
//Either cancelled or error handle appropriately for your app
}
}
I have an app that downloads an image to the phone and depending on the image category it will assign it to a news feed. I am using this function:
private static void DownloadImage(string furl, string ids)
{
// Connect Again to the API
WebClient client = new WebClient();
client.Headers["NewsID"] = ids;
string url = "www.xxx.com/image/xyz";
client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
client.OpenReadAsync(new Uri(url));
}
private static void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (e.Error == null && !e.Cancelled)
{
Stream reply = null;
StreamReader s = null;
// i am not able to read the sender who is a webclient to retrieve the information it is always skipping it
WebClient wcd = sender as WebClient;
reply = (Stream)e.Result;
s = new StreamReader(reply);
//Console.WriteLine(s.ReadToEnd());
s.Close();
reply.Close();
if (!myIsolatedStorage.DirectoryExists("ImageCache"))
{
myIsolatedStorage.CreateDirectory("ImageCache");
}
//try
//{//((MS.Internal.InternalMemoryStream)(e.Result)).FinalUri.Segments[2]
var graphImage = e.Result;
Random rand = new Random();
string fileName = string.Format("ImageCache/{0}.jpg", rand.Next());
IsolatedStorageFileStream fileStream = myIsolatedStorage.CreateFile(fileName);
BitmapImage image = new BitmapImage();
image.SetSource(e.Result);
WriteableBitmap wb = new WriteableBitmap(image);
// Encode WriteableBitmap object to a JPEG stream.
Extensions.SaveJpeg(wb, fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);
fileStream.Close();
//}
//catch (IsolatedStorageException ex)
//{
//IsolatedStorageException
//Exception handle appropriately for your app
//}
}
}
}
In the OpenReadComplete function which I'm using to download the image, I want to get the newsID from the header, and then assign it to the image before saving it into the database. I can't seem to access the header. Is this possible?
I think you can read it with sender.
WebClient c = (WebClient)sender;
string id = c.Headers["NewsID"];
How do I solve the exception, Operation not permitted on IsolatedFileStream?
After debugging, I realised that a certain line wasn't read and it was skipped to the catch part. I am reading images from the photo samples in windows phone 7 as well as uploading them into skydrive. Can anybody guide me on how to solve this problem asap?
Thanks.
public BitmapImage fileName { get; set; }
private void GetImages()
{
MediaLibrary mediaLibrary = new MediaLibrary();
var pictures = mediaLibrary.Pictures;
foreach (var picture in pictures)
{
BitmapImage image = new BitmapImage();
image.SetSource(picture.GetImage());
MediaImage mediaImage = new MediaImage();
mediaImage.fileName = image;
UploadFile(mediaImage, picture.Name);
}
}
public void UploadFile(MediaImage image, string filepath)
{
if (skyDriveFolderID != string.Empty)
{
this.client.UploadCompleted += new EventHandler<LiveOperationCompletedEventArgs>(ISFile_UploadCompleted);
infoTextBlock.Text = "Uploading backup...";
dateTextBlock.Text = "";
try
{
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
// error occurs HERE
IsolatedStorageFileStream readStream = myIsolatedStorage.OpenFile(filepath, FileMode.Open, FileAccess.Read);
readStream.Close();
this.client.UploadAsync(skyDriveFolderID, filepath, true, readStream, null)
}
}
Are you sure error occurs there? I can se you are closing the stream before reading it. So it may be that you got the line of error wrong.
Also, are you absolutely sure, that file with that exact name exists in Isolated Storage?