How to save image in class object? - visual-studio-2010

Can anyone help me to solve my prob?
Declare variable as
public class SaveMypet
{
public ImageSource PetImage { get; set; }
}
On button click my code is
SaveMypet savepet = new SaveMypet();
savepet.PetImage = pet_image.Source;
Is it right way to store image to a class object...??

If by save image to a class you mean assigning it to a container, then sure. Be aware, though, that this does not save the image itself anywhere else in the device storage. So the moment this class, or the original source, is destroyed, so will be your image.
Besides, ImageSource does not carry the image binary data, but rather a reference to it.

Related

Xamarin Android: Dynamic update UI based on Viewmodel

In my android project, the webview url is dynamic. I am using mvvmcros binding on view side but its not being dynamic. If the url content on view model is changing its not being updated on view. Can anyone help me out?
View
public string WebContentUrll { get; set; }
protected override void OnCreate(Android.OS.Bundle bundle)
{
var bindingSet = this.CreateBindingSet<view, ViewModel>();
bindingSet.Bind(this).For(v => v.WebContentUrll).To(vm => vm.WebContentUrl).TwoWay();
}
ViewModel
private string webContentUrl;
public string WebContentUrl
{
get
{
return webContentUrl;
}
set
{
webContentUrl = value;
RaisePropertyChanged(() => webContentUrl);
}
}
public void Init()
{
webContentUrl = "https://.."'
}
The value of web content url in the view model changes after the page is loaded but the android view is not able to get the new updated url.
Can anyone please advise. Thank you.
Update
The web view is opened on a button click and the url is updated after the page loads and before the button is clicked
From you description in the opening post. In your Activity you have defined a property WebContentUrll. You want to bind this and update something when it is changed.
The definition of WebContentUrll is:
public string WebContentUrll { get; set; }
This is not wrong and you should see the value reflected in WebContentUrll when it changes from the ViewModel through your binding. However, there is no code updating any visual states, views or anything based on that property.
If you have a WebView you want to change content for, you could modify your property to something like:
private string _webContentUrll;
public string WebContentUrll
{
get => _webContentUrll;
set
{
_webContentUrll = value;
_webView.LoadUrl(_webContentUrll);
}
}
Given that _webView is your instance of a WebView.

Cannot create BitmapImage from a chosen photo from phone

I'm trying to implement a Windows Phone 8 App that works with image handling, trying it to port it from a Windows 8 App. But I got stuck quite quickly, at the beginning.
What I want to achieve is to select some pictures from the phone and show them in my app, in a similar way they look in an album. For this, I've tried some MVVM technique, also. But I'm given an error when I'm trying to create a BitmapImage from the file Stream saying I'm out of range...
Here's my model :
public class SelectedPhoto : IDisposable
{
public Stream Data { get; set; }
public string Name { get; set; }
public BitmapImage Image { get; set; }
public SelectedPhoto(string name, Stream data)
{
Name = name;
Data = new MemoryStream();
data.CopyTo(Data);
Image = new BitmapImage();
Image.SetSource(Data); //Here's the Argument Exception.
}
public void Dispose()
{
Data.Dispose();
}
}
So I'm given the exception quite in the constructor... and I use this in code in a PhotoChooserTask like this :
private void PhotoChooserTaskCompleted(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
PhotosViewModel.AddPhoto(new SelectedPhoto(e.OriginalFileName, e.ChosenPhoto));
}
}
The Argument Exception says : Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection. But I'm not manipulating the Stream in any way, I just need it as it is to create the BitmapImage from it, as I've looked after some examples.
How can I get the BitmapImage of a selected image file from phone in this case? Or much better, how can I get it directly as a WriteableBitmap? Because later on, I'm planning on doing some pixel manipulation.
Any type of approach is welcome, thank you.
To fix your code, call the Seek method to go back to the beginning of your stream:
public SelectedPhoto(string name, Stream data)
{
Name = name;
Data = new MemoryStream();
data.CopyTo(Data);
Data.Seek(0, SeekOrigin.Begin);
Image = new BitmapImage();
Image.SetSource(Data); //Here's the Argument Exception.
}
That said, why are you duplicating the stream? You could directly use data.

Retrieving multiple images from isolated storage in wp7

