Selasa, 28 Januari 2014

Coding4Fun:SuperImage Bindind Listbox with more Captured Images without out-of-memory -Part 2

Introduction

In Previous Part1 article we can resolve memory issue with listbox images,but unfortunate there is an issue In Listpage.xaml ,Because listbox Ui loads little bit slow when there are more caprtured images.The reason is in MainPage i was storing whole caprured imagesbytes in isolated storage and readed it on Listpage.xaml,it is little bit more complex for loading UI when reading whole captrured  imagebytes.
So that in this part i am going to introduce best solution is,Direclty reference the isostore image path instead of storing and reading whole image bytes using Coding4Fun Toolkit: Introducing SuperImage .
Source File at :SuperImageBindingMemoryFree

Building the Sample

To use SuperImage we have to download Coding4Fun Toolkit and need to reference in your page like this

XAML

xmlns:coding4Fun="clr-namespace:Coding4Fun.Toolkit.Controls;assembly=Coding4Fun.Toolkit.Controls"
 Or you may directly installed it from nugget packages


Description
Actually in previous i tried to reference the image binding with isoStore image path like this way

XAML

<Image Source="isostore:/Shared/SaveImages/Image0.jpg" />
 But unfortunate,it won't work with direct isostore image paths

and after doing a small R&D,i had found an amazing control from coding4fun toolkit is SuperImage ,which can  supports both isostore (from Windows Phone) and ms-appx (from Windows Store) as urls for your ImageSource. 

so that we can direclty bind image paths from isostore using SuperImage like this,

XAML
<coding4Fun:SuperImage Source="isostore:/Shared/ShavedImages?Image0.jpg" Width="120" Stretch="Uniform"/>

 However we need to follow some few steps as below,


1)How to Save captured Images in Local Folder of windows phone

After capturing the image from camera/photo chooser ,we need to store local folder ,in my case"Shared/SavedImagesFiles" 

C#
Stream cameraimgstream; 
public const string StoragePath = "Shared/SavedImagesFiles"
 public static async Task SaveImageToLocalFolder(Stream imageStream, string filename, string folder = StoragePath) 
        { 
             
            var isf = IsolatedStorageFile.GetUserStoreForApplication(); 
            if (!isf.DirectoryExists(StoragePath)) 
            { 
                isf.CreateDirectory(StoragePath); 
            } 
            var file = (folder == null ? filename : String.Format("{0}/{1}", folder, filename)); 
            
            if (isf.FileExists(file)) isf.DeleteFile(file); 
 
            using (var stream = isf.OpenFile(file, FileMode.Create, FileAccess.ReadWrite)) 
            { 
                BitmapImage bitmap = new BitmapImage(); 
                bitmap.SetSource(imageStream); 
 
                WriteableBitmap wb = new WriteableBitmap(bitmap); 
                wb.SaveJpeg(stream, wb.PixelWidth, wb.PixelHeight, 085); 
                stream.Close(); 
                //var ms = new MemoryStream(ImageBytes, false); 
                //await ms.CopyToAsync(stream); 
            } 
        }

And to use above method ,we need to call like
C#
 if (cameraimgstream != null
            { 
 
                await SaveImageToLocalFolder(cameraimgstream, "Image" + count.ToString(), StoragePath); 
            }

2)Direclty Bind  Listbox with The IsoStore Images using SuperImage 


Afetr saving images to isolatedstoarge local folder,we need to reference them,and so as part in our viemodel we need to another class (SavedData.cs) member for storing isostore image
like ImagePath= string.Format("isostore:/{0}", file.ToString()) 
afetr that we need all imagepath to list
C#
 var file = (StoragePath == null ? "Image" + count.ToString() : String.Format("{0}/{1}", StoragePath, "Image" + count.ToString())); 
prkdata.ImagePath = file.ToString(); 
parkinglistobj.Add(new SavedData { ID = count + 1, Address = "Image" + count.ToString(),ImagePath= string.Format("isostore:/{0}", file.ToString())});
 Finally bind list 
<coding4Fun:SuperImage Source="{Binding ImagePath}" Width="120"
Stretch="Uniform"/>

C#
ParkListBox.ItemsSource = parkinglistobj.OrderByDescending(i => i.ID).ToList();

 3)ScreenShots



Note: screens are taken from the emulator

   

Have a nice day by 

Senin, 27 Januari 2014

Windows Phone 8 Listbox Images out of memory exception c# - Part1

Introduction

