Click here to Skip to main content
15,867,834 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello
As a beginner in C # I ask for your help in the following: in a registration form I have a Picturebox to select the logo to load an image file through OpenFileDialog no problem but when you do not select any image file it gives the error System .NullReferenceException img was null.
I really appreciate any help, teaching that helps me to overcome this error.

What I have tried:

C#
{
    using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "JPEG|*.jpg", ValidateNames = true, Multiselect = false })
    {
        if (ofd.ShowDialog() == DialogResult.OK)
        {
            fileName = ofd.FileName;
            lblFileName.Text = File.ReadAllText(ofd.FileName);
            pictureBox.Image = Image.FromFile(fileName);
        }
    }
}
byte[] ConvertImageToBinary(Image img)
    {
        using (MemoryStream ms = new MemoryStream())
        {
            img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);**//erro aqui**
            return ms.ToArray();
        }
    } 
Posted
Updated 23-Mar-21 0:40am

The simplest solution is to use a "neutral" default image and set your PictureBox to that: A blank "head" much like the standard MS one: https://winaero.com/blog/wp-content/uploads/2015/05/user-200.png[^]
That way, the use will always have an image, even if it is boring, dull, and banal.

And your code will know that, so nowhere in it do you need to check ...
 
Share this answer
 
Comments
miguel santos 2021 20-Mar-21 5:40am    
Thanks for the solution presented, but this image is part of a field of crystal reports but I can also put a white image with nothing, just blank color
OriginalGriff 20-Mar-21 5:53am    
So use a blank, white image ...
miguel santos 2021 20-Mar-21 6:09am    
kkkkkkk ok many thanks; but is it not possible to do this through C #?
Sorry my curiosity
OriginalGriff 20-Mar-21 6:43am    
That's kinda difficult to say: you can do it in C# by checking the Image property for null everywhere you try to use it, but if You miss one and don;t test it, it will crash in production.
Similarly, if CR doesn't check for a null value when you try to use that to display it, it could crash - hence the "difficult to say" bit, I avoid CR like COVID-19! :laugh:

You do know what a "null reference exception" is, don't you?
miguel santos 2021 24-Mar-21 3:03am    
sorry for my late reply but in my country was hollydy untill today thanks fpo you help brother
Simple: check whether the image is null, and return a suitable default in that case. For example:
C#
byte[] ConvertImageToBinary(Image img)
{
    if (img is null) return Array.Empty<byte>();
    
    using (MemoryStream ms = new MemoryStream())
    {
        img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
        return ms.ToArray();
    }
} 
If an empty byte array doesn't work, try a single-pixel transparent GIF:
graphics - smallest filesize for transparent single pixel image - Stack Overflow[^]
C#
if (img is null)
{
    return new byte[]
    {
        0x47, 0x49, 0x46, 0x38, 0x37, 0x61, 0x01, 0x00, 0x01, 0x00, 0x80, 0x01, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
        0x00, 0x00, 0x2C, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x02, 0x02, 0x44, 0x01
    };
}
(You should cache the default image byte array in a private static readonly field, so that you don't have to create a new array each time.)
 
Share this answer
 
Comments
miguel santos 2021 24-Mar-21 3:35am    
thank you so much for your help and sorry for my ignorance but how do i??"(You should cache the default image byte array in a private static readonly field, so that you don't have to create a new array each time.)"many thanks again
Richard Deeming 24-Mar-21 5:11am    
Create a readonly static field to store the default image:
public class YourClass
{
    private static readonly byte[] EmptyImage = new byte[]
    {
        0x47, 0x49, 0x46, 0x38, 0x37, 0x61, 0x01, 0x00, 0x01, 0x00, 0x80, 0x01, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
        0x00, 0x00, 0x2C, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x02, 0x02, 0x44, 0x01
    };

Then use that field in your method:
if (img is null) return EmptyImage;
miguel santos 2021 24-Mar-21 6:20am    
sorry brother but you are always giving the error here ** pictureBox.Image = Image.FromFile (dataGridView1.SelectedRows [0] .Cells ["dgFileName"]. Value.ToString ()); ** when compiling, can I please I give you the code so that you can help me correct the error and I can learn from you? thank you so much again for your patience
Richard Deeming 24-Mar-21 6:30am    
That's not the code in your question, and you haven't provided any details of the error you're getting.
miguel santos 2021 24-Mar-21 6:46am    
if the image is null when I insert the record it gives the error ** System.ArgumentException: 'The path does not have a legal format.' ** in ** pictureBox.Image = Image.FromFile (dataGridView1.SelectedRows [0] .Cells [ "dgFileName"]. Value.ToString ());
insert record with image ** without errors **
if I make changes to the registry and eliminate only the error image ** System.NullReferenceException: 'The object reference was not defined as an instance of an object.'
img was null. ** in ** img.Save (ms, ImageFormat.Jpeg); ** again thank you very much for your help

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900