Display an image into windows forms - c#

I wanted to display an image to the windows forms, but i already did this and the image did not come out.
Where did I go wrong?
Here is the code:
private void Images(object sender, EventArgs e)
{
PictureBox pb1 = new PictureBox();
pb1.Image = Image.FromFile("../SamuderaJayaMotor.png");
pb1.Location = new Point(100, 100);
pb1.Size = new Size(500, 500);
this.Controls.Add(pb1);
}

Here (http://www.dotnetperls.com/picturebox) there 3 ways to do this:
Like you are doing.
Using ImageLocation property of the PictureBox like:
private void Form1_Load(object sender, EventArgs e)
{
PictureBox pb1 = new PictureBox();
pb1.ImageLocation = "../SamuderaJayaMotor.png";
pb1.SizeMode = PictureBoxSizeMode.AutoSize;
}
Using an image from the web like:
private void Form1_Load(object sender, EventArgs e)
{
PictureBox pb1 = new PictureBox();
pb1.ImageLocation = "http://www.dotnetperls.com/favicon.ico";
pb1.SizeMode = PictureBoxSizeMode.AutoSize;
}
And please, be sure that "../SamuderaJayaMotor.png" is the correct path of the image that you are using.

There could be many reasons for this. A few that come up quickly to my mind:
Did you call this routine AFTER InitializeComponent()?
Is the path syntax you are using correct? Does it work if you try it in the debugger? Try using backslash (\) instead of Slash (/) and see.
This may be due to side-effects of some other code in your form. Try using the same code in a blank Form (with just the constructor and this function) and check.

I display images in windows forms when I put it in Load event like this:
private void Form1_Load( object sender , EventArgs e )
{
pictureBox1.ImageLocation = "./image.png"; //path to image
pictureBox1.SizeMode = PictureBoxSizeMode.AutoSize;
}

private void Form1_Load(object sender, EventArgs e)
{
PictureBox pb = new PictureBox();
pb.Location = new Point(0, 0);
pb.Size = new Size(150, 150);
pb.Image = Image.FromFile("E:\\Wallpaper (204).jpg");
pb.Visible = true;
this.Controls.Add(pb);
}

Related

How to clear a pictureBox in C#? I have tried setting the property to null but it doesnt work

I would like to clear a pictureBox after clicking on an 'Encode' button to save it as a new image file in my project. I would like to clear the fields on the form after the user saves the image file.
The code I use to display image on pictureBox:
private void btnOpenfile_Click(object sender, EventArgs e)
{
// open file dialog
OpenFileDialog open = new OpenFileDialog();
// image filters
open.Filter = "Image Files (*.png)|*.png";
if (open.ShowDialog() == DialogResult.OK)
{
// display image in picture box
pictureBox1.Image = new Bitmap(open.FileName);
pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
tbFilepath.Text = open.FileName;
//pictureBox1.ImageLocation = tbFilepath.Text;
}
}
The code I used to clear the pictureBox:
private void clearForm()
{
pictureBox1.Image = null; //doesn't work
pictureBox1.Invalidate(); //doesn't work
tbFilepath.Text = "";
tbMessage.Text = "";
}
I have also tried the following but it did not work either:
private void clearForm()
{
Bitmap bm = new Bitmap(img);
bm.Save(tbFilepath.Text,System.Drawing.Imaging.ImageFormat.Png);
}
I tried using the Refresh() method as one of the commentors suggested, but it did not work either:
private void clearForm()
{
Refresh(); //first attempt
pictureBox1.Refresh();// second attempt
}
I expect the pictureBox field to clear out the existing image I have selected but the image did not clear away.
Before clicking on encode button
After clicking on encode button, the textBox fields are cleared but not the pictureBox field. I used the codes I have added in this question.
Try creating a new Bitmap Variable and use it for the picturebox:
Bitmap bitmap = new Bitmap(pictureBox.Width, pictureBox.Height);
pictureBox.Image = bitmap;
pictrueBox.Invalidate();
Also, try to declare a Global Variable for the Bitmap so it is the one to be set as the picture and also the one to be cleared before setting it as the image for the PictureBox.
On the other hand you could try using the OnPaint Method of the Picurebox:
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
bm = new Bitmap(pictureBox1.Width, pictureBox1.Height);
}
Bitmap bm = null;
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
pictureBox1.Image = bm;
}
private void btn_Open_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp); *.PNG|*.jpg; *.jpeg; *.gif; *.bmp; *.PNG";
if (ofd.ShowDialog() == DialogResult.OK)
{
bm = new Bitmap(Image.FromFile(ofd.FileName), new Size(pictureBox1.Width, pictureBox1.Height));
textBox1.Text = ofd.FileName;
pictureBox1.Invalidate();
}
}
private void btn_Clear_Click(object sender, EventArgs e)
{
bm = null;
pictureBox1.Invalidate();
}
These code I made worked perfectly. So please try it.