I am trying to retrieve multiple images from isolated storage using listbox but i am not sure why it just only retrieve the lastest image from isolated storage.Therefore hope anyone could help me make amends to my code or could provide me with sample code that works which is about the same as mine.Thanks.
My code :
private void LoadFromLocalStorage(string imageFolder, string imageFileName )
{
var isoFile = IsolatedStorageFile.GetUserStoreForApplication();
if (!isoFile.DirectoryExists(imageFolder))
{
isoFile.CreateDirectory(imageFolder);
}
string filePath = Path.Combine(imageFolder, imageFileName);
using (var imageStream = isoFile.OpenFile(filePath, FileMode.Open, FileAccess.Read))
{
var imageSource = PictureDecoder.DecodeJpeg(imageStream);
BitmapImage bi = new BitmapImage();
ListBoxItem item = new ListBoxItem();
bi.SetSource(imageStream);
item.Content = new Image()
{
Source = bi, MaxHeight = 100, MaxWidth = 100 };
listBox1.Items.Add(item);
}
It would be helpful if you tell what results are you getting.
Do you see only 1 element?
Do you see multiple elements and they are the same?
Do you see multiple elements and only 1 shows a picture and other are empty?
Anyway this is not a proper way to treat listbox. But first things first.
This line doesn't do anything useful:
var imageSource = PictureDecoder.DecodeJpeg(imageStream);
This code should work (it seems), but there may be an error outside the code. How many times this function is called and what parameters are passed - that is what actually matters.
But I would change the code to use Data Binding and proper ItemsSource.
Create class for items
public class MyImage
{
public string FilePath {get; set;}
public ImageSource LoadedSource {get; set;}
}
Create an ObservableCollection<MyImage>() and fill it with your data.
Bind it to ListBox by setting ItemsSource
Design a proper ItemTemplate with Image and Binding:
<Image Source={Binding LoadedSource}/>
This setup will help you debug the issues easily and localize the problem. It is likely that you are calling your original function incorrectly.

Can I associate an image with a class and load this image without creating an instance of the class?

Long time lurker, first time poster here.
My question is:
Using C# 2.0, is there a way to associate am image with a class/type such that I don't have to create an instance of the class just to get the image object from that class?
What I am trying to do is scan all the .dlls in my application and construct a list of classes and corresponding attributes. I have this working great, and now I want to somehow associate an image with each class so that I can display a list of classes and have a unique image for each.
I've tried searching SO and the internet for an answer, but can't find anything definite. Any help would be greatly appreciated.
Thanks,
Kyle
You could create an ImageAttribute.
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
class ImageAttribute : Attribute
{
private string ImagePath { get; set; }
public ImageAttribute(string imagePath)
{
ImagePath = imagePath;
}
public Bitmap Image
{
get { return new Bitmap(ImagePath); }
}
}
Or database id, just some way to identify an image.
Figured out how to do it using ideas here and there.
Mark the image as an EmbeddedResource.
Create an attribute for specifying the image name.
Once the image name attribute is read, use the following to locate the image resource inside the assembly where the class was declared:
string[] all = info.Type.Assembly.GetManifestResourceNames();
foreach (string resourceStr in all)
{
if (!String.IsNullOrEmpty(resourceStr) && resourceStr.EndsWith(String.Format(".{0}", iconName), true, CultureInfo.CurrentCulture))
{
Stream file = info.Type.Assembly.GetManifestResourceStream(resourceStr);
if (file != null)
{
info.Icon = Image.FromStream(file);
}
}
}

Observer pattern on GWT

Hey there! I'm relatively new to both GWT and java programming (or OOP for that matter), so apologies for the beginner questions/mistakes in advance. I've been trying to create some kind of observer pattern, but the development mode console keeps dropping error messages and sadly, they're far from helpful.
So here's what I'm trying to achieve:
- I've got the model that consists of the class Country, and stores a value called Influence.
- The view is the class called CountryDisplay. It's a GWT widget that should always display the current influence of a given country.
public class Country {
private int influece;
private CountryDisplay display;
public Country() {
influence = 0;
}
public void setDisplay(CountryDisplay display) //...
public int getInfluence() //...
public void setInfluence(int value) {
influence = value;
display.update();
}
}
public class CountryDisplay {
private Country country;
public CountryDisplay (Country country) {
//GWT widget creating stuff
this.country = country;
}
public void update() {
//InfluenceCounter is a simple Label
InfluenceCounter.setText(Integer.toString(country.getInfluence()));
}
}
Then in the EntryPoint class I do something like this:
Country italy = new Country();
CountryDisplay italyDisplay = new CountryDisplay(italy);
italy.setDisplay(italyDisplay);
RootPanel.get("nameFieldContainer").add(italyDisplay);
italy.setInfluence(3);
The development console indicated that it had a problem with the line "display.update();" in class Country. My first guess was that the problem was that the display was not initiated, so I created an interface for it, and in the Country constructor I created an empty, new display, that would later be overwritten.
public Country() {
influence = 0;
display = new DisplayInterface() {
public void update() {}
}
}
But I had no luck this way either. I guess this kind of cross-referencing is not allowed? I mean that the view has the model as a variable and vice versa.
When calling a method on the view individually (like:
italy.setInfluence(3);
italyDisplay.displayTheCurrentValue();
) it works, so the problem is definitely in the observer logic.
If I understand correctly, your are trying to "bind" user interface elements (your view class CountryDisplay) to data (the model class Country). "Bind" in the sense that if you change the model data (for example, call italy.setInfluence(10)) then the view would automatically update itself to reflect the change. And if your view provided an editor, you want the "binding" also to work in the other direction.
There are several frameworks out there that achieve this, see for example the post Best data binding solution for GWT. I have used GWT Pectin and there is the GWT Editors framework (which I have not yet used myself as it is relatively new).
Looking at your code, I feel you might want to more clearly separate the model from the view: your model class (Country) should not know about the view class, that is, it should not store a reference to CountryDisplay.

Resources