Bitmap ArgumentException - c#

I'm trying to create an example program and I'm having issues creating the Bitmap needed for it. When I try running the code below I'm getting an ArgumentException.
I think this is being thrown because it cannot find the file on the disk. If this is the case where do I put the file in my project so it can find it? I've tried putting the file in the main project directory and have tried placing it within the debug and release folders.
If this is not what is causing the issue can someone point me in the right direction?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Drawing;
namespace Given
{
public class Photo : Form
{
Image image;
public Photo()
{
image = new Bitmap("jug.jpg"); // ArgumentException thrown here
this.Text = "Lemonade";
this.Paint += new PaintEventHandler(Drawer);
}
public virtual void Drawer(Object source, PaintEventArgs e)
{
e.Graphics.DrawImage(image, 30, 20);
}
}
}
namespace Photo_Decorator
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Given.Photo());
}
}
}

It's throwing this because it can't find the JPG, and therefore can't create a proper bitmap object. You need to either place the image file in the same folder as the EXE (Debug? Release?), or specify the entire path to the image (e.g C:/jug.jpg). Hope this helps :)

You'd need to put the file in the same folder as the executable (bin\Debug or bin\Release). You could place it in the bin folder and just use #"..\jug.jpg" as the path instead so it worked in both Debug and Release modes.

Related

Embedding DLL in a compiled C# executable

I am using scitersharp with WinForms and trying to build a single standalone compiled c# executable. It's a simple "Hello World" app which loads an HTML file. Initially after compilation 3 DLLs (sciter.dll, sciter64.dll and SciterSharpWindows.dll) were being generated in the bin\Debug folder. So, i googled and tried to find a solution to embed those dll files into the executable. Here is what i tried:
Loading the DLL in project window in visual studio and setting the build option as "Embedded resource"
Add references to the resources but this method didn't worked and it's giving me the following error:
`A reference to resource 'pathto\sciter.dll' could not be added. Please make sure the file is accesible and that it is a valid assembly or COM component`
Read the solutions from this stackoverflow question
Installed Cosutra.Fody package and rebuild the project. This time i managed to embed only the SciterSharpWindows.dll
Here is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Sciter;
using SciterSharp;
using SciterSharp.WinForms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
// Create a class-accesible sciter control
private SciterControl SciterElement;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// Create a new instance of the sciter control
SciterElement = new SciterControl();
// Set the callback once the element is ready to be used
SciterElement.HandleCreated += SciterControl1_HandleCreated;
// Add the Sciter Control to the Form and fill it
this.Controls.Add(SciterElement);
SciterElement.Dock = DockStyle.Fill;
}
private void SciterControl1_HandleCreated(object sender, EventArgs e)
{
// Initialize with some HTML
SciterElement.SciterWnd.LoadHtml(#"
<div style='padding: 0px 8px;'>
<h1>
Hello World
</h1>
</div>
");
}
}
}
Is there any way to embed these resources into the executable? Also, please let me know if i am missing something? Thank you in advance.
Here is a workaround maybe you can refer to.
First, add the dll to Reference and set Copy Local to False.
Then create a new project folder "libs", copy the referenced dll into this folder, and set Build Action to "Embedded Resources"
In the main() method, add code to handle the exception "dll not found".
static void Main()
{
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs e)
{
//The namespace of the project is embeddll, and the embedded dll resources are in the libs folder, so the namespace used here is: embeddll.libs.
string _resName = "embeddll.libs." + new AssemblyName(e.Name).Name + ".dll";
using (var _stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(_resName))
{
byte[] _data = new byte[_stream.Length];
_stream.Read(_data, 0, _data.Length);
return Assembly.Load(_data);
}
}

OpenGL4Net WM_PAINT does not exist?