Click on a picturebox and go to website

I have a pictureBoxes that are being created at run time and I would like to be able to click on that box and go to a webpage after the program completes. How can I create a click event for something like this?
This is what I am thinking:
PictureBox PB = new PictureBox();
PB.Name = "PB" + i.ToString();
PB.Location = new Point(51 * i, 331);
PB.Size = new Size(50, 50);
PB.ImageLocation = Sub1;
Controls.Add(PB);
PB.Click +=new EventHandler(PB_Click);
protected void PB_Click(object sender, EventArgs e)
{
MessageBox.Show("You clicked the mouse over the PictureBox");
}
Is this on the right track?
If you want open Internet explorer and navigate to the desired address automatically, use this:
Process.Start("iexplore.exe", "http://www.google.com");
After fooling around a little I figured it out and thought I would post my solution, maybe someone else could benefit. I decided to take the easy route and just open up the link using webrowser control on the form.
![private void FrmWeb_Btn_Click(object sender, EventArgs e)
{
PictureBox PB = new PictureBox();
PB.ImageLocation = "https://si0.twimg.com/profile_images/378800000038434114/f676cbea6f8500c9c15529e1d5e548c1_reasonably_small.jpeg";
PB.Size = new Size(100, 100);
Controls.Add(PB);
PB.Click +=new EventHandler(PB_Click);
}
protected void PB_Click(object sender, EventArgs e)
{
webBrowser1.Navigate("http://twit.tv/");
}][2]

C# save bitmap output

I'm creating a C# program that's capturing the screen with bitmap.
And than I want to save it to an .Avi/ .mpeg file.
But I don't know how to save it to a video.
Here is the code I already have.
public Form1()
{
InitializeComponent();
}
static Bitmap bm;
private void btnFolder_Click(object sender, EventArgs e)
{
FolderBrowserDialog folderDlg = new FolderBrowserDialog();
folderDlg.ShowNewFolderButton = true;
DialogResult result = folderDlg.ShowDialog();
if (result == DialogResult.OK)
{
textBox1.Text = folderDlg.SelectedPath;
Environment.SpecialFolder root = folderDlg.RootFolder;
}
}
private void btnStart_Click(object sender, EventArgs e)
{
timer1.Start();
}
private void btnStop_Click(object sender, EventArgs e)
{
timer1.Stop();
SaveCapture(textBox1.Text);
}
private void SaveCapture(string path)
{
// Here should be the code to save it to mpeg/avi
}
private void timer1_Tick(object sender, EventArgs e)
{
// Take screenshot
bm = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
Graphics graphics = Graphics.FromImage(bm as Image);
graphics.CopyFromScreen(0, 0, 0, 0, bm.Size);
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
// Show it in picturebox
pictureBox1.Image = bm;
}
Thank you very much!
Create a Video Stream (AVI) from a Series of Images
I think this might be your best solution. Store all the .jpg's and create an avi from the command line at intervals. I don't see how creating video on the fly would produce a "lightweight" solution.
Hello click this to download the aviwrapper liblary. And the code that you should write is this:
var pngFileList = Directory.EnumerateFiles(folderImages, "*.png");
//load the first image
Bitmap bitmap = (Bitmap)Image.FromFile(pngFileList.First());
//create a new AVI file
AviManager aviManager = new AviManager(fileName, false); // location and the name of video file
//add a new video stream and one frame to the new file
//set IsCompressed = false
VideoStream aviStream = aviManager.AddVideoStream(false, 3, bitmap);
pngFileList.Skip(1).ToList().ForEach(file =>
{
bitmap = (Bitmap)Bitmap.FromFile(file);
aviStream.AddFrame(bitmap);
bitmap.Dispose();
});
aviManager.Close();

