How to cache images from PictureBox in C# winform - c#

Im trying to load images from a website. It loads very slowly. Everytime its selected. Any way to cache the image.
picturebox1.ImageLocation = "http://example.com/Image.jpg";
That form will be opened many times frequently, right now each time form is opened, images are being downloaded every time. It is unnecessary increasing traffic.
Is it possible to tell PictureBox to cache image (as Browser do), so next time same images is requested, it should load quickly. Is this possible?
if (listBox1.SelectedIndex == 0)
{
richTextBox1.Text = "Explore any game with Dex";
Image img = Image.FromFile("https://i.imgur.com/Jb6lTp1.png");
pictureBox1.Image = img;
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
It says given path format is not supported

Try this way:
First Create a function to check whether file exist or not. If exist then simply load the file from local path else download the file from URL and store it in local.
//Function to validate the local cache file
private Image load_image()
{
Image img=null;
if(!(File.Exists(#"d:\samp.png")))
{
using (HttpClient httpclient= new HttpClient())
{
var response = httpclient.GetAsync(#"https://i.imgur.com/Jb6lTp1.png");
if (!response.Result.IsSuccessStatusCode)
{
return img;
}
using (var fs= new FileStream(#"d:\samp.png",FileMode.CreateNew)) // Path can be added as parameter of function
{
response.Result.Content.CopyToAsync(fs);
}
}
}
img = Image.FromFile(#"d:\samp.png");
return img;
}
//calling the function of click event
private void button1_Click(object sender, EventArgs e)
{
if (listBox1.SelectedIndex == 0)
{
richTextBox1.Text = "Explore any game with Dex";
pictureBox1.Image = load_image();
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
}
}
NOTE: Handle the exceptions where ever required. Use parameters in function as per requirement

Use PictureBox's Load method in the Form1_Load event. Also make sure the URL is valid.
private void Form1_Load(object sender, EventArgs e)
{
pictureBox1.Load("https://www.nippon.com/en/ncommon/contents/japan-data/169591/169591.jpg");
}

Related

Make a picturebox change itself very fast between 2 pictures (Windows Forms app)

I want to make a picture change itself very fast between 2 pictures. I have the pictures saved in the debug folder of the program.
Here is the image of pictures with there names saved:
https://i.stack.imgur.com/XQ9g5.png
So here is the code were I save a picture in the picturebox so that there is not an empty picturebox
private void Gamble_Load(object sender, EventArgs e)
{
pictureBox1.Image = (Image.FromFile("21.png"));
}
And here is the timer click method I think I need to use for this action
private void timer1_Tick(object sender, EventArgs e)
{
pictureBox1.Image = pictureBox1.Image is null;
}
Try putting this in your Gamble_Load:
var t = new Timer(x => pictureBox1.Image = (Image.FromFile("otherimage.png")), null, 1000);
This creates a timer that will fire after 1 second and update the image.
https://learn.microsoft.com/en-us/dotnet/api/system.timers.timer?view=net-6.0

How do I take an Screenshot of my camera on EMGUCV 3.1?

I'm doing a very simple program on EMGU CV, so I need to take a screenshot of what my camera is recording and save it in a specific folder, here follows my code of camera capture:
ImageViewer viewer = new ImageViewer();
VideoCapture capture = new VideoCapture();
Application.Idle += new EventHandler(delegate (object sender, EventArgs e)
{
viewer.Image = capture.QueryFrame();
});
viewer.ShowDialog();
I apologize for the simple terms, I still really noob in programming.
It seems like you just posted the standard code from the EmguCV wiki. But let me try to explain how you can show a video feed of your webcam on your computer and save a screenshot when you press a button (you'll have to create all the UI elements yourself). You'll need a form with an PictureBox element to display the image and a button to save a snapshot.
I'll explain everything in the code through comments and work from the standard EmguCV code:
private Capture capture;
private bool takeSnapshot = false;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// Make sure we only initialize webcam capture if the capture element is still null
if (capture == null)
{
try
{
// Start grabbing data, change the number if you want to use another camera
capture = new Capture(0);
}
catch (NullReferenceException excpt)
{
// No camera has been found
MessageBox.Show(excpt.Message);
}
}
// This makes sure the image will be fitted into your picturebox
originalImageContainer.SizeMode = PictureBoxSizeMode.StretchImage;
// When the capture is initialized, start processing the images in the PorcessFrame method
if (capture != null)
Application.Idle += ProcessFrame;
}
// You registered this method, so whenever the application is Idle, this method will be called.
// This allows you to process a new frame during that time.
private void ProcessFrame(object sender, EventArgs arg)
{
// Get the newest webcam frame
Image<Bgr, double> capturedImage = capture.QueryFrame();
// Show it in your PictureBox. If you don't want to convert to Bitmap you should use an ImageBox (which is an EmguCV element)
originalImageContainer.Image = capturedImage.ToBitmap();
// If the button was clicked indicating you want a snapshot, save the image
if(takeSnapshot)
{
// Save the image
capturedImage.Save(#"C:\your\picture\path\image.jpg");
// Set the bool to false again to make sure we only take one snapshot
takeSnapshot = !takeSnapshot;
}
}
//When clicking the save button
private void SaveButton_Click(object sender, EventArgs e)
{
// Set the bool to true, so that on the next frame processing the frame will be saved
takeSnapshot = !takeSnapshot;
}
Hope this helps you. Let me know if anything is still unclear!
Sometimes Bgr cannot be converted to bitmap directly. Instead I do employ
following lines:
Emgu.CV.Mat capturedImage = capture.QueryFrame();
pictureBox1.Image = capturedImage.Bitmap;

How to permanently display the placed image

I created a windows form that displays and image as a Logo. I was able to browse and display an image to the PictureBox with this code:
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "jpg (*.jpg)|*.jpg|bmp (*.bmp)|*.bmp|png (*.png)|*.png";
if (ofd.ShowDialog() == DialogResult.OK && ofd.FileName.Length > 0)
{
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
pictureBox1.Image = Image.FromFile(ofd.FileName);
}
}
I want the placed image saved in that PictureBox to be displayed every time the Form is called. What code do I need to write in order to do that?
On the load event of the form you can set the image of the picture box. By going to project settings, Resources tab, you can add an image as a Resource and reference it using the ProjectNamespace.Resources.NameOfResource.
You need a special kind of pictureBox that shows the logo. Let's call this a LogoBox. If you make this a user control you can use Visual Studio Toolbox to add it to your controls.
In Visual Studio:
Open the project where the LogoBox is to be used, or put it in a DLL, so it can be used by several executables.
Menu: Project - Add User Control, Name it LogoBox
Use the Toolbox to add a PictureBox to the user control.
Change the Dock style of picture box to DockStyle.Fill
Use properties to add an event handler for the Load Event, let's call it OnLoad.
Your LogoBox class will need a property to change the image that will be used as a logo. I use the same function as PictureBox.Image, but call it Logo:
[BindableAttribute(true)]
public Image Logo
{
get {return this.pictureBox1.Image;}
set
{
this.pictureBox1.Image = image;
}
}
This code is not enough: the next time you load this LogoBox you want it to load its last set Logo. The esiest method is to save the last set image in a file, because then you know certain that if the user of your LogoBox deletes the original image after setting it you still have your own saved copy.
You'll need a filename for the file. User project properties - settings to create a filename.
Make it a string property with application scope (it will never change)
Name: LogoFileName
Value: think of something nice. Logo.Img?
.
[BindableAttribute(true)]
public Image Logo
{
get {return this.pictureBox1.Image;}
set
{
this.pictureBox1.Image = image;
image.Save(Properties.Settings.Default.LogoFileName)
}
}
Finally load the image when your LogoBox is loaded:
private void OnFormLoading(object sender, EventArgs e)
{
var img = Image.FromFile(Properties.Settings.Default.LogoFileName);
this.pictureBox1.Image = img;
}
Don't use this.Logo = img, because that will save the image again which is a waste of time.
The only thing to do is error handling if the logo file does not exist.
Then lets have a static thing.
Within your form, implement a static paths for your image..say
public string prg_form_image
{
get { return "myimage.jpg"; }
}
public string prg_image_path
{
get { return this.AppDomain.CurrentDomain.BaseDirectory + "image\\"; }
}
private string myImage
{
get
{
return File.Exists(prg_image_path + prg_form_image)
? prg_image_path + prg_form_image
: prg_image_path + "default.jpg";
}
}
public Image img
{
get { return Image.FromFile(prg_image_path + prg_form_image); }
}
private void SetImage()
{
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
pictureBox1.Image = img;
}
private void Form_Load(object sender, EventArgs e)
{
SetImage();
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "jpg (*.jpg)|*.jpg|bmp (*.bmp)|*.bmp|png (*.png)|*.png";
if (ofd.ShowDialog() == DialogResult.OK && ofd.FileName.Length > 0)
{
if(File.Exists(prg_image_path + prg_form_image))
{
File.Delete(prg_image_path + prg_form_image);
}
if(!Directory.Exists(prg_image_path)) { Directory.Create(prg_image_path); }
Image imgIn = Image.FromFile(ofd.FileName);
imgIn.SaveAs(prg_image_path + prg_form_image);
SetImage();
}
}
Notes : Folder name image should exists along-side your executable program. a default.jpg should also exist inside the folder image.

How to create a video file out of bitmaps?

Is there any way for how to record the images into a video file (output.avi) by implementing some code inside the NewFrame event handler. Also how can we make the size of file not too much big?
I've got a pictureBox1 and a button1 and I'm using the code below to switch on the webcam and display the output on pictureBox1
The code works fine. However, I need to implement a way to Save the output to a video file rather than showing it on the pictureBox
I use the code below
private void button1_Click(object sender, EventArgs e)
{
videoSource = new VideoCaptureDevice(videoDevices[comboBox1.SelectedIndex].MonikerString);
videoSource.NewFrame += new NewFrameEventHandler(video_NewFrame);
///
CloseVideoSource();
videoSource.Start();
}
private void video_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
Bitmap img = (Bitmap)eventArgs.Frame.Clone();
pictureBox1.Image = img; // Something should go here to make the video file out of successive bitmaps ?
}
private void CloseVideoSource()
{
if (!(videoSource == null))
if (videoSource.IsRunning)
{
videoSource.SignalToStop();
videoSource = null;
}
}
I think all you need is to use the VideoFileWriter class. There's a nice demo in the AForge.Net documentation.
Note that your code will need to include the FFMPEG dlls found in the Externals folder in your AForge installation directory.

Change button image after clicking it

i have picturebox with picture cb.
PBr1_1.Image = new Bitmap(#"Logos\\Images\\cb.png");
I'd like to change image to cg.png and do some action when i click this image. I was trying something like that but without success:
private void PBr1_1_Click(object sender, EventArgs e)
{
if (PBr1_1.Image.ToString() == "cb.png")
{
PBr1_1.Image = new Bitmap(#"Logos\\Images\\cg.png");
// Do some stuff.
}
}
And then do the same when i click image with cb. To visualise this cb is black circle button image, and cg is green one.
How can i do this?
Jason is right, you should use some kind of temporary storage to save your current bitmap.
The Tag property is useful in this kind of situations. Here a sample code: (Without error handling)
somewhere in your load event
PBr1.Tag = "cb.png";`
PBr1_1.Image = new Bitmap(Path.Combine("Logos\\Images", PBr1.Tag.ToString());
and then in button click
private void PBr1_1_Click(object sender, EventArgs e)
{
string imgPath = "Logos\\Images";
PBr1_1.Image.Dispose();
PBr1_1.Tag = (PBr1_1.Tag == "cb.png" ? "cg.png") : "cb.png") ;
Bitmap bm = new Bitmap(Path.Combine(imgPath, PBr1.Tag.ToString());
PBr1_1.Image = bm;
}
Are you sure that "PBr1_1.Image.ToString()" really returns only the image name?
Maybe you should check this by writing PBr1_1.Image.ToString() to console or something like that

Categories

Resources