c#.Object引用未设置为对象的实例。 [英] c#.Object reference not set to an instance of an object.

查看:123
本文介绍了c#.Object引用未设置为对象的实例。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须比较两张图片的高度和宽度我正在调整第一张图片的高度和宽度,如下所示:

i have to compare height and width of two images i am geeting height and width of first images as follow :

public int imageWidth()
        {




            {

                int w=0;
                w = pictureBox1.Image.Width;
                return w;

            }
        }
        public int imageheight()
        {
            int h=0;
           h = pictureBox1.Image.Height;
            return h;

        }



和我正在使用的secode类。

CreateSheet cs = new CreateSheet();

if(bmp.Width!= cs.imageWidth()&& bmp.Height!= cs.imageheight())

{

MessageBox.Show(两个图像的宽度和高度不相等);

ImageResize(bmp,cs.imageWidth(),cs.imageheight());



}

但是geeting exception

对象引用未设置为对象的实例。 at line:


and in secode class i am using.
CreateSheet cs = new CreateSheet();
if (bmp.Width != cs.imageWidth() && bmp.Height != cs.imageheight())
{
MessageBox.Show("width and height of both images are not equal");
ImageResize(bmp,cs.imageWidth(),cs.imageheight());

}
but geeting exception
Object reference not set to an instance of an object. at line :

w = pictureBox1.Image.Width; how it can be solved??

             return w;

推荐答案

什么关于PictureBox中没有加载图片?即 pictureBox1.Image 为null,因此您无法访问其width属性。

顺便说一句,您不需要将图像加载到PictureBox中以获得其大小。 Image和Bitmap类也有这些属性。
What about no Image loaded in the PictureBox? I.e. pictureBox1.Image is null, and consequently you cannot acces its width property.
By the way, you do not need to load an image into a PictureBox to get its size. The Image and Bitmap classes have these properties too.


是的,在使用之前检查Null也是为了避免异常,你也可以对你分配给Picture Box的图像进行非空检查



public int imageWidth()

{

{



int w = 0;

if(pictureBox1 && pictureBox1.Image)

w = pictureBox1.Image.Width;

返回w;



}

}

public int imageheight()

{

int h = 0;

if(pictureBox1 && pictureBox1.Image)

h = pictureBox1.Image.Height;

return h;



}
Yes check Null before using also in order to avoid exception you can also put not null check on image you are assigning to Picture Box

public int imageWidth()
{
{

int w=0;
if(pictureBox1&&pictureBox1.Image)
w = pictureBox1.Image.Width;
return w;

}
}
public int imageheight()
{
int h=0;
if(pictureBox1&&pictureBox1.Image)
h = pictureBox1.Image.Height;
return h;

}


这篇关于c#.Object引用未设置为对象的实例。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