C# Embed Image in New Outlook Mail Item from Standalone Application

What is the best way of embedding an image into a new outlook mail item from a Stand Alone application. Not building an add-in for outlook.
Trying to embed or attach an existing picture to a new email item. I have read and looked at a lot of sources but most of these are tied into exchange or by using AddIn methods in Outlook.
User would see the image embedded into the new email and would just need to fill out the "To:" field. Would like to make the subject pre-populated in new email message as well from application.
Code Below: (I am trying to attach the picture that I capture below to an outlook email!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net.Mail;
using System.Net.Mime;
namespace While_You_Were_Out
{
public partial class main : Form
{
public main()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
WindowState = FormWindowState.Normal;
Show();
Rectangle l = Screen.PrimaryScreen.WorkingArea;
//Sets Position Manual all other Dialogs are set within parent center area.
this.StartPosition = FormStartPosition.Manual;
this.Location = new Point(Screen.PrimaryScreen.WorkingArea.Width - this.Width, Screen.PrimaryScreen.WorkingArea.Height - this.Height);
}
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
new AboutDialog().ShowDialog(this);
}
private void trayIcon_MouseDoubleClick(object sender, MouseEventArgs e)
{
WindowState = FormWindowState.Normal;
Show();
Rectangle l = Screen.PrimaryScreen.WorkingArea;
//Sets Position Manual all other Dialogs are set within parent center area.
this.StartPosition = FormStartPosition.Manual;
this.Location = new Point(Screen.PrimaryScreen.WorkingArea.Width - this.Width, Screen.PrimaryScreen.WorkingArea.Height - this.Height);
}
private void trayRightClickMenu2_Opening(object sender, CancelEventArgs e)
{
}
private void toolStripMenuExit_Click(object sender, EventArgs e)
{
//Exit Application
Application.Exit();
}
private void toolStripMenuOpen1_Click(object sender, EventArgs e)
{
WindowState = FormWindowState.Normal;
Show();
Rectangle l = Screen.PrimaryScreen.WorkingArea;
//Sets Position Manual all other Dialogs are set within parent center area.
this.StartPosition = FormStartPosition.Manual;
this.Location = new Point(Screen.PrimaryScreen.WorkingArea.Width - this.Width, Screen.PrimaryScreen.WorkingArea.Height - this.Height);
}
private void button1_Click(object sender, EventArgs e)
{
//Hides to System Tray
this.Hide();
trayIcon.Visible = true;
//Dispose();
}
private void button2_Click(object sender, EventArgs e)
{
}
private void sendNotificationToolStripMenuItem_Click(object sender, EventArgs e)
{
/* Bitmap bmp = new Bitmap(panel1.Width, panel1.Height);
panel1.DrawToBitmap(bmp, new Rectangle(0, 0, bmp.Width, bmp.Height));
bmp.Save(#"C:\Razor\wywo_notification.jpg");
bmp.Dispose();*/
SaveAsBitmap(panel1, #"C:\Users\Razor\wywo_notification.jpg");
}
private void clearFormToolStripMenuItem_Click(object sender, EventArgs e)
{
txtBox6.Text = string.Empty;
txtBox8.Text = string.Empty;
txtBox9.Text = string.Empty;
}
public void SaveAsBitmap(Control control, string fileName)
{
//get the instance of the graphics from the control
Graphics g = control.CreateGraphics();
//new bitmap object to save the image
Bitmap bmp = new Bitmap(panel1.Width, panel1.Height);
//Drawing control to the bitmap
panel1.DrawToBitmap(bmp, new Rectangle(0, 0, control.Width, control.Height));
bmp.Save(fileName);
bmp.Dispose();
}
private void sendToOutlook_Click(object sender, EventArgs e)
{
}
}
}
I was able to perform the function with VBS Script:
Set olApp = CreateObject("Outlook.Application")
Set olMsg = olApp.CreateItem(0)
With olMsg
.To = "test#test.com"
'.CC = "cc#test.com"
'.BCC = "bcc#test.com"
.Subject = "Subject"
.HTMLBody = "<html><p>This is a picture.</p>" & _
"<img src='cid:wywo_notification.jpg'>"
'.Body = "<IMG align=baseline border=0 hspace=0 src=cid:myident>"
'.Attachments.Add "C:\users\doej\wywo_notification.jpg"
'.Attachments.Add "C:\users\doej\wywo_notification.jpg"
.Display
End With
I was able to solve my problem by relying on an VBS script called from within the application it was simple and solved my issue.
Create an attachment and set the PR_ATTACH_CONTENT_ID property (DASL name "http://schemas.microsoft.com/mapi/proptag/0x3712001F") using Attachment.PropertyAccessor.
Your HTML body would then need to reference that image attachment through the cid:
img src="cid:xyz"
where xyz is the value of the PR_ATTACH_CONTENT_ID property.
Look at an existing message with OutlookSpy (I am its author - click IMessage button).