Images are the best attraction for every mobile app.But Users have high expectations when it comes to using applications on their mobile devices. It is important to have good performance and quality in your applications and there are a number of things you can do to deliver great performance.So as s developer it is more quit difficult to overcome out of memory exception,however I’ll list a few that apply to memory, images, data binding and more.and i hope i will definately helpful for who are having same problem.
Source File at :WP8ImageFree

Building the Sample

We need ad namespaces " Microsoft.Phone.Tasks" for camera task and "System.IO.IsolatedStorage,System.Runtime.Serialization" for isolated storage ,and no need for any other external dll's
Description
However  I had taken for the requirements of "Saving Camera captured Images to Isolated Storage" ,"Read the camera captured images from the isolated storage to listbox" and also "How to resize captured images in wp8 c#
Let's start few steps to meet above requirements

1)Saving Camera captured Images to Isolated Storage:

Before going to start this section, we must need to know about "isolated storage",so that in previously i had posted about this one at"http://bsubramanyamraju.blogspot.com/2014/01/how-to-store-listbox-items-into.html"
and now we are going to cature the image from camera like this way,
C#
private void CarImage_tap(object sender, System.Windows.Input.GestureEventArgs e) 
        { 
 
            CameraCaptureTask ccTask = new CameraCaptureTask(); 
            ccTask.Completed += ccTaskCompleted; 
            ccTask.Show(); 
        } 
 
        private void ccTaskCompleted(object sender, PhotoResult pr) 
        { 
            try 
            { 
                byte[] ImageBytes; 
 
                if (pr.ChosenPhoto != null
                { 
                    ImageBytes = new byte[(int)pr.ChosenPhoto.Length]; 
                    pr.ChosenPhoto.Read(ImageBytes, 0, ImageBytes.Length); 
                    pr.ChosenPhoto.Seek(0, System.IO.SeekOrigin.Begin); 
                    var bitmapImage = PictureDecoder.DecodeJpeg(pr.ChosenPhoto, 480856); 
                    if (bitmapImage.PixelHeight > bitmapImage.PixelWidth) 
                    { 
                        CarImage.MaxHeight = 450
                        CarImage.MaxWidth = 252
                    } 
                    else 
                    { 
                        CarImage.MaxHeight = 252
                        CarImage.MaxWidth = 450
                    } 
                    this.CarImage.Source = bitmapImage; 
                    prkdata.CarImageBytes = ImageBytes; 
 
                     
                } 
 
            } 
            catch 
            { 
            } 
         
        }
after capturing the image ,we need to store imagebytes in isolated storage like this way,

C#
SavedData prkdata = new SavedData(); 
        SavedDataList parkinglistobj = new SavedDataList(); 
        IsolatedStorageFile Settings = IsolatedStorageFile.GetUserStoreForApplication(); 
prkdata.CarImageBytes = ImageBytes; 
parkinglistobj.Add(new SavedData { ID = count + 1, Address = "Image" + count.ToString(), CarImageBytes = prkdata.CarImageBytes }); 
 
            if (Settings.FileExists("ParkignItemList")) 
            { 
                Settings.DeleteFile("ParkignItemList"); 
            } 
            using (IsolatedStorageFileStream fileStream = Settings.OpenFile("ParkignItemList", FileMode.Create)) 
            { 
                DataContractSerializer serializer = new DataContractSerializer(typeof(SavedDataList)); 
                serializer.WriteObject(fileStream, parkinglistobj); 
 
            }

2)Resizing Camera captured Images in windows phone 8 c#:
In above code i had resize captured image to max height 450 and width to 252,How ever to resize image the without loss image quality we need to adjust width and height with equal proprotions,here i had taken with help of paint applicaiton in windows 8 os to calculate apect pixel ratio's image to fixed height of 450. 
C#
var bitmapImage = PictureDecoder.DecodeJpeg(pr.ChosenPhoto, 480856); 
                    if (bitmapImage.PixelHeight > bitmapImage.PixelWidth) 
                    { 
                        CarImage.MaxHeight = 450
                        CarImage.MaxWidth = 252
                    } 
                    else 
                    { 
                        CarImage.MaxHeight = 252
                        CarImage.MaxWidth = 450
                    }
3)Reading Camera captured Images from isolatedstorage to listbox:
In this step we need to helper classes 
3.1)For storing capture image bytes i.e(SavedData.cs):

C#
public class SavedData 
    { 
        public int ID { getset; } 
        public String Address { getset; } 
        public byte[] CarImageBytes { getset; } 
    } 
    public class SavedDataList : List<SavedData> 
    { 
    }