I'm trying to get OpenGL4Net working with C# in Microsoft Visual Studio Comunity 2015.
I've downloaded this file:
https://sourceforge.net/projects/ogl4net/files/Rev.%2037/x64/
And followed these instructions:
https://sourceforge.net/p/ogl4net/wiki/Tutorials/
At first with a console application but then starting again with a Windows Form application as it seems as if it was going to be using the window from that as opposed to making its own.
So far the various refrances have been added, form1.cs is untouched and Program.cs looks like this:
using System;
using System.Collections.Generic;
//using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using OpenGL4NET;
namespace pads2
{
class Program : Form
{
RenderingContext rc;
static void Main(string[] args)
{
Program program = new Program();
program.Init();
Application.Run(program);
}
// required for open GL
void Init()
{
rc = RenderingContext.CreateContext(this);
SetStyle(ControlStyles.AllPaintingInWmPaint, true);
}
void Render()
{
gl.Clear(GL.COLOR_BUFFER_BIT);
// here is the right place to draw all your scene
rc.SwapBuffers();
}
// change window size
protected override void OnSizeChanged(EventArgs e)
{
gl.Viewport(0, 0, ClientSize.Width, ClientSize.Height);
// projection matrix may also need adjusting
}
// required for open GL
protected override void WndProc(ref Message m)
{
switch (m.Msg)
{
case Windows.WM_PAINT: Render(); break;
default: base.WndProc(ref m); break;
}
}
}
}
/*
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
/*
The compiler seems unhappy about the comment at the end of the code, however the main issue is that I recieve the error:
The type or namespace name 'WM_PAINT' does not exist in the namespace 'Windows' (are you missing an assembly reference?)
I've been unable to find what reference I need for WM_PAINT online, including a reference for System.Windows did not help.
Q: How can I solve this and am I setting this up correctly?
WM_PAINT is described in detail in its MSDN entry:
https://msdn.microsoft.com/en-us/library/windows/desktop/dd145213(v=vs.85).aspx
The article however omits its POD value, being the Integer constant "15".
Had this problem earlier, the example forgets to add the reference, the case should be:
case OpenGL4NET.Windows.WM_PAINT: Render(); break;
(Would comment if rep allowed me too)

Why is EmguCV throwing this StackOverFlowException when capturing?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Emgu.CV;
using Emgu.CV.Structure;
namespace WebcamTest
{
public partial class Form1 : Form
{
private Capture c;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
c = new Capture();
c.ImageGrabbed += ProcessFrame;
c.Start();
}
public void ProcessFrame(object sender, EventArgs e)
{
Image<Bgr, byte> image = c.QueryFrame();
c.ImageGrabbed -= ProcessFrame;
c.Stop();
c.Dispose();
}
}
}
So I have this really simple code to grab a webcam image and store it, just one time. It does nothing else currently, but I'm having a weird issue. In my file, one line seems to cause the issue:
Image<Bgr, byte> image = c.QueryFrame();
EDIT: I have tried changing this line to this as the wiki suggests:
Image<Bgr, byte> image = new Image<Bgr, byte>(c.RetreiveBgrFrame().ToBitmap());
This one always gives a null reference exception the first time; afterwards it acts the same as the other line. Every pixel's combined values are 0's after the first run.
Then I go a bit deeper into the problem,
I found that I keep getting a StackOverflowException in the Emgu.CV.dll itself. It continously says it is line 240 in this file: Capture.cs
The line is this:
bool grabbed = CvInvoke.cvGrabFrame(_ptr);
I have ran through their examples before and actually had them working before. I have never really had this issue before since it's coming from inside their dll. Why would this line keep causing this error? Is the pointer way off point for some unknown reason? The only thing I could think was that it was trying to access a memory location outside the actual bounds. It's always the very first run it does this. Then when it crashes, the camera stays on and so next time it runs. Though the image pixels are all 0's every time after that.

Aforge.net Camera Capture & Save image to directory

everyone. I have been stuck here dealing with this bugs for days, but I still couldn't figure it out.
My guess: I think my code has some problem as I did not dispose the object properly after using it, (I'm not very familiar with these concepts of releasing resources, threading) .
I got these code by taking reference of what people did on youtube, but despite me doing exactly the same thing, my code didn't work out nicely.
SITUATION:
I have two picture boxes, left one can take video of me, right one take the snapshot, if you press button1 , you will start the video, clone_button will copy a image i.e. take a snapshot, and save_image should save it to the path reference, however, i get a generic error occured in GDI+ again and again while I'm trying to save it. Also, my debugger seemed to get crazy (i.e. failed to terminate the vshost.exe ) once I ran this program, I have to restart the computer to get my code running again, which is bleak and frustrating.
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.Drawing.Imaging;
//AForge.Video dll
using AForge.Video;
using AForge.Video.DirectShow;
using AForge.Imaging;
using AForge.Imaging.Filters;
using AForge;
namespace WebCameraCapture
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private FilterInfoCollection CaptureDevice; // list of webcam
private VideoCaptureDevice FinalFrame;
private void Form1_Load(object sender, EventArgs e)
{
CaptureDevice = new FilterInfoCollection(FilterCategory.VideoInputDevice);//constructor
foreach (FilterInfo Device in CaptureDevice)
{
comboBox1.Items.Add(Device.Name);
}
comboBox1.SelectedIndex = 0; // default
FinalFrame = new VideoCaptureDevice();
}
private void button1_Click(object sender, EventArgs e)
{
FinalFrame = new VideoCaptureDevice(CaptureDevice[comboBox1.SelectedIndex].MonikerString);// specified web cam and its filter moniker string
FinalFrame.NewFrame += new NewFrameEventHandler(FinalFrame_NewFrame);// click button event is fired,
FinalFrame.Start();
}
void FinalFrame_NewFrame(object sender, NewFrameEventArgs eventArgs) // must be void so that it can be accessed everywhere.
// New Frame Event Args is an constructor of a class
{
pictureBox1.Image = (Bitmap)eventArgs.Frame.Clone();// clone the bitmap
}
private void From1_CLosing(object sender, EventArgs e)
{
if (FinalFrame.IsRunning==true) FinalFrame.Stop();
}
private void save_Click(object sender, EventArgs e)
{
if (pictureBox2.Image != null)
{
Bitmap varBmp = new Bitmap(pictureBox2.Image);
Bitmap newBitmap = new Bitmap(varBmp);
varBmp.Dispose();
varBmp = null;
varBmp.Save(#"C:\a.png", ImageFormat.Png);
}
else
{ MessageBox.Show("null exception"); }
}
private void clone_Click(object sender, EventArgs e)
{
pictureBox2.Image = (Bitmap)pictureBox1.Image.Clone();
}
}
}
Any AForge.net user can just PRESS the LINK below and try it out. Thanks!
SAMPLE
After having a look at your code, to me it appears that you are disposing of your image right before you save it. Meaning that your program can't save the image, because it doesn't exist anymore. Actually it reads that you've essentially removed the captured image twice, once on dispose, the second when you set it as null.
So if you move the two code segments after the save, it should be working. Granted without using a dialog box to change the name of the file, you'll surely receive an error unless you remove that file after each time it has been created.
private void save_Click(object sender, EventArgs e)
{
if (pictureBox2.Image != null)
{
//Save First
Bitmap varBmp = new Bitmap(pictureBox2.Image);
Bitmap newBitmap = new Bitmap(varBmp);
varBmp.Save(#"C:\a.png", ImageFormat.Png);
//Now Dispose to free the memory
varBmp.Dispose();
varBmp = null;
}
else
{ MessageBox.Show("null exception"); }
}
If you open the task manager, you can watch how much memory your program is soaking up.
Disposing of the memory after you're done using it, gives it back to the system.
You don't have a dispose inside your FinalFrame_NewFrame thread, so when the camera is reading images,
you should see the memory usage continue to climb until you stop the program.
I've added dispose to my thread, putting the memory usage under control, but now I'm debugging my image saves. Because I'm disposing, I can't save the image lol. My program ends up trying to save a null image file and throws the appropriate error.
I'm using a 2nd picurebox just as you are, but using for example, pbox2.image = pbox1.image, doesn't copy the data, it copies the memory location with the image data, so when I dispose pbox1 to free memory, the image data disappears with the memory location.
So, I had the same issue, and it was resolved one, by moving the dispose method, and two, I had to change the path, it didnt want to save to C:, so I put it on my desktop, you may not have had this issue if you were running as admin but I did so for anyone else who sees this, dont save to the root of C:.

nullReferenceException when i try to play a sound effect?

I'm making a soundboard with sound effects and I'm getting :
"A first chance exception of type 'System.NullReferenceException'"
when building after 'UI Task' (Managed):
Loaded 'Microsoft.Xna.Framework.dll'
I did have it working but after changes (overwrote previous version) I have been getting this error and I'm stuck. Java is my first language and with C# I'm a beginner. I have spent countless hours looking for a solution.
The nullReferenceException is coming from loadsound(), I think! I have the sound files(.wav) in a folder called resources and build action:resources and copy to output:do not copy(have tried all options here). Also in references a reference was made to Microsoft.Xna.Framework
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Resources;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Media;
namespace Craggy_Island
{
public partial class MainPage : PhoneApplicationPage
{
// The Resources to play
private SoundEffect drink;//(plus 23 more effects)
// Flag that indicates if we need to resume Zune playback upon exiting.
bool resumeMediaPlayerAfterDone = false;
// Constructor
public MainPage()
{
InitializeComponent();
// Timer to simulate the XNA game loop (SoundEffect class is from the XNA Framework)
GameTimer gameTimer = new GameTimer();
gameTimer.UpdateInterval = TimeSpan.FromMilliseconds(33);
// Call FrameworkDispatcher.Update to update the XNA Framework internals.
gameTimer.Update += delegate { try { FrameworkDispatcher.Update(); } catch { } };
// Start the GameTimer running.
gameTimer.Start();
// Prime the pump or we'll get an exception.
FrameworkDispatcher.Update();
//LoadSound("Resources/drink.wav", out drink);
// Create and load SoundEffect objects.
LoadSound("Resources/drink.wav", out drink);
}
private void LoadSound(String SoundFilePath, out SoundEffect Sound)
{
// For error checking, assume we'll fail to load the file.
Sound = null;
try
{
// Holds informations about a file stream.
StreamResourceInfo SoundFileInfo = App.GetResourceStream(new Uri(SoundFilePath, UriKind.Relative));
// Create the SoundEffect from the Stream
Sound = SoundEffect.FromStream(SoundFileInfo.Stream);
}
catch (NullReferenceException)
{
// Display an error message
MessageBox.Show("Couldn't load sound " + SoundFilePath);
}
}
private void button_Click(object sender, RoutedEventArgs e)
{
Button Current = sender as Button;
try
{
if (Current.Equals(button1))
drink.Play();//(other buttons here for other sound effects)
}
catch (NullReferenceException)
{
MessageBox.Show("Can't play, sound file problem.");
}
}
#region Zune Pause/Resume
private void ZunePause()
{
// Please see the MainPage() constructor above where the GameTimer object is created.
// This enables the use of the XNA framework MediaPlayer class by pumping the XNA FrameworkDispatcher.
// Pause the Zune player if it is already playing music.
if (!MediaPlayer.GameHasControl)
{
MediaPlayer.Pause();
resumeMediaPlayerAfterDone = true;
}
}
private void ZuneResume()
{
// If Zune was playing music, resume playback
if (resumeMediaPlayerAfterDone)
{
MediaPlayer.Resume();
}
}
#endregion Zune Pause/Resume
}
}
Scrap my original answer unless you're using XNA for game development on Windows/Xbox. (Original poster is using it for the Zune.)
Regarding the WAV file:
First problem is that you need to set Copy to Output Directory to Copy if newer. (You could use Always, but that would be unnecessary.)
Second problem is that its type needs to be set to Content.
You are taking the hard approach. Look into ContentManager (accessible as this.Content from within the Game instance). You can use Content.Load<T>(string) to access your audio file, but you'll need to put the audio file in the content project. Don't change its type: leave it at the default. Even it's not a resource, leave it be. It will be compiled into a different format. Also, omit the file extension from the parameter passed to Content.Load<>.
You are starting the game before you are loading the sound:
gameTimer.Start();
FrameworkDispatcher.Update();
LoadSound("Resources/drink.wav", out drink);
I had almost the same problem. Finally I got it accidently as follows:
StreamResourceInfo streaminfo = Application.GetResourceStream(new Uri("project_name;component/folder_name/Sound3.wav", UriKind.RelativeOrAbsolute));
SoundEffect effect1 = SoundEffect.FromStream(streaminfo.Stream);
effect1.Play();
AND:
the Property "Build Action" of the .wav file must be setted to "Resource" and the Porperty "Copy to Output Directory" should be setted to "Copy if newer"
By the way, I´m working with Silverlight5.

Categories

Resources