how to display image in a grid using C# for WP8?

i need to insert an image in a WP8. i have a stack of images. once i click the image, it has to be set as background for a grid. so i created an empty "grid1" and button. wrote the below code in the button click event, but the image doesnot get displayed !
private void bg6_Click(object sender, RoutedEventArgs e)
{
System.Windows.Media.ImageBrush myBrush = new System.Windows.Media.ImageBrush();
Image image = new Image();
image.Source = new System.Windows.Media.Imaging.BitmapImage(
new Uri("\\PhoneApp2\\PhoneApp2\\Assets\\bg\\bg5.jpg"));
myBrush.ImageSource = image.Source;
// Grid grid1 = new Grid();
grid1.Background = myBrush;
}
It is hard to know if your image file is in the correct place and set to the right build type. I'd suggest adding an event handler to the Image failed event.
private void bg6_Click(object sender, RoutedEventArgs e)
{
System.Windows.Media.ImageBrush myBrush = new System.Windows.Media.ImageBrush();
Image image = new Image();
image.ImageFailed += (s, e) => MessageBox.Show("Failed to load: " + e.ErrorException.Message);
image.Source = new System.Windows.Media.Imaging.BitmapImage(
new Uri("\\PhoneApp2\\PhoneApp2\\Assets\\bg\\bg5.jpg"));
myBrush.ImageSource = image.Source;
// Grid grid1 = new Grid();
grid1.Background = myBrush;
}
First, you don't need to use Image to fill the background from URI.
private void bg6_Click(object sender, RoutedEventArgs e)
{
System.Windows.Media.ImageBrush myBrush = new System.Windows.Media.ImageBrush(new Uri("\\PhoneApp2\\PhoneApp2\\Assets\\bg\\bg5.jpg"));
// Grid grid1 = new Grid();
grid1.Background = myBrush;
}
Second, it is a WAY better to design it in XAML and manipulate it visibility and source from code by creating the helper class with visibility and source property. Don't forget to implement INotifyPropertyChanged interface into that class.
<Grid x:Name="myGrid" DataContext="{Binding}" Visibility="{Binding Path=VisibleProperty}">
<Grid.Background>
<ImageBrush x:Name="myBrush" ImageSource="{Binding Path=SourceProperty}"></ImageBrush>
</Grid.Background>
And in code:
private void bg6_Click(object sender, RoutedEventArgs e)
{
myGrid.DataContext=new myImagePresenterClass(new Uri("\\PhoneApp2\\PhoneApp2\\Assets\\bg\\bg5.jpg"), Visibility.Visible)
}
public class myImagePresenterClass:INotifyPropertyChanged
{
private URI sourceProperty
Public URI SourceProperty
{
get
{
return sourceProperty;
}
set
{
sourceProperty=value;
if(PropertyChanged!=null){PropertyChanged(this, new PropertyChangedEventArgs("SourceProperty"));}
}
}
//Don't forget to implement the Visible property the same way as SourceProperty and the class constructor.
}
i found the mistake... i'm sorry guys. i didn't follow the syntax correctly. i missed the '#' in the Uri method. the correct way to represent this is
private void bg1_Click(object sender, RoutedEventArgs e)
{
System.Windows.Media.ImageBrush myBrush = new System.Windows.Media.ImageBrush();
Image image = new Image();
image.ImageFailed += (s, i) => MessageBox.Show("Failed to load: " + i.ErrorException.Message);
image.Source = new System.Windows.Media.Imaging.BitmapImage(new Uri(#"/Assets/bg/bg1.jpg/", UriKind.RelativeOrAbsolute));
myBrush.ImageSource = image.Source;
grid1.Background = myBrush;
}

Categories