C# 无法将类型“System.Drawing.Image”隐式转换为“System.Drawing.Bitmap”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8860725/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 04:50:44  来源:igfitidea点击:

Cannot implicitly convert type 'System.Drawing.Image' to 'System.Drawing.Bitmap'`

c#.netbitmap

提问by Ozarraga_AB

Declared a bitmap which was

声明了一个位图

private Bitmap img1 = null;  
private Bitmap img2 = null;  

the image will be putted after selecting it from openFileDialog.
the selected images were placed in an array.

openFileDialog 中选择图像后,图像将被放置。
选定的图像被放置在一个数组中。

imgName = openFD.FileNames;

then button1 to display these image.

然后 button1 显示这些图像。

pictureBox1.Image = Image.FromFile(imgName[0]);  
pictureBox2.Image = Image.FromFile(imgName[1]);

i replaced the button1 code with this

我用这个替换了 button1 代码

img1 = Image.FromFile(imgName[0]);  
img2 = Image.FromFile(imgName[1]);

but an error occurs

但发生错误

Cannot implicitly convert type 'System.Drawing.Image' to 'System.Drawing.Bitmap'

无法将类型“System.Drawing.Image”隐式转换为“System.Drawing.Bitmap”

I'd try to change the code to img1 = Bitmap.FromFile(imgName[0]);. but still has the same error.
Any suggestion how to correct or do this right?

我会尝试将代码更改为img1 = Bitmap.FromFile(imgName[0]);. 但仍然有同样的错误。
任何建议如何纠正或正确执行此操作?

采纳答案by icktoofay

img1 = new Bitmap(imgName[0]);
img2 = new Bitmap(imgName[1]);

回答by Haris Hasan

img1 = (Bitmap) Image.FromFile(imgName[0]);
img2 = (Bitmap) Image.FromFile(imgName[1]);

As the error message says you cannot implicitly do this you need to explicitly cast it to Bitmap

由于错误消息说您不能隐式执行此操作,因此您需要将其显式转换为 Bitmap

Edit

编辑

Based on the comments below I would suggest either go with icktoofay's answer i.e. use the Bitmap constructor or if you can use the Image class directly instead of using Bitmap you can also go with that

根据下面的评论,我建议要么使用 icktoofay 的答案,即使用 Bitmap 构造函数,或者如果您可以直接使用 Image 类而不是使用 Bitmap,您也可以使用它

回答by TEHSEEN

I have used these three lines in my code to assing byte value to image in c#.

我在我的代码中使用了这三行来将字节值分配给 c# 中的图像。

ImageConverter converter = new ImageConverter();
pbStudentPicture.Image =  (Image)converter.ConvertFrom(StudentPinfo.Picture);
pbStudentPicture.SizeMode = PictureBoxSizeMode.StretchImage;