Need to bind ISO Stores file in a ListBox - c#

I am trying to store some soundclips which are tagged with Images chosen from ISO Storage through a PhotoChooserTask.
I can successfully display the image in a standalone Image box but when I am setting the Imagebox source inside a listbox It does not shows the image.
Currently what I am doing is something like this:
public ImageSource Image
{
get {
try
{
BitmapImage image;
if(Category == 11)
{
image = new BitmapImage(new Uri(this.ImageLocation));
}
return image;
}
catch (Exception)
{
return null;
}
}
I don't understand what is missing

BitmapImage can't load image from Isolated Storage. You need to read file image manually
BitmapImage bi = new BitmapImage();
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(this.ImageLocation, FileMode.Open, FileAccess.Read))
{
bi.SetSource(fileStream);
}
}
return bi;
Also, if this won't work, check CreateOptions and set it to None

Related

How to display image from a video stream using image control

I'm c# begginer.I used wpf image control to show image from my camera. It's work normally in winform pictureBox but not in WPF image control. It's all blank! And I'm sure the data stream exist.
The icImagingControl1 is the control of my camera SDK.
It's can return image data in many forms. Like Intptr,Byte,Bitmap.
I want load data in image control from memory.
And the function would be triggered everytime the camera snap.
Here is my code.
private void icImagingControl1_ImageAvailable(object sender, XXX.Imaging.ICImagingControl.ImageAvailableEventArgs e)
{
XXX.Imaging.ImageBuffer CurrentBuffer = null;
CurrentBuffer = icImagingControl1.ImageBuffers[e.bufferIndex];
try
{
using (MemoryStream memory = new MemoryStream())
{
CurrentBuffer.Bitmap.Save(memory, ImageFormat.Bmp);
memory.Position = 0;
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.StreamSource = memory;
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.EndInit();
image1.Source = bitmapImage;
}
}
catch (Exception ex)
{
System.Diagnostics.Trace.WriteLine(ex.Message);
}
}
Hope anyone could help me.

WPF C# Image Source

