How to add an existing item via code in wpf - c#

I am attempting to copy a selected image to a folder and then want to display it with an Image object. The copying works fine, but when I want to display it it seems like the program cannot find it. Displaying the image only works if I manually use "add existing Item". Is there a way to add it automatically?
Here is my code:
string name = "image1";
OpenFileDialog dialog = new OpenFileDialog();
Nullable<bool> dialogOK = dialog.ShowDialog();
if(dialogOK == true)
{
File.Copy(dialog.FileName, #"..\..\Images\" + name + ".png", true);
image.Source = new BitmapImage(new Uri(#"Images\" + name + ".png", UriKind.Relative));
}
("image" is defined in xaml)

It seems safer to use an absolute path for loading the BitmapImage:
var dialog = new OpenFileDialog();
if (dialog.ShowDialog() == true)
{
var targetFile = #"..\..\Images\" + name + ".png";
var currentDir = Environment.CurrentDirectory;
var targetPath = Path.Combine(currentDir, targetFile);
var targetDir = Path.GetDirectoryName(targetPath);
Directory.CreateDirectory(targetDir);
File.Copy(dialog.FileName, targetPath, true);
image.Source = new BitmapImage(new Uri(targetPath));
}
In order to release the file directly after loading the BitmapImage, load it from a FileStream:
BitmapImage bitmap = new BitmapImage();
using (var stream = File.OpenRead(targetPath))
{
bitmap.BeginInit();
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.StreamSource = stream;
bitmap.EndInit();
}
image.Source = bitmap;

Related

Loading Image from memory in Windows Phone

I'd like to be able to take a photo, display it, and keep the location so I can save it to a record and be able to display it at a later point.
I've been able to display it fine using the code
BitmapImage bmp = newBitmapImage();
bmp.SetSource(e.ChosenPhoto);
myImage.Source = bmp2;
When myImage is the image being displayed, and e is a PhotoResult object. However, as I need to save this in a record, I tried to use this code to display the photo based on the location.
string imageLoc = e.OriginalFileName;
Uri imageUri = new Uri(imageLoc, UriKind.Relative);
StreamResourceInfo resourceInfo = Application.GetResourceStream(imageUri);
BitmapImage bmp = BitmapImage();
bmp.SetSource(resourceInfo.Stream);
myImage.Source = bmp;
When I run this code, I get a System.NullReferenceException. I assume it's to do with the Application.GetResourceStream, but I'm just not certain what's going wrong.
For clarification, I'd like to be able to load and display a photo from a location such as
'C:\Data\Users\Public\Pictures\Camera Roll\imageExample.jpg'
if you want to save image in windows phone device, you need to user IsolatedStorage.
Save Image =>
String tempJPEG = "logo.jpg";
// Create virtual store and file stream. Check for duplicate tempJPEG files.
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);
BitmapImage bitmap = new BitmapImage();
bitmap.SetSource(sri.Stream);
WriteableBitmap wb = new WriteableBitmap(bitmap);
// Encode WriteableBitmap object to a JPEG stream.
Extensions.SaveJpeg(wb, fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);
//wb.SaveJpeg(fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);
fileStream.Close();
}
Read Image =>
BitmapImage bi = new BitmapImage();
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile("logo.jpg", FileMode.Open, FileAccess.Read))
{
bi.SetSource(fileStream);
this.img.Height = bi.PixelHeight;
this.img.Width = bi.PixelWidth;
}
}
this.img.Source = bi;
If you want to get pictures from MediaLibrary (Camera roll, Saved Pictures ..) then you can accomplish your task:
using PhotoChooserTask
or using MediaLibrary and here is good example
Your code can look for example like this (I've edited it to use only Images from Camera Roll):
You get your picture stream with line picture.GetImage() - this method return Stream which you can use for example to copy to IsolatedStorage.
private void MyImg()
{
using (MediaLibrary mediaLibrary = new MediaLibrary())
foreach (PictureAlbum album in mediaLibrary.RootPictureAlbum.Albums)
{
if (album.Name == "Camera Roll")
{
PictureCollection pictures = album.Pictures;
foreach (Picture picture in pictures)
{
// example how to use it as BitmapImage
// BitmapImage image = new BitmapImage();
// image.SetSource(picture.GetImage());
// I've commented that above out, as you can get Memory Exception if
// you try to read all pictures to memory and not handle it properly.
// Example how to copy to IsolatedStorage
using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!storage.DirectoryExists("SavedImg"))
storage.CreateDirectory("SavedImg");
if (storage.FileExists("SavedImg" + #"\" + picture.Name))
storage.DeleteFile("SavedImg" + #"\" + picture.Name);
using (IsolatedStorageFileStream file = storage.CreateFile("SavedImg" + #"\" + picture.Name))
picture.GetImage().CopyTo(file);
}
}
}
}
}

after selecting image display same image inside picturebox

on buttonclick I'm taking image from file system and save into database, everything is ok but I want when I select image to display that image into pictureBox1
OpenFileDialog open = new OpenFileDialog() { Filter = "Image Files(*.jpeg;*.bmp;*.png;*.jpg)|*.jpeg;*.bmp;*.png;*.jpg" };
if (open.ShowDialog() == DialogResult.OK)
{
txtPhoto.Text = open.FileName;
}
string image = txtPhoto.Text;
Bitmap bmp = new Bitmap(image);
FileStream fs = new FileStream(image, FileMode.Open, FileAccess.Read);
byte[] bimage = new byte[fs.Length];
fs.Read(bimage, 0, Convert.ToInt32(fs.Length));
fs.Close();
byte[] Photo = bimage;
You can use Image property to set the Image for PictureBox Control.
Try This:
DialogResult result= openFileDialog1.ShowDialog();
if(result==DialogResult.OK)
pictureBox1.Image =new Bitmap(openFileDialog1.FileName);
if you want to add it in your code
Complete Code:
OpenFileDialog open = new OpenFileDialog() { Filter = "Image Files(*.jpeg;*.bmp;*.png;*.jpg)|*.jpeg;*.bmp;*.png;*.jpg" };
if (open.ShowDialog() == DialogResult.OK)
{
txtPhoto.Text = open.FileName;
}
string image = txtPhoto.Text;
Bitmap bmp = new Bitmap(image);
pictureBox1.Image = bmp;//add this line
FileStream fs = new FileStream(image, FileMode.Open, FileAccess.Read);
byte[] bimage = new byte[fs.Length];
fs.Read(bimage, 0, Convert.ToInt32(fs.Length));
fs.Close();
byte[] Photo = bimage;
Simple code:
picturebox.Image = Bitmap.FromFile(yourimagepath);
OpenFileDialog open = new OpenFileDialog()
{
Filter = "Image Files(*.jpeg;*.bmp;*.png;*.jpg)|*.jpeg;*.bmp;*.png;*.jpg"
};
if (open.ShowDialog() == DialogResult.OK)
{
PictureBoxObjectName.Image = Image.FromFile(open.FileName);
}
openFileDialog1.Multiselect = false;
openFileDialog1.Filter= "jpg files (*.jpg)|*.jpg";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
foreach (String file in openFileDialog1.FileNames)
{
picturebox1.Image = Image.FromFile(File);
}
}
This is for selection of one image.

WPF - can't get resource file

I have file animaha135.gif in /Images folder, set "Build Action" as "Embedded Resource" or "Resources", I want to get this image to bitmap:
var image = new BitmapImage();
image.BeginInit();
image.UriSource = new Uri("pack://application:,,,/Images/animaha135.gif");
image.EndInit();
but it does not work:
Cannot locate resource 'images/animaha135.gif'.
what I do incorrectly?
solved this problem. Name of assembly was another than name of project. I set the same and my first code works
Don t build as "Embedded Resource". Build as "Resource". -> worked for me
EDIT:
use this to create your uri:
protected static Uri GetUri(string filename, Type type)
{
Assembly assembly = type.Assembly;
string assemblyName = assembly.ToString().Split(',')[0];
string uriString = String.Format("pack://application:,,,/{0};component/{1}",
assemblyName, filename);
return new Uri(uriString);
}
I used this for custom shadereffects
If you use embeed resources, you need read assembly maniffest
private void LoadImg()
{
//x is name of <Image name="x"/>
x.Source = GetResourceTextFile(GetResourcePath("Images/animaha135.gif"));
}
private string GetResourcePath(string path)
{
return path.Replace("/", ".");
}
public BitmapFrame GetResourceTextFile(string filename)
{
string result = string.Empty;
using (Stream stream = this.GetType().Assembly.GetManifestResourceStream(String.Format("{0}.{1}",this.GetType().Assembly.GetName().Name,filename)))
{
BitmapFrame bmp = BitmapFrame.Create(stream);
return bmp;
}
}
Other solution (return Bitmap):
//Use BitmapImage bitmap = GetResourceTextFile(GetResourcePath("Images/animaha135.gif"));
public BitmapImage GetResourceTextFile(string filename)
{
string result = string.Empty;
using (Stream stream = this.GetType().Assembly.GetManifestResourceStream(String.Format("{0}.{1}",this.GetType().Assembly.GetName().Name,filename)))
{
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.StreamSource = stream;
bi.EndInit();
return bi;
}
}
Note: Embed resources replace path => / by .

Set WPF Image Source from a Hyper Link (from Internet)

I try to set WPF image source from an Internet link. How can I do this?
I tried this, but doesn't work:
Image image1 = new Image();
BitmapImage bi3 = new BitmapImage();
bi3.BeginInit();
bi3.UriSource = new Uri("link" + textBox2.Text + ".png", UriKind.Relative);
bi3.CacheOption = BitmapCacheOption.OnLoad;
bi3.EndInit();
Prepending "link" to the URL is certainly incorrect. Just make sure that you type the full path of your image into your textbox.
// For example, type the following address into your text box:
textBox2.Text = "http://www.gravatar.com/avatar/ccac9a107581b343e832a2b040278b98?s=128&d=identicon&r=PG";
bi3.UriSource = new Uri(textBox2.Text, UriKind.RelativeOrAbsolute);

How to save an image to a file in WPF

I am new in wpf control and framework. I cant seem to save my images can you help me
Below is my code
SaveFileDialog sfd = new SaveFileDialog();
sfd.FileName = System.IO.Path.GetFileNameWithoutExtension(newlist[currentPicture]);
Nullable<bool> result = sfd.ShowDialog();
if (result == true)
{
System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(newlist[currentPicture]);
bmp.Save(newlist[currentPicture]);
}
For a System.Drawing.Bitmap, you need to pass the dialog's FileName property to the Save method.
EDIT: In WPF:
var encoder = new PngBitmapEncoder()
encoder.Frames.Add(BitmapFrame.Create(image));
using (var stream = dialog.OpenFile())
encoder.Save(stream);

Categories