3.2)IValueConverter class for converting imagebytes to bitmapimage:
C#

public class BytesToImageConverter : IValueConverter 
    { 
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
        { 
            if (value != null && value is byte[]) 
            { 
                byte[] bytes = value as byte[]; 
                MemoryStream stream = new MemoryStream(bytes); 
                BitmapImage image = new BitmapImage(); 
                image.DecodePixelType = DecodePixelType.Logical; 
                image.CreateOptions = BitmapCreateOptions.BackgroundCreation; 
                image.CreateOptions = BitmapCreateOptions.DelayCreation; 
                var bitmapImage = PictureDecoder.DecodeJpeg(stream, 480856); 
                if (bitmapImage.PixelHeight > bitmapImage.PixelWidth) 
                { 
                    image.DecodePixelWidth = 56
                    image.DecodePixelHeight = 100
                } 
                else 
                { 
                    image.DecodePixelWidth = 100
                    image.DecodePixelHeight = 56
                } 
                image.SetSource(stream); 
                return image; 
            } 
 
            return null
 
        } 
 
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
        { 
            throw new NotImplementedException(); 
        }

Notes:
1)in ivalueconverter class it is most important thing, i had mention is BitmapImage properties are"DecodePixelHeight,DecodePixelWidth,CreateOptions" to know more about this ones http://msdn.microsoft.com/en-us/library/windowsphone/develop/system.windows.media.imaging.bitmapimage(v=vs.105).aspx

And is is very important to set 
bitimage.DecodePixelWidth = 56; 
bitimage.DecodePixelHeight = 100;

For additional performance benefit, if you are planning to only have the image displayed as a 100 x 100 frame across all devices, you can encode your images to that size. In general, the resolution of the image should be no greater than the frame it will be displayed in.  If your image is larger, resize it, especially if the frame is going to be drawn multiple times.

C#
BitmapImage image = new BitmapImage(); 
                image.DecodePixelType = DecodePixelType.Logical; 
                image.CreateOptions = BitmapCreateOptions.BackgroundCreation; 
                image.CreateOptions = BitmapCreateOptions.DelayCreation; 
               image.DecodePixelWidth = 56
                    image.DecodePixelHeight = 100;

 2)bitimage.DecodePixelWidth and bitimage.DecodePixelHeight are only supported in windowsphone 8 os


3.2)Binding listbox with bitmapimage from captured imagebytes :

We can bind listbox items with imagebytes in xaml using above ivalueconverter class i.e "BytesToImageConverter.cs" .so that we need to reference above ivalueconverter class
like this way 
XAML
xmlns:n="clr-namespace:ImageFreewp8" 
<phone:PhoneApplicationPage.Resources
        <n:BytesToImageConverter x:Name="ByteToImage" /> 
    </phone:PhoneApplicationPage.Resources>

 and bind listbox image with ivaluecoverter like this way,

XAML
 <Image Source="{Binding CarImageBytes, Converter={StaticResource ByteToImage}}"  Stretch="None" VerticalAlignment="Center"   HorizontalAlignment="Center"  />

finally assign the list of captured isolated storage images to listbox like this way,

C#
 if (Settings.FileExists("ParkignItemList")) 
                { 
                    using (IsolatedStorageFileStream fileStream = Settings.OpenFile("ParkignItemList", FileMode.Open)) 
                    { 
                        DataContractSerializer serializer = new DataContractSerializer(typeof(SavedDataList)); 
                        parkinglistobj = (SavedDataList)serializer.ReadObject(fileStream); 
 
                    } 
                } 
                
               
                ParkListBox.ItemsSource = parkinglistobj.OrderByDescending(i => i.ID).ToList();
 4)ScreenShots :

Note: screens are taken from the emulator
   

Senin, 06 Januari 2014

How to store ListBox items into IsolatedStorage in WindowsPhone 8 c#

Introduction

In every mobile app,there is requirement for storing data and accessing data. We need to store data in our Phones to persist data when the application is not running.However fortunatley Windows Phone 7 &windows phone 8 provides a secure way to store data into Isolated Store.Isolated Storage, as the name suggests is a special virtualized file system that every application can access for standard IO operations yet the file is unavailable to any other application. Hence the files stored by one application is isolated from another. 

Note For beginners:
1)Isolated storage are best and simple for storing data,for more info you may visit 
http://www.geekchamp.com/tips/all-about-wp7-isolated-storage--intro-to-isolated-storage
2)We can also store and access data using sqlite,i will be introduce it laterely or next article.

Source File at :IsolatedStorageList

Building the Sample