I'm pretty new to displaying images in WPF forms, and i'm having trouble when it comes to converting and assigning an Image source for my GUI.
System.Drawing.Image testImg = ImageServer.DownloadCharacterImage(charID, ImageServer.ImageSize.Size128px);
byte[] barr = imgToByteArray(testImg);
CharImage.Source = ByteToImage(barr);
public byte[] imgToByteArray(System.Drawing.Image testImg)
{
using (MemoryStream ms = new MemoryStream())
{
testImg.Save(ms,System.Drawing.Imaging.ImageFormat.Jpeg);
return ms.ToArray();
}
}
public System.Drawing.Image ByteToImage(byte[] barr)
{
MemoryStream ms = new MemoryStream(barr);
System.Drawing.Image returnImage = System.Drawing.Image.FromStream(ms);
return returnImage;
}
So i take in an image (JPEG) from the EVE Online C# API Library and then try to convert it to a byte array and back to a proper image. However i always get this error: "Cannot Implicitly convert type 'System.Drawing.Image' to 'System.Windows.Media.ImageSource'" I'm completely dumbfounded on how to solve this.
One possible solution is to save the image files (for example, .jpg) as WPF embedded resource and then use the following code snippet to get BitmapImage:
Listing 1. Get BitmapImage from EmbeddedResource
private string GetAssemblyName()
{
try { return Assembly.GetExecutingAssembly().FullName.Split(',')[0]; }
catch { throw; }
}
private BitmapImage GetEmbeddedBitmapImage(string pathImageFileEmbedded)
{
try
{
// compose full path to embedded resource file
string _fullPath = String.Concat(String.Concat(GetAssemblyName(), "."), pathImageFileEmbedded);
BitmapImage _bmpImage = new BitmapImage();
_bmpImage.BeginInit();
_bmpImage.StreamSource = Assembly.GetExecutingAssembly().GetManifestResourceStream(_fullPath);
_bmpImage.EndInit();
return _bmpImage;
}
catch { throw; }
finally { }
}
Correspondingly, set the Source property of the WPF Image control (for example, Image1) to that BitmapImage returned by function:
Image1.Source = GetEmbeddedBitmapImage(_strEmbeddedPath);
Note: you should reference the following:
using System.Windows.Media.Imaging;
using System.Reflection;
Another possible solution is to get the BitmapImage from image file using Uri object as shown in the following code snippet (Listing 2):
Listing 2. Get BitmapImage from File (use Uri)
private BitmapImage GetBitmapImageFromFile(string ImagePath)
{
Uri BitmapUri;
StreamResourceInfo BitmapStreamSourceInfo;
try
{
// Convert stream to Image.
BitmapImage bi = new BitmapImage();
BitmapUri = new Uri(ImagePath, UriKind.Relative);
BitmapStreamSourceInfo = Application.GetResourceStream(BitmapUri);
bi.BeginInit();
bi.StreamSource = BitmapStreamSourceInfo.Stream;
bi.EndInit();
return bi;
}
catch { throw; }
}
Hope this may help.
System.Drawing.Image is WinForms, not WPF. Your ByteToImage method should return BitmapSource instead.
The probably easiest way to create a BitmapSource from a byte array is BitmapFrame.Create:
public BitmapSource ByteArrayToImage(byte[] buffer)
{
using (var stream = new MemoryStream(buffer))
{
return BitmapFrame.Create(stream,
BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
}
}
You would assign the return value of the above method to the Source property of an Image control:
image.Source = ByteArrayToImage(barr);

How can I decode a byte array using a JpegBitmapDecoder

I cannot decode images back from their encoded form as a (Jpeg) byte array retrieved from my database to be used as image sources for my WPF application.
The code I am using to encode them as a Jpeg byte array is as follows:
public byte[] bytesFromBitmap(BitmapImage bit)
{
byte[] data;
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bit));
using (MemoryStream ms = new MemoryStream())
{
encoder.Save(ms);
data = ms.ToArray();
}
return data;
}
This is taking my Image taken directly from a webpage and assigned to an Image control like so:
var img = new BitmapImage(new Uri(entity.Image.ImageSrc)); //the entity has been saved in my DB, having been parsed from html
pbImage.Source = img;
This works just fine, I encode the BitmapImage and it saves just fine. But when I retrieve it from the DB and try to display it in another window, I cannot get it to work after trying every example I can see online - all either render nothing, or a black box or a visual mess not at all similar to the image I encoded.
Neither of the following have worked for me:
public BitmapSource GetBMImage(byte[] data)
{
using (var ms = new MemoryStream(data))
{
JpegBitmapDecoder decoder = new JpegBitmapDecoder(ms, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
BitmapSource frame = decoder.Frames[0];
return frame;
}
}
public static BitmapImage ImageFromBytes(byte[] imageData)
{
if (imageData == null)
{
return null;
}
else
{
var image = new BitmapImage();
using (var mem = new MemoryStream())
{
mem.Position = 0;
image.BeginInit();
image.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
image.CacheOption = BitmapCacheOption.OnLoad;
image.UriSource = null;
image.StreamSource = mem;
image.EndInit();
}
image.Freeze();
return image;
}
} //this throws a 'No imaging component suitable to complete this operation was found' exception
Among other uses of memory streams and decoders I just can't get this to work - can anyone help?

how to set picturebox image location from zip without extrat?

I want to set picture box from zip file without extract zip.
my code:
ZipFile zip = new ZipFile("data.zip");
using (Stream s = zip["p3.png"].OpenReader())
{
picturebox.ImageLocation = s.ToString();
}
Picture Box Show error image.
I should use Bitmap. Correct Code:
ZipFile zip = new ZipFile("data.zip");
using (Stream s = zip["p3.png"].OpenReader())
{
Bitmap bitmap= new Bitmap(s);
PictureBox picturebox.Image = bitmap;
}

how to store an image received from the web and display it in the windows phone 7 application

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

Categories

Resources