1)You will have to add a reference to System.Xml.Serialization 
2)Needed <tt>System.IO.IsolatedStorage</tt> namespace to access files and/or application settings.
Description

1)However in this sample i had taken "MyData" class as well as "MyDataList"  


C#
 public class MyData 
    { 
        public string Name { getset; } 
        public string Location { getset; } 
    } 
    public class MyDataList : List<MyData>//for storing mydata class items with type of list 
    { 
 
 
    }

 2) Add item to "MyDataList" like this way

C#
MyDataList listobj = new MyDataList(); 
listobj.Add(new MyData { Name = "subbu", Location = "hyd" }); 
listobj.Add(new MyData { Name = "Venky", Location = "Kadapa" }); 
listobj.Add(new MyData { Name = "raju", Location = "Kuwait" }); 
listobj.Add(new MyData { Name = "balu", Location = "US" }); 
listobj.Add(new MyData { Name = "gopi", Location = "London" }); 
listobj.Add(new MyData { Name = "rupesh", Location = "USA" }); 
listobj.Add(new MyData { Name = "ram", Location = "bang" });

3)Write list or listbox items into IsolatedStorage

C#
IsolatedStorageFile Settings1 = IsolatedStorageFile.GetUserStoreForApplication(); 
if (Settings1.FileExists("MyStoreItems")) 
 { 
    Settings1.DeleteFile("MyStoreItems"); 
 } 
 using (IsolatedStorageFileStream fileStream = Settings1.OpenFile("MyStoreItems", FileMode.Create)) 
 { 
    DataContractSerializer serializer = new DataContractSerializer(typeof(MyDataList)); 
                    serializer.WriteObject(fileStream, listobj); 
 
  }

 4)Read  
list or listbox items from IsolatedStorage

C#
 if (Settings1.FileExists("MyStoreItems")) 
            { 
                using (IsolatedStorageFileStream fileStream = Settings1.OpenFile("MyStoreItems", FileMode.Open)) 
                { 
                    DataContractSerializer serializer = new DataContractSerializer(typeof(MyDataList)); 
                    listobj = (MyDataList)serializer.ReadObject(fileStream); 
                     
                } 
            }

  5)Remove list or listbox items from IsolatedStorage 

C#
if (Settings1.FileExists("MyStoreItems")) 
            { 
                Settings1.DeleteFile("MyStoreItems"); 
                MessageBox.Show("Items removed successfully."); 
            }

6)Binding listbox items from IsolatedStorage list data

C#
if (Settings1.FileExists("MyStoreItems")) 
            { 
                using (IsolatedStorageFileStream fileStream = Settings1.OpenFile("MyStoreItems", FileMode.Open)) 
                { 
                    DataContractSerializer serializer = new DataContractSerializer(typeof(MyDataList)); 
                    listobj = (MyDataList)serializer.ReadObject(fileStream); 
                     
                } 
            } 
Isolistbox.ItemsSource = listobj;//binding isolated storage list data

7)Write selected listbox class item into IsolatedStorage 
C#
 private void Isolistbox_SelectionChanged_1(object sender, SelectionChangedEventArgs e) 
        { 
            MyData selecteddata = (MyData)Isolistbox.SelectedItem;//get listbox item data 
            //Write selected class item value into  isolated storage  
            if (selecteddata != null
            { 
                if (Settings1.FileExists("MySelectedStoreItem")) 
                { 
                    Settings1.DeleteFile("MySelectedStoreItem"); 
                } 
                using (IsolatedStorageFileStream fileStream = Settings1.OpenFile("MySelectedStoreItem", FileMode.Create)) 
                { 
                    DataContractSerializer serializer = new DataContractSerializer(typeof(MyData)); 
                    serializer.WriteObject(fileStream, selecteddata); 
 
                } 
                MessageBox.Show("Your selected item Name:" + selecteddata.Name.ToString()+" " + "is stored in isolated storage"); 
            } 
        }
8)ScreenShots 



  





Windows Phone tutorials for beginners key points



This section is included for only windows phone beginners.However this article can covers following questions.Off course these key words are more helpful for getting more best results about this topic in search engines like google/bing/yahoo.. 




1. IsolatedStorage in windowsphone 8 c#





2. Storing ListBox items in isolatedstorage in windowsphone






3. Removing items from isolatedstorage in windowsphone






4. Reading listbox items from isolated storage





5. Binding listbox items from isolated storag




6. Storing listbox selcted item in isolatedstorage






7.How to get listbox selected item from isolated storage






Have a nice day by